Skip to content
← Back

src/syntax/process/printer/formatter_statements.ghul

1
namespace Syntax.Process.Printer is
2
use Collections
3
4
use Trees
5
use Source
6
7
use Lexical.TRIVIA
8
9
10
// Statement and case formatting: lists, blocks, lets, if statements and expressions,
11
// refutable bindings, for loops and case arms.
12
partial FORMATTER is
13
14
// --- definition / statement lists: leading-trivia interleaving ---
15
16
// A file with no namespace can carry bare statements at its root
17
// (synthesise-top-level-entry consumes them into a global entry
18
// point before declare-symbols), interleaved with global
19
// definitions in source order - GHUL.md: "may be interleaved with
20
// global definitions, which are visible regardless of where they
21
// appear." `definitions` and `top_level_statements` are two
22
// separately-ordered runs, so a formatter that rendered every
23
// definition before every statement would silently reorder the
24
// file. Walk both by source position instead.
25
visit(definitions: Definitions.LIST) is
26
// A file-level pragma comes before everything else in the file,
27
// written as its ordinary form behind a second `@`.
28
if let file_pragmas = definitions.file_pragmas then
29
for pragma in file_pragmas do
30
flush_leading(pragma.location.start)
31
write("@")
32
pragma.accept(self)
33
write_line()
34
od
35
fi
36
37
let items = LIST[Trees.Node]()
38
39
for d in definitions do
40
items.add(d)
41
od
42
43
if let statements = definitions.top_level_statements then
44
for s in statements do
45
items.add(s)
46
od
47
fi
48
49
items.sort((a, b) => a.location.start - b.location.start)
50
51
let first mut = true
52
53
for item in items do
54
flush_leading(item.location.start)
55
56
// Nothing has been written yet before the very first item
57
// (the root Definitions.LIST is visited before anything
58
// else), so `at_line_start` is still at its unset default
59
// there - only break between items, never before the first.
60
if !first /\ !at_line_start then
61
write_line()
62
fi
63
64
item.accept(self)
65
66
first = false
67
68
if let variable: Variables.VARIABLE = item then
69
if let variable.name? /\ name.name.starts_with("$") then
70
write_terminator()
71
fi
72
fi
73
od
74
si
75
76
visit(list: Statements.LIST) is
77
for s in list do
78
// A statement ending in a block terminator leaves the line open,
79
// and running the next statement onto it produces source that no
80
// longer parses - `odwrite_line(...)`.
81
if !at_line_start then
82
write_line()
83
fi
84
85
flush_leading(s.location.start)
86
s.accept(self)
87
od
88
si
89
90
visit(block: Bodies.BLOCK) is
91
// An empty body renders on the header's line - `init() is si` -
92
// rather than splitting over two. A body carrying comments keeps
93
// the general path so they stay inside the block.
94
if block.statements.is_empty /\ ! _has_trivia_before(block.location.end) then
95
write("is si")
96
return
97
fi
98
99
write_line("is")
100
indent()
101
102
// A final statement that reached the body terminator without
103
// its `;` is an implicit tail return: it renders as a bare
104
// expression, since printing the `;` would turn the return
105
// back into a discarded statement.
106
let tail_expression: Trees.Expressions.Expression? mut = null
107
108
if !block.statements.last_was_terminated then
109
if let l = block.statements.last then
110
if let te = cast Statements.EXPRESSION?(l) then
111
tail_expression = te.expression
112
fi
113
fi
114
fi
115
116
if let te = tail_expression then
117
let items = LIST[Statements.Statement]()
118
119
for s in block.statements do
120
items.add(s)
121
od
122
123
let i mut = 0
124
while i < items.count - 1 do
125
// A statement ending in a block terminator leaves the
126
// line open, and the next statement's leading comment
127
// would be written onto it. So the break comes before
128
// the flush, as it does in visit(Statements.LIST).
129
if ! at_line_start then
130
write_line()
131
fi
132
133
flush_leading(items[i].location.start)
134
items[i].accept(self)
135
i = i + 1
136
od
137
138
if ! at_line_start then
139
write_line()
140
fi
141
142
flush_leading(items[items.count - 1].location.start)
143
te.accept(self)
144
write_line("")
145
else
146
block.statements.accept(self)
147
fi
148
149
// The last statement may have ended in a block terminator of its
150
// own, leaving the line open: `si` must not run onto it.
151
if !at_line_start then
152
write_line()
153
fi
154
155
flush_leading(block.location.end)
156
outdent()
157
write("si")
158
si
159
160
// --- visits the plain printer never implemented ---
161
162
visit(let_in: Expressions.LET_IN) is
163
note(let_in.location)
164
write("let ")
165
if let_in.want_dispose then
166
write("use ")
167
fi
168
let_in.variables.accept(self)
169
write(" in ")
170
let_in.expression.accept(self)
171
si
172
173
visit(assert_in: Expressions.ASSERT_IN) is
174
note(assert_in.location)
175
write("assert ")
176
assert_in.condition.accept(self)
177
if assert_in.message? then
178
write(" else ")
179
assert_in.message!.accept(self)
180
fi
181
write(" in ")
182
assert_in.expression.accept(self)
183
si
184
185
visit(recurse: Expressions.RECURSE) is
186
note(recurse.location)
187
write("rec")
188
si
189
190
// --- faithfulness fix: an `if ... fi` in expression position is
191
// Expressions.STATEMENT wrapping Statements.IF. The inherited
192
// visit renders the statement form — `;`-terminated branch
193
// bodies plus a trailing `;` — which is invalid in expression
194
// position. Render the expression form instead. ---
195
196
visit(statement: Expressions.STATEMENT) is
197
note(statement.location)
198
199
if let if_statement: Statements.IF = statement.statement then
200
emit_if_expression(if_statement)
201
elif let case_statement: Statements.CASE = statement.statement then
202
emit_case_expression(case_statement)
203
elif let for_statement: Statements.FOR = statement.statement then
204
emit_for_expression(for_statement)
205
elif let do_statement: Statements.DO = statement.statement then
206
emit_do_expression(do_statement)
207
elif let throw_statement: Statements.THROW = statement.statement then
208
// `=> throw E` stubs a diverging body. The statement form
209
// writes its own `;`, which the member's `after_body` would
210
// duplicate - render the expression form instead.
211
write("throw")
212
if throw_statement.expression? then
213
write(" ")
214
throw_statement.expression.accept(self)
215
fi
216
else
217
statement.statement.accept(self)
218
fi
219
si
220
221
// `val ... lav` block expression. The keyword pair is load-
222
// bearing; each statement renders normally (with its own `;`)
223
// and the surrounding context decides whether the block's value
224
// is consumed.
225
visit(block: Expressions.VAL_BLOCK) is
226
note(block.location)
227
228
if block.is_parenthesised then
229
write_line("(")
230
indent()
231
block.body.accept(self)
232
outdent()
233
write(")")
234
else
235
write_line("val")
236
indent()
237
block.body.accept(self)
238
outdent()
239
write("lav")
240
fi
241
si
242
243
// --- faithfulness fix: the inherited visit(Statements.LET) never
244
// emits the `use` disposal keyword, so `let use x = e` round-trips
245
// to `let x = e`, silently dropping the disposal. ---
246
247
visit(l: Statements.LET) is
248
write("let ")
249
250
if l.want_dispose then
251
write("use ")
252
fi
253
254
_in_let = true
255
l.variables.accept(self)
256
_in_let = false
257
write_terminator()
258
si
259
260
// --- faithfulness fix: the inherited visit(Statements.IF) ignores a
261
// branch binding, so `if let v = e then` renders as a bare `else`
262
// with the binding dropped. ---
263
264
visit(if_statement: Statements.IF) is
265
note(if_statement.location)
266
267
let branches = LIST[Statements.IF_BRANCH]()
268
for b in if_statement.branches do
269
branches.add(b)
270
od
271
272
let first mut = true
273
let i mut = 0
274
for branch in branches do
275
// The previous branch ended with a statement that may
276
// itself have closed a block, leaving the line open:
277
// `elif` and `else` must not run onto it.
278
if !first /\ !at_line_start then
279
write_line()
280
fi
281
282
if let branch.binding? then
283
if first then
284
write("if let ")
285
else
286
write("elif let ")
287
fi
288
binding.accept(self)
289
if let branch.condition? then
290
write(" /\\ ")
291
condition.accept(self)
292
fi
293
write_line(" then")
294
elif let branch.condition? then
295
if first then
296
write("if ")
297
else
298
write("elif ")
299
fi
300
condition.accept(self)
301
write_line(" then")
302
else
303
write_line("else")
304
fi
305
306
indent()
307
branch.body.accept(self)
308
309
// A comment after the branch's last statement belongs inside
310
// the branch: consume it while still indented, or it is
311
// emitted after the `fi` - or, ahead of the next clause's
312
// keyword, trails that keyword's line instead.
313
flush_leading(
314
if i + 1 < branches.count then
315
branches[i + 1].location.start
316
else
317
if_statement.location.end
318
fi)
319
320
outdent()
321
322
first = false
323
i = i + 1
324
od
325
326
// The last branch's body may have ended in a block terminator
327
// of its own, leaving the line open: `fi` must not run onto it.
328
if !at_line_start then
329
write_line()
330
fi
331
332
write_line("fi")
333
si
334
335
// --- the REFUTABLE_BINDING node carries the `pattern[: T] =
336
// scrutinee[ /\ guard]` shape that drives an `if let` arm,
337
// or the leaf-name shorthand `path?` / `path: T` when the
338
// variable name was inferred from the path. The `if let ` /
339
// `elif let ` keyword is emitted by the surrounding
340
// visit(Statements.IF); this renders the clause payload
341
// only. ---
342
343
visit(rb: Statements.REFUTABLE_BINDING) is
344
note(rb.location)
345
346
let first mut = true
347
348
for c in rb.clauses do
349
if !first then
350
write(", ")
351
fi
352
353
if c.is_inferred_name then
354
c.scrutinee.accept(self)
355
356
if let c.narrow_type_expression? then
357
write(": ")
358
narrow_type_expression.accept(self)
359
else
360
write("?")
361
fi
362
else
363
c.pattern.accept(self)
364
365
if let c.narrow_type_expression? then
366
write(": ")
367
narrow_type_expression.accept(self)
368
fi
369
370
write(" = ")
371
c.scrutinee.accept(self)
372
fi
373
374
if let c.guard? then
375
write(" /\\ ")
376
guard.accept(self)
377
fi
378
379
first = false
380
od
381
si
382
383
// --- faithfulness fix: the inherited visit(Statements.FOR) emits
384
// `for` with a trailing newline, stranding it on its own line. ---
385
386
visit(for_statement: Statements.FOR) is
387
note(for_statement.location)
388
389
write("for ")
390
391
let variable = for_statement.variable
392
if variable? then
393
variable.accept(self)
394
fi
395
396
write(" in ")
397
398
let expression = for_statement.expression
399
if expression? then
400
expression.accept(self)
401
fi
402
403
write_line(" do")
404
405
indent()
406
407
let body = for_statement.body
408
if body? then
409
body.accept(self)
410
fi
411
412
// A comment after the body's last statement belongs inside the
413
// loop: consume it while still indented, or it is emitted after
414
// the `od`.
415
flush_leading(for_statement.location.end)
416
417
outdent()
418
419
// Nested blocks each end with their own terminator, and the inner
420
// one leaves the line open: `od` must not run onto it.
421
if !at_line_start then
422
write_line()
423
fi
424
425
write("od")
426
si
427
428
// The base visit renders the statement form but never consumes the
429
// trivia queue, so a comment trailing the body is emitted after the
430
// `od` rather than inside the loop.
431
visit(`do: Statements.DO) is
432
note(`do.location)
433
434
if let `do.binding? then
435
write("while let ")
436
binding.accept(self)
437
write(" ")
438
elif let `do.condition? then
439
write("while ")
440
condition.accept(self)
441
write(" ")
442
fi
443
444
write_line("do")
445
indent()
446
`do.body.accept(self)
447
448
// A comment after the body's last statement belongs inside the
449
// loop: consume it while still indented, or it is emitted after
450
// the `od`.
451
flush_leading(`do.location.end)
452
453
outdent()
454
455
// Nested blocks each end with their own terminator, and the inner
456
// one leaves the line open: `od` must not run onto it.
457
if !at_line_start then
458
write_line()
459
fi
460
461
write_line("od")
462
si
463
464
// The base visit renders the statement form but never consumes the
465
// trivia queue, so a comment trailing a body is emitted after the
466
// `yrt` - or, ahead of a `catch` or `finally` keyword, trails that
467
// keyword's line - rather than staying in the body it was written in.
468
visit(`try: Statements.TRY) is
469
note(`try.location)
470
471
write_line("try")
472
indent()
473
`try.body.accept(self)
474
475
let catches = LIST[Statements.CATCH]()
476
for c in `try.catches do
477
catches.add(c)
478
od
479
480
flush_leading(next_clause_start(`try, catches, 0))
481
482
outdent()
483
484
let i mut = 0
485
for c in catches do
486
// The body may have ended in a nested block, whose own
487
// terminator leaves the line open: `catch` must not run
488
// onto it, as the `yrt` below does not.
489
if !at_line_start then
490
write_line()
491
fi
492
493
write("catch ")
494
495
if let c.variable? then
496
variable.accept(self)
497
fi
498
write_line()
499
500
indent()
501
c.body.accept(self)
502
503
flush_leading(next_clause_start(`try, catches, i + 1))
504
505
outdent()
506
507
i = i + 1
508
od
509
510
let `finally = `try.`finally
511
512
if `finally? then
513
if !at_line_start then
514
write_line()
515
fi
516
517
write_line("finally")
518
indent()
519
`finally.accept(self)
520
521
// A comment after the last statement of the finally body
522
// belongs inside it: consume it while still indented, or it
523
// is emitted after the `yrt`.
524
flush_leading(`try.location.end)
525
526
outdent()
527
fi
528
529
if !at_line_start then
530
write_line()
531
fi
532
533
write_line("yrt")
534
si
535
536
// The position a body's trailing trivia is flushed against: the next
537
// `catch` clause when one follows, the `finally` body if the next
538
// thing is a finally, and the end of the try otherwise.
539
next_clause_start(`try: Statements.TRY, catches: LIST[Statements.CATCH], next: int) -> int is
540
if next < catches.count then
541
return catches[next].location.start
542
fi
543
544
let `finally = `try.`finally
545
546
if `finally? then
547
return `finally.location.start
548
fi
549
550
return `try.location.end
551
si
552
553
emit_if_expression(if_statement: Statements.IF) is
554
_builder.begin_group()
555
556
let first mut = true
557
for branch in if_statement.branches do
558
if !first /\ !at_line_start then
559
_builder.line()
560
fi
561
562
// Trivia (a comment, a blank line) between one branch's
563
// last statement and the next branch's keyword has to be
564
// consumed here - otherwise it stays in the trivia queue
565
// and surfaces later, wherever the next flush_leading
566
// happens to land.
567
if !first then
568
flush_leading(branch.location.start)
569
fi
570
571
if let branch.binding? then
572
if first then
573
write("if let ")
574
else
575
write("elif let ")
576
fi
577
binding.accept(self)
578
if let branch.condition? then
579
write(" /\\ ")
580
condition.accept(self)
581
fi
582
write(" then")
583
elif let branch.condition? then
584
if first then
585
write("if ")
586
else
587
write("elif ")
588
fi
589
condition.accept(self)
590
write(" then")
591
else
592
write("else")
593
fi
594
595
_builder.begin_nest(4)
596
_builder.line()
597
emit_branch_value(branch.body)
598
599
// A statement arm - a `return`, say - writes its own line
600
// break. The soft break that separates it from the next
601
// keyword would then be a second one, and the blank line
602
// it leaves comes back as another on every reformat.
603
_builder.end_nest()
604
605
first = false
606
od
607
608
flush_leading(if_statement.location.end)
609
610
if !at_line_start then
611
_builder.line()
612
fi
613
614
write("fi")
615
_builder.end_group()
616
si
617
618
// Emit an if-expression branch body. The branch's value is its last
619
// bare expression (no `;`); any leading statements render
620
// normally.
621
emit_branch_value(body: Statements.LIST) is
622
let statements = LIST[Statements.Statement]()
623
for s in body do
624
statements.add(s)
625
od
626
627
let i mut = 0
628
while i < statements.count do
629
let s = statements[i]
630
let is_last = i == statements.count - 1
631
632
// Leading trivia (blank lines, comments) between arm-body
633
// statements has to be consumed here, in place - otherwise
634
// it stays in the trivia queue and surfaces later, at
635
// whichever definition or statement next calls
636
// flush_leading, stacking with whatever blank line already
637
// belongs there.
638
// A statement ending in a block terminator - an arm body's
639
// `od` - leaves the line open, and the next statement's
640
// leading comment would be written onto it, so the break
641
// comes first. The arm's own opening break is a soft one,
642
// which `at_line_start` does not see, so this asks only
643
// about a break the previous statement should have left.
644
if i > 0 /\ !at_line_start then
645
write_line()
646
fi
647
648
flush_leading(s.location.start)
649
650
// A tail statement can itself be an if/case/for/do used as
651
// a value (implicit tail return). Each of those has its own
652
// no-trailing-terminator expression renderer, matching the
653
// dispatch in visit(Expressions.STATEMENT); the ordinary
654
// statement-form renderers (`visit(Statements.IF)` and
655
// friends) are for a statement in statement position, and
656
// terminate their own line.
657
if is_last /\ isa Statements.EXPRESSION(s) then
658
let expression_statement = cast Statements.EXPRESSION(s)
659
expression_statement.expression.accept(self)
660
elif is_last /\ isa Statements.IF(s) then
661
emit_if_expression(cast Statements.IF(s))
662
elif is_last /\ isa Statements.CASE(s) then
663
emit_case_expression(cast Statements.CASE(s))
664
elif is_last /\ isa Statements.FOR(s) then
665
emit_for_expression(cast Statements.FOR(s))
666
elif is_last /\ isa Statements.DO(s) then
667
emit_do_expression(cast Statements.DO(s))
668
else
669
s.accept(self)
670
fi
671
i = i + 1
672
od
673
si
674
675
// Loop expressions render like their statement forms but end at
676
// the closing keyword with no trailing `;` — the consuming
677
// context owns statement termination — and the body's value is
678
// its last bare expression, as in an if-expression branch.
679
emit_for_expression(for_statement: Statements.FOR) is
680
write("for ")
681
682
if let for_statement.variable? then
683
variable.accept(self)
684
fi
685
686
write(" in ")
687
688
if let for_statement.expression? then
689
expression.accept(self)
690
fi
691
692
write_line(" do")
693
indent()
694
695
if let for_statement.body? then
696
body.accept(self)
697
fi
698
699
outdent()
700
701
// Nested blocks each end with their own terminator, and the inner
702
// one leaves the line open: `od` must not run onto it.
703
if !at_line_start then
704
write_line()
705
fi
706
707
write("od")
708
si
709
710
emit_do_expression(do_statement: Statements.DO) is
711
if let do_statement.binding? then
712
write("while let ")
713
binding.accept(self)
714
write(" ")
715
elif let do_statement.condition? then
716
write("while ")
717
condition.accept(self)
718
write(" ")
719
fi
720
721
write_line("do")
722
indent()
723
do_statement.body.accept(self)
724
outdent()
725
726
// Nested blocks each end with their own terminator, and the inner
727
// one leaves the line open: `od` must not run onto it.
728
if !at_line_start then
729
write_line()
730
fi
731
732
write("od")
733
si
734
735
// --- faithfulness fix: `case` statement / expression. The base
736
// printer emits a legacy `when X :` / `default` / `esac`
737
// shape; the parser accepts only `when X then` / `else` /
738
// `esac`. Binding-pattern arms (`when v: int then`) and
739
// literal-leaf patterns live on the arm's `pattern` field
740
// rather than its `expressions` list and must be emitted
741
// from there. ---
742
743
visit(`case: Statements.CASE) is
744
emit_case_header(`case)
745
746
let i mut = 0
747
for m in `case.matches do
748
// A comment after an arm's last statement belongs inside the
749
// arm: bound the flush by the next arm's keyword (or the
750
// `esac`), or it trails the next keyword's line.
751
let limit =
752
if i + 1 < `case.matches.count then
753
`case.matches[i + 1].location.start
754
else
755
`case.location.end
756
fi
757
758
emit_case_match_at(m, false, limit)
759
i = i + 1
760
od
761
762
// An arm ending in a nested block leaves the line open after
763
// that block's terminator: `esac` must not run onto it.
764
if !at_line_start then
765
write_line()
766
fi
767
768
write_line("esac")
769
si
770
771
visit(match: Statements.CASE_MATCH) is
772
emit_case_match_at(match, false, match.location.end)
773
si
774
775
emit_case_header(case_statement: Statements.CASE) is
776
note(case_statement.location)
777
write("case ")
778
case_statement.expression.accept(self)
779
write_line()
780
si
781
782
emit_case_match_at(match: Statements.CASE_MATCH, as_expression: bool, limit: int) is
783
note(match.location)
784
785
if let match.pattern? then
786
write("when ")
787
pattern.accept(self)
788
789
if let match.guard? then
790
write(" /\\ ")
791
guard.accept(self)
792
fi
793
794
write_line(" then")
795
elif match.expressions? then
796
write("when ")
797
let first mut = true
798
for e in match.expressions! do
799
if !first then
800
write(", ")
801
fi
802
e.accept(self)
803
first = false
804
od
805
write_line(" then")
806
else
807
write_line("else")
808
fi
809
810
indent()
811
812
if as_expression then
813
emit_branch_value(match.statements)
814
write_line()
815
else
816
match.statements.accept(self)
817
fi
818
819
// A comment after the arm's last statement belongs inside the
820
// arm: consume it while still indented, or it is emitted after
821
// the `esac` - or trails the next arm keyword's line.
822
flush_leading(limit)
823
824
outdent()
825
si
826
827
emit_case_expression(case_statement: Statements.CASE) is
828
emit_case_header(case_statement)
829
830
let i mut = 0
831
for m in case_statement.matches do
832
let limit =
833
if i + 1 < case_statement.matches.count then
834
case_statement.matches[i + 1].location.start
835
else
836
case_statement.location.end
837
fi
838
839
emit_case_match_at(m, true, limit)
840
i = i + 1
841
od
842
843
write("esac")
844
si
845
si
846
si