Skip to content
← Back

src/syntax/process/printer/base.ghul

1
namespace Syntax.Process.Printer is
2
use IO.Std
3
4
use Trees
5
use Source
6
7
class Base : StrictVisitor abstract is
8
_indent: int
9
_depth: int
10
_run_on: bool
11
_indent_needed: bool
12
_want_locations: bool
13
_current_line: int
14
_result: System.Text.StringBuilder
15
16
init(want_locations: bool) is
17
super.init()
18
19
_want_locations = want_locations
20
_depth = 0
21
_indent = 2
22
_result = System.Text.StringBuilder()
23
_current_line = 1
24
si
25
26
result: string => _result.to_string()
27
28
// The statement terminator, as one overridable call. The plain
29
// printer writes it; the formatter, which lays out one statement
30
// per line, marks it instead and drops the ones a line break makes
31
// redundant.
32
write_terminator() is
33
write_line(";")
34
si
35
36
write_line(value: string) is
37
write(value)
38
write_line()
39
si
40
41
write(value: string) is
42
write_indent()
43
_result.append(value)
44
si
45
46
write(c: char) is
47
write_indent()
48
_result.append(c)
49
si
50
51
write_line() is
52
_current_line = _current_line + 1
53
_indent_needed = true
54
_result.append('\n')
55
si
56
57
indent() is
58
_depth = _depth + 1
59
si
60
61
outdent() is
62
_depth = _depth - 1
63
si
64
65
write_indent() is
66
if _indent_needed then
67
let i mut = 0
68
while i < _indent*_depth do
69
_result.append(' ')
70
i = i + 1
71
od
72
_indent_needed = false
73
fi
74
si
75
76
location(node: Node) is
77
location(node.location)
78
si
79
80
location(location: LOCATION) is
81
let new_line = location.start_line
82
if new_line != _current_line then
83
_current_line = new_line
84
if _want_locations then
85
write("#{_current_line} ")
86
fi
87
fi
88
si
89
90
write(node: Node) is
91
node.accept(self)
92
si
93
94
write_name(name: string) is
95
write(name)
96
si
97
98
visit(identifier: Identifiers.Identifier) is
99
location(identifier)
100
write_name(identifier.name)
101
si
102
103
visit(identifier: Identifiers.QUALIFIED) is
104
location(identifier)
105
identifier.qualifier.accept(self)
106
write('.')
107
108
// An operator reached through a qualifier - `use Ghul.Pipes.`>>` -
109
// is an identifier only under its backtick.
110
if Lexical.TOKENIZER.is_operator_name(identifier.name) then
111
write('`')
112
fi
113
114
write_name(identifier.name)
115
si
116
117
visit(modifier: Modifiers.Modifier) is
118
location(modifier)
119
write(modifier.name)
120
si
121
122
visit(modifiers: Modifiers.LIST) is
123
location(modifiers)
124
if let modifiers.access_modifier? then
125
access_modifier.accept(self)
126
write(' ')
127
fi
128
if let modifiers.storage_class? then
129
storage_class.accept(self)
130
write(' ')
131
fi
132
if modifiers.is_abstract then
133
write("abstract ")
134
fi
135
if modifiers.is_pure then
136
write("pure ")
137
fi
138
if modifiers.is_stable then
139
write("stable ")
140
fi
141
si
142
143
visit(variables: Variables.LIST) is
144
location(variables)
145
let first mut = true
146
for v in variables do
147
if !first then
148
write(", ")
149
fi
150
v.accept(self)
151
first = false
152
od
153
si
154
155
visit(definitions: Definitions.LIST) is
156
location(definitions)
157
for d in definitions do
158
d.accept(self)
159
160
// yuck...
161
if isa Variables.VARIABLE(d) then
162
let variable = d
163
if let variable.name? /\ name.name.starts_with("$") then
164
write_terminator()
165
fi
166
fi
167
od
168
si
169
170
visit(`enum: Definitions.ENUM) is
171
location(`enum)
172
write("enum ")
173
`enum.name.accept(self)
174
write_line(" is")
175
indent()
176
let seen_any mut = false
177
for member in `enum.members do
178
if seen_any then
179
write_line(",")
180
fi
181
member.accept(self)
182
seen_any = true
183
od
184
write_line()
185
outdent()
186
write_line("si")
187
si
188
189
visit(member: Definitions.ENUM_MEMBER) is
190
location(member)
191
member.name.accept(self)
192
if member.initializer? then
193
write(" = ")
194
member.initializer!.accept(self)
195
fi
196
si
197
198
visit(functions: Definitions.FUNCTION_GROUP) is
199
write_line("function group ")
200
indent()
201
for f in functions.functions do
202
f.accept(self)
203
od
204
outdent()
205
si
206
207
visit(pragma: Pragmas.PRAGMA) is
208
write("@")
209
210
pragma.name.accept(self)
211
write("(")
212
213
pragma.arguments.accept(self)
214
write_line(")")
215
si
216
217
visit(pragma: Definitions.PRAGMA) is
218
pragma.definition.accept(self)
219
si
220
221
visit(type_expression: TypeExpressions.UNDEFINED) is
222
write("???")
223
si
224
225
visit(type_expression: TypeExpressions.INFER) is
226
write("infer")
227
si
228
229
visit(array: TypeExpressions.ARRAY_) is
230
array.element.accept(self)
231
write("[]")
232
si
233
234
visit(iterable: TypeExpressions.ITERABLE) is
235
iterable.element.accept(self)
236
write("{{}}")
237
si
238
239
visit(pointer: TypeExpressions.POINTER) is
240
pointer.element.accept(self)
241
write(" ptr")
242
si
243
244
visit(optional: TypeExpressions.OPTIONAL) is
245
optional.element.accept(self)
246
write("?")
247
si
248
249
visit(reference: TypeExpressions.REFERENCE) is
250
reference.element.accept(self)
251
write(" ref")
252
si
253
254
pre(member: TypeExpressions.MEMBER) -> bool => true
255
visit(member: TypeExpressions.MEMBER) is
256
member.left.accept(self)
257
write('.')
258
member.name.accept(self)
259
si
260
261
visit(functions: TypeExpressions.FUNCTION_GROUP) is
262
write("function group ")
263
for f in functions.functions do
264
f.accept(self)
265
write(' ')
266
od
267
si
268
269
visit(named: TypeExpressions.NAMED) is
270
location(named)
271
named.name.accept(self)
272
273
if named.is_argument_pack then
274
write("..")
275
fi
276
si
277
278
visit(tuple: TypeExpressions.TUPLE) is
279
location(tuple)
280
write("(")
281
tuple.elements.accept(self)
282
write(")")
283
si
284
285
visit(element: TypeExpressions.NAMED_TUPLE_ELEMENT) is
286
location(element)
287
element.name.accept(self)
288
write(": ")
289
element.type_expression.accept(self)
290
si
291
292
visit(constraint: TypeExpressions.TYPE_PARAMETER_CONSTRAINT) is
293
location(constraint)
294
write(constraint.keyword)
295
si
296
297
visit(types: TypeExpressions.LIST) is
298
location(types)
299
let seen_any mut = false
300
for t in types do
301
if seen_any then
302
write(", ")
303
fi
304
t.accept(self)
305
seen_any = true
306
od
307
si
308
309
visit(`none: Expressions.Literals.NONE) is
310
location(`none)
311
write("none")
312
si
313
314
visit(identifier: Expressions.IDENTIFIER) is
315
location(identifier)
316
identifier.identifier.accept(self)
317
si
318
319
visit(`super: Expressions.SUPER) is
320
location(`super)
321
write("super")
322
si
323
324
visit(construct: Expressions.CONSTRUCT) is
325
location(construct)
326
write('_')
327
write('(')
328
construct.arguments.accept(self)
329
write(')')
330
si
331
332
// Whether a cast's written target is left out, leaving the target
333
// for inference to recover from the cast's context.
334
strip_cast_target(`cast: Expressions.CAST, type_expression: TypeExpressions.TypeExpression) -> bool => false
335
336
visit(`cast: Expressions.CAST) is
337
location(`cast)
338
write("cast")
339
340
// A cast whose target was written parenthesised is printed
341
// back that way, whichever reading it settled on: dropping
342
// the parentheses would make the source say the typed
343
// reading outright, and adding a call around it would say
344
// the other.
345
if `cast.is_ambiguous then
346
write('(')
347
`cast.type_expression!.accept(self)
348
write(')')
349
write('(')
350
`cast.call_arguments!.accept(self)
351
write(')')
352
353
return
354
fi
355
356
if let type_expression = `cast.type_expression /\ !strip_cast_target(`cast, type_expression) then
357
write(' ')
358
type_expression.accept(self)
359
fi
360
361
write('(')
362
`cast.right.accept(self)
363
write(')')
364
si
365
366
visit(`isa: Expressions.ISA) is
367
location(`isa)
368
write("isa ")
369
`isa.type_expression.accept(self)
370
write('(')
371
`isa.right.accept(self)
372
write(')')
373
si
374
375
visit(field_equals: Expressions.FIELD_EQUALS) is
376
location(field_equals)
377
field_equals.left.accept(self)
378
write(" =~ ")
379
field_equals.right.accept(self)
380
si
381
382
visit(hash_operand: Expressions.HASH_OPERAND) is
383
location(hash_operand)
384
hash_operand.left.accept(self)
385
si
386
387
// A synthesized body has no source to print. The formatter
388
// reaches one only when a whole file is round-tripped, and
389
// what it stands for is a comparison the compiler emits
390
// rather than anything the author wrote.
391
visit(memberwise_equals: Expressions.MEMBERWISE_EQUALS) is
392
location(memberwise_equals)
393
si
394
395
visit(memberwise_hash: Expressions.MEMBERWISE_HASH) is
396
location(memberwise_hash)
397
si
398
399
visit(`typeof: Expressions.TYPEOF) is
400
location(`typeof)
401
write("typeof ")
402
`typeof.type_expression.accept(self)
403
si
404
405
visit(`default: Expressions.DEFAULT) is
406
location(`default)
407
write("_")
408
409
let type_expression = `default.type_expression
410
411
if type_expression? then
412
write('[')
413
type_expression.accept(self)
414
write(']')
415
fi
416
si
417
418
visit(tuple: Expressions.TUPLE) is
419
location(tuple)
420
write('(')
421
tuple.elements.accept(self)
422
write(')')
423
si
424
425
visit(call: Expressions.CALL) is
426
location(call)
427
if call.is_thread_first /\ call.arguments.count >= 1 then
428
call.arguments.expressions[0].accept(self)
429
write(if call.propagates_absence then " ~> " else " |> " fi)
430
call.function.accept(self)
431
write('(')
432
let seen mut = false
433
for i in 1..call.arguments.count do
434
if seen then
435
write(',')
436
fi
437
call.arguments.expressions[i].accept(self)
438
seen = true
439
od
440
if call.arguments.has_trailing_comma then
441
write(',')
442
fi
443
write(')')
444
else
445
call.function.accept(self)
446
write('(')
447
call.arguments.accept(self)
448
write(')')
449
fi
450
si
451
452
visit(member: Expressions.MEMBER) is
453
location(member)
454
member.left.accept(self)
455
if member.is_coalesce then
456
write("?.")
457
else
458
// `123.get_type()` scans `123.` as the start of a float.
459
if isa Expressions.Literals.INTEGER(member.left) then
460
write(' ')
461
fi
462
463
write('.')
464
fi
465
466
// An operator named as a member is an identifier only under its
467
// backtick: `a.=~(b)` scans `.=~` as one operator.
468
if Lexical.TOKENIZER.is_operator_name(member.identifier.name) then
469
write('`')
470
fi
471
472
member.identifier.accept(self)
473
si
474
475
visit(index: Expressions.INDEX) is
476
location(index)
477
index.left.accept(self)
478
write('[')
479
index.index.accept(self)
480
write(']')
481
si
482
483
visit(unary: Expressions.UNARY) is
484
location(unary)
485
unary.operation.accept(self)
486
write(' ')
487
unary.right.accept(self)
488
si
489
490
visit(binary: Expressions.BINARY) is
491
location(binary)
492
binary.left.accept(self)
493
write(' ')
494
495
if binary.actual_operation? then
496
write(binary.actual_operation)
497
else
498
binary.operation.accept(self)
499
fi
500
501
write(' ')
502
binary.right.accept(self)
503
si
504
505
visit(expressions: Expressions.LIST) is
506
location(expressions)
507
let seen_any mut = false
508
for e in expressions do
509
if seen_any then
510
write(',')
511
fi
512
e.accept(self)
513
seen_any = true
514
od
515
516
if expressions.has_trailing_comma then
517
write(',')
518
fi
519
si
520
521
visit(literal: Expressions.Literals.Literal) is
522
location(literal)
523
write(literal.value_string)
524
si
525
526
write_escape_char(c: char) is
527
let ci = cast int(c)
528
if ci < 32 then
529
write("\\{string.format("X", ci)}")
530
elif ci == 34 then
531
write("\\")
532
write(cast char(34))
533
elif ci == 39 then
534
write("'")
535
elif ci == 92 then
536
write("\\\\")
537
else
538
write(c)
539
fi
540
si
541
542
visit(`string: Expressions.Literals.STRING) is
543
location(`string)
544
write(cast char(34))
545
for c in `string.value_string do
546
write_escape_char(c)
547
od
548
write(cast char(34))
549
si
550
551
visit(interpolation: Expressions.STRING_INTERPOLATION) is
552
location(interpolation)
553
554
let in_expression mut = false
555
556
write("\"")
557
for e in interpolation.values do
558
if in_expression then
559
write("{{")
560
561
e.expression.accept(self)
562
563
if e.format? then
564
write(":{e.format}")
565
fi
566
567
if in_expression then
568
write("}}")
569
fi
570
else
571
// TODO: no quotes around string literals
572
e.expression.accept(self)
573
fi
574
575
in_expression = !in_expression
576
od
577
write("\"")
578
si
579
580
visit(integer: Expressions.Literals.INTEGER) is
581
location(integer)
582
write(integer.value_string)
583
si
584
585
visit(float: Expressions.Literals.FLOAT) is
586
location(float)
587
write(float.value_string)
588
si
589
590
visit(character: Expressions.Literals.CHARACTER) is
591
location(character)
592
write("'")
593
write_escape_char(character.value_string[0])
594
write("'")
595
si
596
597
visit(boolean: Expressions.Literals.BOOLEAN) is
598
location(boolean)
599
write(boolean.value_string)
600
si
601
602
visit(left: Trees.Expressions.SIMPLE_LEFT_EXPRESSION) is
603
left.expression.accept(self)
604
si
605
606
visit(destructure_left: Trees.Expressions.DESTRUCTURING_LEFT_EXPRESSION) is
607
let seen_any mut = false
608
write("(")
609
for e in destructure_left.elements do
610
if seen_any then
611
write(", ")
612
fi
613
614
e.accept(self)
615
616
seen_any = true
617
od
618
write(")")
619
si
620
621
visit(list: Statements.LIST) is
622
location(list)
623
for s in list do
624
s.accept(self)
625
od
626
si
627
628
visit(assign: Statements.ASSIGNMENT) is
629
location(assign)
630
assign.left.accept(self)
631
write(" = ")
632
assign.right.accept(self)
633
write_terminator()
634
si
635
636
visit(expression: Statements.EXPRESSION) is
637
location(expression)
638
expression.expression.accept(self)
639
write_terminator()
640
si
641
642
visit(r: Statements.RETURN) is
643
location(r)
644
write("return")
645
if r.expression? then
646
write(' ')
647
r.expression!.accept(self)
648
fi
649
write_terminator()
650
si
651
652
visit(t: Statements.THROW) is
653
location(t)
654
write("throw")
655
if t.expression? then
656
write(' ')
657
t.expression!.accept(self)
658
fi
659
write_terminator()
660
si
661
662
visit(`await: Expressions.AWAIT) is
663
location(`await)
664
write("await")
665
write(' ')
666
`await.operand.accept(self)
667
si
668
669
visit(`use: Expressions.USE) is
670
location(`use)
671
write("use")
672
write(' ')
673
`use.operand.accept(self)
674
si
675
676
visit(y: Statements.YIELD) is
677
location(y)
678
write("yield")
679
write(' ')
680
y.expression.accept(self)
681
write_terminator()
682
si
683
684
visit(y: Statements.YIELD_ALL) is
685
location(y)
686
write("yield in")
687
write(' ')
688
y.expression.accept(self)
689
write_terminator()
690
si
691
692
visit(t: Statements.ASSERT) is
693
location(t)
694
write("assert")
695
write(' ')
696
t.expression.accept(self)
697
698
if t.message? then
699
write(" else ")
700
t.message!.accept(self)
701
fi
702
703
write_terminator()
704
si
705
706
visit(i: Statements.IF) is
707
location(i)
708
let is_first mut = true
709
let seen_else mut = false
710
711
712
for b in i.branches do
713
location(b)
714
715
if seen_else then
716
IoC.CONTAINER.instance.logger.error(b.location, "broken if statement")
717
fi
718
719
assert !seen_else
720
721
if let b.condition? then
722
if is_first then
723
write("if ")
724
else
725
write("elif ")
726
fi
727
condition.accept(self)
728
write_line(" then")
729
else
730
seen_else = true
731
write_line("else")
732
fi
733
indent()
734
b.body.accept(self)
735
outdent()
736
is_first = false
737
od
738
write_line("fi")
739
si
740
741
visit(`case: Statements.CASE) is
742
location(`case)
743
write("case ")
744
`case.expression.accept(self)
745
write_line()
746
for m in `case.matches do
747
m.accept(self)
748
od
749
write_line("esac")
750
si
751
752
visit(match: Statements.CASE_MATCH) is
753
location(match)
754
if let match.expressions? then
755
write("when ")
756
expressions.accept(self)
757
write_line(":")
758
else
759
write_line("default")
760
fi
761
indent()
762
match.statements.accept(self)
763
outdent()
764
si
765
766
visit(`try: Statements.TRY) is
767
location(`try)
768
write_line("try")
769
indent()
770
`try.body.accept(self)
771
outdent()
772
for c in `try.catches do
773
c.accept(self)
774
od
775
let `finally = `try.`finally
776
777
if `finally? then
778
write_line("finally")
779
indent()
780
`finally.accept(self)
781
outdent()
782
fi
783
write_line("yrt")
784
si
785
786
visit(`catch: Statements.CATCH) is
787
location(`catch)
788
write("catch ")
789
790
if let `catch.variable? then
791
variable.accept(self)
792
fi
793
write_line()
794
indent()
795
`catch.body.accept(self)
796
outdent()
797
si
798
799
visit(`do: Statements.DO) is
800
location(`do)
801
if let `do.binding? then
802
write("while let ")
803
binding.accept(self)
804
write(" ")
805
elif let `do.condition? then
806
write("while ")
807
condition.accept(self)
808
write(" ")
809
fi
810
write_line("do")
811
indent()
812
`do.body.accept(self)
813
outdent()
814
write_line("od")
815
si
816
817
visit(labelled: Statements.LABELLED) is
818
location(labelled)
819
labelled.label.accept(self)
820
write(": ")
821
labelled.statement.accept(self)
822
si
823
824
visit(`break: Statements.BREAK) is
825
location(`break)
826
write("break")
827
828
if let `break.expression? then
829
write(' ')
830
expression.accept(self)
831
fi
832
write_terminator()
833
si
834
835
visit(`continue: Statements.CONTINUE) is
836
location(`continue)
837
write("continue")
838
let label = `continue.label
839
840
if label? then
841
write(' ')
842
label.accept(self)
843
fi
844
write_terminator()
845
si
846
847
visit(pragma: Statements.PRAGMA) is
848
if let pragma.statement? then
849
statement.accept(self)
850
fi
851
si
852
853
// A body-less function, property accessor or indexer accessor still
854
// needs a body node, so the parser hands back this rather than
855
// leaving the slot absent. There is nothing written to render:
856
// the caller's `after_body` is what emits the terminating `;`.
857
visit(block: Bodies.NULL) is si
858
si
859
si