Skip to content
← Back

src/syntax/process/printer/formatter_expressions.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
// Expression and member formatting: interpolation, variables, properties, modifiers,
11
// calls, parameter and argument lists.
12
partial FORMATTER is
13
14
// A range between two single terms reads tight: `1..10`, `a.b..c.e`,
15
// `(a + 1)..(b + 2)`. A term ends in a token that cannot join the
16
// range operator, so the spaces come off. Any other operand shape -
17
// a binary, a unary, an unwrap - keeps the spaced form.
18
// A binary chain is one breaking unit: the whole left-nested spine
19
// shares a single group with a soft break after each operator, so a
20
// chain that does not fit breaks one operand per line with each
21
// operator left at the end of the line above it. Breaks go after an
22
// operator only - a line-start operator opens something new, so a
23
// break before one would change what the next line re-parses as.
24
visit(binary: Expressions.BINARY) is
25
note(binary.location)
26
27
if is_tight_range(binary) then
28
binary.left.accept(self)
29
write_operation(binary)
30
binary.right.accept(self)
31
return
32
fi
33
34
_builder.begin_group()
35
_builder.begin_nest(4)
36
37
_emit_binary_chain(binary)
38
39
_builder.end_nest()
40
_builder.end_group()
41
si
42
43
// Emit a chain's operands and operators in tree order, a soft break
44
// after each operator. Only the left spine is flattened into the
45
// enclosing group; a binary right operand recurses through
46
// visit(BINARY) and breaks as its own unit, so a nested chain indents
47
// once rather than once per enclosing operator.
48
_emit_binary_chain(binary: Expressions.BINARY) is
49
if
50
let left_binary: Expressions.BINARY = cast Expressions.BINARY?(binary.left) /\
51
!is_tight_range(left_binary)
52
then
53
_emit_binary_chain(left_binary)
54
else
55
binary.left.accept(self)
56
fi
57
58
write(' ')
59
write_operation(binary)
60
_builder.line()
61
binary.right.accept(self)
62
si
63
64
write_operation(binary: Expressions.BINARY) is
65
if binary.actual_operation? then
66
write(binary.actual_operation)
67
else
68
binary.operation.accept(self)
69
fi
70
si
71
72
is_tight_range(binary: Expressions.BINARY) -> bool is
73
let name = binary.actual_operation ?? binary.operation.name
74
75
if !(name.starts_with("..") \/ name.starts_with("::")) then
76
return false
77
fi
78
79
return is_range_term(binary.left) /\ is_range_term(binary.right)
80
si
81
82
// An operand that needs no separating space beside a range operator:
83
// it ends in a name character or a closing delimiter.
84
is_range_term(e: Expressions.Expression) -> bool =>
85
isa Expressions.Literals.Literal(e) \/
86
isa Expressions.IDENTIFIER(e) \/
87
isa Expressions.MEMBER(e) \/
88
isa Expressions.CALL(e) \/
89
isa Expressions.INDEX(e) \/
90
isa Expressions.TUPLE(e)
91
92
// --- faithfulness fix: string interpolation. The inherited visit
93
// runs each literal fragment through visit(STRING), which wraps
94
// it in quotes — producing invalid nested-string output. Emit the
95
// literal fragments as raw escaped text instead. ---
96
97
visit(interpolation: Expressions.STRING_INTERPOLATION) is
98
note(interpolation.location)
99
100
write(cast char(34))
101
102
for fragment in interpolation.values do
103
if fragment.is_expression then
104
write('{')
105
fragment.expression.accept(self)
106
if let fragment.alignment? then
107
write(',')
108
alignment.accept(self)
109
fi
110
if fragment.format? then
111
let format = fragment.format!
112
write(':')
113
write(format)
114
fi
115
write('}')
116
else
117
emit_interpolation_literal(fragment)
118
fi
119
od
120
121
write(cast char(34))
122
si
123
124
emit_interpolation_literal(fragment: Expressions.INTERPOLATION_FRAGMENT) is
125
let literal = cast Expressions.Literals.STRING?(fragment.expression)
126
127
if !literal? then
128
return
129
fi
130
131
for c in literal.value_string do
132
if c == '{' then
133
write('{')
134
write('{')
135
elif c == '}' then
136
write('}')
137
write('}')
138
else
139
write_escape_char(c)
140
fi
141
od
142
si
143
144
// --- faithfulness fix: the inherited write_escape_char renders
145
// control characters via string.format("X", ci), which returns
146
// the literal "X" (no placeholder), mangling e.g. '\n' to '\X'.
147
// Emit the escapes the tokenizer actually understands. ---
148
149
write_escape_char(c: char) is
150
let ci = cast int(c)
151
152
if c == '\n' then
153
write("\\")
154
write('n')
155
elif ci == 9 then
156
write("\\")
157
write('t')
158
elif ci == 13 then
159
write("\\")
160
write('r')
161
elif ci == 34 then
162
write("\\")
163
write(cast char(34))
164
elif ci == 92 then
165
write("\\\\")
166
elif ci < 32 then
167
write("\\u00")
168
write(hex_digit((ci >> 4) & 15))
169
write(hex_digit(ci & 15))
170
else
171
write(c)
172
fi
173
si
174
175
hex_digit(n: int) -> char is
176
if n < 10 then
177
return cast char(cast int('0') + n)
178
fi
179
180
return cast char(cast int('A') + n - 10)
181
si
182
183
// --- faithfulness fix: a plain string literal loses its brace
184
// escaping. `{{` written back as `{` opens an interpolation on
185
// the next parse. The interpolated path doubles braces
186
// (emit_interpolation_literal); the plain path must agree. ---
187
188
visit(string: Expressions.Literals.STRING) is
189
note(string.location)
190
write(cast char(34))
191
192
for c in string.value_string do
193
if c == '{' then
194
write('{')
195
write('{')
196
elif c == '}' then
197
write('}')
198
write('}')
199
else
200
write_escape_char(c)
201
fi
202
od
203
204
write(cast char(34))
205
si
206
207
// --- faithfulness fix: a character literal's quote must stay
208
// escaped - `'\''` written back as `'''` is reported as a
209
// zero-length literal - and a double quote needs no escape in
210
// this context, where the inherited write_escape_char (which
211
// carries the string literal's rules) adds one. ---
212
213
visit(character: Expressions.Literals.CHARACTER) is
214
note(character.location)
215
write("'")
216
217
let c = character.value_string[0]
218
219
if c == '\'' then
220
write("\\'")
221
elif c == cast char(34) then
222
write(c)
223
else
224
write_escape_char(c)
225
fi
226
227
write("'")
228
si
229
230
// --- faithfulness fix: a prefix operator is written tight against
231
// its operand. The inherited visit spaces it (`! x`), which is
232
// a faithfulness change on every reformat; a line-start
233
// operator is significant to boundary inference, so the
234
// spacing must not drift. ---
235
236
visit(unary: Expressions.UNARY) is
237
note(unary.location)
238
unary.operation.accept(self)
239
unary.right.accept(self)
240
si
241
242
// --- faithfulness fix: the inherited expression-list emitter
243
// writes `,` with no following space, so a tuple literal comes
244
// back as `(a,b)`. ---
245
246
visit(expressions: Expressions.LIST) is
247
note(expressions.location)
248
249
let seen_any mut = false
250
251
for e in expressions do
252
if seen_any then
253
write(", ")
254
fi
255
e.accept(self)
256
seen_any = true
257
od
258
259
if expressions.has_trailing_comma then
260
write(',')
261
fi
262
si
263
264
// --- faithfulness fix: a postfix type constructor applied to a
265
// function type binds to that function's *result*, so
266
// `(() -> T)?` written back without its parens is `() -> T?`,
267
// a function returning an optional. Parenthesise the operand
268
// whenever it is a function type. ---
269
270
visit(optional: TypeExpressions.OPTIONAL) is
271
note(optional.location)
272
emit_type_operand(optional.element)
273
write("?")
274
si
275
276
visit(array: TypeExpressions.ARRAY_) is
277
note(array.location)
278
emit_type_operand(array.element)
279
write("[]")
280
si
281
282
visit(iterable: TypeExpressions.ITERABLE) is
283
note(iterable.location)
284
emit_type_operand(iterable.element)
285
write("{{}}")
286
si
287
288
visit(pointer: TypeExpressions.POINTER) is
289
note(pointer.location)
290
emit_type_operand(pointer.element)
291
write(" ptr")
292
si
293
294
visit(reference: TypeExpressions.REFERENCE) is
295
note(reference.location)
296
emit_type_operand(reference.element)
297
write(" ref")
298
si
299
300
emit_type_operand(element: TypeExpressions.TypeExpression) is
301
if isa TypeExpressions.FUNCTION(element) then
302
write("(")
303
element.accept(self)
304
write(")")
305
return
306
fi
307
308
element.accept(self)
309
si
310
311
// --- faithfulness fix: a VARIABLE carries three optional pieces
312
// the inherited printer never emits — the `..` splice marker
313
// (only inside a secondary `init` formal-arg list), the
314
// trailing `mut` keyword (set by the parser when source had
315
// `mut`), and a trailing modifier suffix list (only on
316
// primary-ctor parameter declarations, where `public`,
317
// `field`, and `init` describe the auto-generated body
318
// member). ---
319
320
// A lambda parameter written as a destructure group has a synthesised
321
// name - the source names only the leaves - and the group itself is on
322
// `left`. Printing the name hands back `$destructured_argument`, which
323
// is not what was written and does not parse.
324
visit(variable: Expressions.VARIABLE) is
325
emit_parameter_pragmas(variable.pragmas)
326
327
if variable.is_synthesized /\ variable.left? then
328
variable.left.accept(self)
329
else
330
variable.name.accept(self)
331
fi
332
333
let type_expression = variable.type_expression
334
335
if !isa TypeExpressions.INFER(type_expression) /\ !_strip("parameter", variable.location, "type", type_expression.location, type_expression.location) then
336
write(": ")
337
type_expression.accept(self)
338
elif let annotation = _annotation(a => a.parameter_type(variable.location)) then
339
write(": {annotation}")
340
fi
341
342
if !variable.is_synthesized /\ variable.initializer? then
343
write(" = ")
344
variable.initializer!.accept(self)
345
fi
346
si
347
348
visit(variable: Variables.VARIABLE) is
349
note(variable.location)
350
351
if variable.is_splice then
352
write("..")
353
return
354
fi
355
356
emit_parameter_pragmas(variable.pragmas)
357
358
variable.left.accept(self)
359
360
let variable_type_expression = variable.type_expression
361
362
if !isa TypeExpressions.INFER(variable_type_expression) /\ !(_in_let /\ _strip("local", variable.location, "type", variable_type_expression.location, variable_type_expression.location)) then
363
write(": ")
364
variable_type_expression.accept(self)
365
elif let annotation = _annotation(a => a.local_type(variable.location)) then
366
write(": {annotation}")
367
fi
368
369
if variable.is_mutable_marked then
370
write(" mut")
371
fi
372
373
if let variable.modifiers? /\ !modifiers.is_empty then
374
write(" ")
375
emit_modifiers(modifiers)
376
fi
377
378
let initializer = variable.initializer
379
if initializer? then
380
write(" = ")
381
initializer.accept(self)
382
fi
383
si
384
385
// --- faithfulness fix: a body-less property (a field) is terminated
386
// with `;` and a newline, which the plain printer omits ---
387
388
visit(property: Definitions.PROPERTY) is
389
if property.name? then
390
property.name.accept(self)
391
fi
392
393
let property_type_expression = property.type_expression
394
395
if !isa TypeExpressions.INFER(property_type_expression) then
396
write(": ")
397
property_type_expression.accept(self)
398
fi
399
400
if !property.modifiers.is_empty then
401
write(" ")
402
emit_modifiers(property.modifiers)
403
fi
404
405
if !property.read_body? /\ !property.assign_body? then
406
write_terminator()
407
return
408
fi
409
410
let out_again =
411
indent_property(
412
property.read_body? /\ !_has_no_written_body(property.read_body),
413
property.assign_body?
414
)
415
416
if property.read_body? then
417
property.read_body.accept(self)
418
if property.assign_body? then
419
write_line(",")
420
else
421
after_body(property.read_body!)
422
fi
423
else
424
write(" ")
425
fi
426
427
if property.assign_body? then
428
write("= ")
429
property.assign_argument!.accept(self)
430
// The block body opens with `is`, written directly after
431
// whatever precedes it. The argument does not end in a
432
// space, so without one here the keyword runs onto it -
433
// `= valueis` - and the result no longer parses.
434
if !at_line_start then
435
write(" ")
436
fi
437
property.assign_body!.accept(self)
438
after_body(property.assign_body!)
439
fi
440
441
if out_again then
442
outdent()
443
fi
444
si
445
446
// Emit modifiers without the trailing space the inherited
447
// Modifiers.LIST visit appends (which would strand a space before a
448
// following `;`).
449
emit_modifiers(modifiers: Modifiers.LIST) is
450
let first mut = true
451
452
if let modifiers.access_modifier? then
453
access_modifier.accept(self)
454
first = false
455
fi
456
457
if let modifiers.storage_class? then
458
if !first then
459
write(" ")
460
fi
461
storage_class.accept(self)
462
first = false
463
fi
464
465
if modifiers.is_abstract then
466
if !first then
467
write(" ")
468
fi
469
write("abstract")
470
first = false
471
fi
472
473
if modifiers.is_pure then
474
if !first then
475
write(" ")
476
fi
477
write("pure")
478
first = false
479
fi
480
481
if modifiers.is_stable then
482
if !first then
483
write(" ")
484
fi
485
write("stable")
486
first = false
487
fi
488
si
489
490
// --- wrapping: call argument lists and function parameter lists ---
491
492
visit(call: Expressions.CALL) is
493
note(call.location)
494
if call.is_thread_first /\ call.arguments.count >= 1 then
495
call.arguments.expressions[0].accept(self)
496
write(if call.propagates_absence then " ~> " else " |> " fi)
497
emit_callee(call.function)
498
emit_inferred_type_arguments(call.function)
499
write("(")
500
emit_argument_list(call.arguments, 1)
501
write(")")
502
else
503
emit_callee(call.function)
504
emit_inferred_type_arguments(call.function)
505
write("(")
506
emit_argument_list(call.arguments, 0, call.argument_names)
507
write(")")
508
fi
509
si
510
511
// A callee that writes its own type arguments prints without
512
// them when the stripper takes that site.
513
// A single type argument parses as an index until the build
514
// decides, so that shape arrives as the ambiguous node.
515
emit_callee(callee: Expressions.Expression) is
516
if let generic: Expressions.GENERIC_APPLICATION = callee /\ _strip("type-arguments", callee.location, "after", generic.identifier.location, callee.location) then
517
if let generic.left? then
518
left.accept(self)
519
write(".")
520
fi
521
522
generic.identifier.accept(self)
523
elif let ambiguous: Expressions.AMBIGUOUS_EXPRESSION = callee /\ _names_a_type(_bracketed(ambiguous.index)) /\ _strip("type-arguments", callee.location, "after", ambiguous.identifier.location, callee.location) then
524
if let ambiguous.left? then
525
left.accept(self)
526
write(".")
527
fi
528
529
ambiguous.identifier.accept(self)
530
else
531
callee.accept(self)
532
fi
533
si
534
535
// What an ambiguous bracket holds: the node keeps the whole indexing
536
// expression, whose own index is the bracket's content.
537
_bracketed(index: Expressions.Expression) -> Expressions.Expression =>
538
if let indexed: Expressions.INDEX = index then indexed.index else index fi
539
540
// Whether an ambiguous bracket's content is a type rather than an
541
// index: a capitalised or qualified name, or a primitive's.
542
_names_a_type(index: Expressions.Expression) -> bool is
543
if let identifier: Expressions.IDENTIFIER = index then
544
let name = identifier.identifier.name
545
546
char.is_upper(name[0]) \/
547
["int", "string", "bool", "double", "char", "object", "single", "long", "byte", "short", "decimal", "bigint", "uint", "ulong", "ubyte", "ushort", "word", "uword", "void"]
548
|> Ghul.Pipes.any(p => p =~ name)
549
elif isa Expressions.MEMBER(index) then
550
true
551
else
552
false
553
fi
554
si
555
556
emit_inferred_type_arguments(callee: Expressions.Expression) is
557
// Only a bare or qualified name: a callee that writes its own
558
// type arguments parses as something else.
559
if !isa Expressions.IDENTIFIER(callee) /\ !isa Expressions.MEMBER(callee) then
560
return
561
fi
562
563
if let arguments = _annotation(a => a.type_arguments(callee.location)) then
564
write("[")
565
write(arguments)
566
write("]")
567
fi
568
si
569
570
visit(function: Definitions.FUNCTION) is
571
if let function.name? then
572
name.accept(self)
573
fi
574
575
if _has_type_arguments(function.generic_arguments) then
576
write("[")
577
function.generic_arguments.accept(self)
578
write("]")
579
fi
580
581
write("(")
582
emit_parameter_list(function.arguments)
583
write(")")
584
585
let function_type_expression = function.type_expression
586
587
if !isa TypeExpressions.INFER(function_type_expression) then
588
write(" -> ")
589
function_type_expression.accept(self)
590
fi
591
592
if !function.modifiers.is_empty then
593
write(" ")
594
emit_modifiers(function.modifiers)
595
fi
596
597
let body = function.body
598
599
if body? /\ !_has_no_written_body(body) then
600
write(" ")
601
body.accept(self)
602
fi
603
604
after_body(body)
605
si
606
607
emit_parameter_list(parameters: Variables.LIST) is
608
if !_has_parameters(parameters) then
609
return
610
fi
611
612
_builder.begin_group()
613
_builder.begin_nest(4)
614
_builder.soft_line()
615
616
let first mut = true
617
for p in parameters do
618
if !first then
619
_builder.text(",")
620
_builder.line()
621
fi
622
p.accept(self)
623
first = false
624
od
625
626
_builder.end_nest()
627
_builder.soft_line()
628
_builder.end_group()
629
si
630
631
_has_parameters(parameters: Variables.LIST?) -> bool is
632
if !parameters? then
633
return false
634
fi
635
for p in parameters do
636
return true
637
od
638
return false
639
si
640
641
_has_type_arguments(arguments: TypeExpressions.LIST?) -> bool is
642
if !arguments? then
643
return false
644
fi
645
for a in arguments do
646
return true
647
od
648
return false
649
si
650
651
// --- faithfulness fix: a NAMED_TUPLE_ELEMENT in type-parameter
652
// position can carry up to four pieces of constraint syntax
653
// past its name:type slot — the trailing kind keyword after a
654
// type bound (`[T: A class]`), an `init` ctor constraint, and a
655
// trailing `in` / `out` variance. The inherited visit emits
656
// only `name: type_expression`, dropping the other three.
657
// The `[T: out]` variance-only form also needs its
658
// TYPE_PARAMETER_CONSTRAINT(NONE) placeholder suppressed
659
// (the inherited path renders it as `?`). ---
660
661
visit(element: TypeExpressions.NAMED_TUPLE_ELEMENT) is
662
note(element.location)
663
element.name.accept(self)
664
write(": ")
665
666
let constraint = cast TypeExpressions.TYPE_PARAMETER_CONSTRAINT?(element.type_expression)
667
let is_placeholder =
668
constraint? /\
669
constraint.kind == Semantic.Symbols.TypeParameterConstraintKind.NONE
670
let need_separator mut = false
671
672
if !is_placeholder then
673
element.type_expression.accept(self)
674
need_separator = true
675
fi
676
677
for bound in element.additional_bounds do
678
write(" /\\ ")
679
bound.accept(self)
680
od
681
682
if element.combined_kind != Semantic.Symbols.TypeParameterConstraintKind.NONE then
683
if need_separator then
684
write(" ")
685
fi
686
write(_constraint_kind_keyword(element.combined_kind))
687
need_separator = true
688
fi
689
690
if element.has_constructor then
691
if need_separator then
692
write(" ")
693
fi
694
write("init")
695
need_separator = true
696
fi
697
698
if element.variance == Semantic.Types.TypeVariance.COVARIANT then
699
if need_separator then
700
write(" ")
701
fi
702
write("out")
703
elif element.variance == Semantic.Types.TypeVariance.CONTRAVARIANT then
704
if need_separator then
705
write(" ")
706
fi
707
write("in")
708
fi
709
si
710
711
_constraint_kind_keyword(kind: Semantic.Symbols.TypeParameterConstraintKind) -> string is
712
if kind == Semantic.Symbols.TypeParameterConstraintKind.REFERENCE then
713
return "class"
714
elif kind == Semantic.Symbols.TypeParameterConstraintKind.VALUE then
715
return "struct"
716
elif kind == Semantic.Symbols.TypeParameterConstraintKind.OPTIONAL then
717
return "optional"
718
fi
719
return ""
720
si
721
722
emit_argument_list(arguments: Expressions.LIST) is
723
emit_argument_list(arguments, 0)
724
si
725
726
emit_argument_list(arguments: Expressions.LIST, start: int) is
727
emit_argument_list(arguments, start, null)
728
si
729
730
// Attributes written before a parameter stay on its own line.
731
emit_parameter_pragmas(pragmas: Collections.LIST[Pragmas.PRAGMA]?) is
732
if !pragmas? then
733
return
734
fi
735
736
for pragma in pragmas do
737
pragma.accept(self)
738
write(" ")
739
od
740
si
741
742
// `names`, when the call used named-argument syntax, runs parallel
743
// to `arguments`: the parser moved each value into the list and
744
// kept the name beside it.
745
emit_argument_list(arguments: Expressions.LIST, start: int, names: Collections.List[Identifiers.Identifier]?) is
746
if arguments.count <= start then
747
return
748
fi
749
750
_builder.begin_group()
751
_builder.begin_nest(4)
752
_builder.soft_line()
753
754
let first mut = true
755
for i in start..arguments.count do
756
if !first then
757
_builder.text(",")
758
_builder.line()
759
fi
760
761
if names? /\ i < names.count then
762
names[i].accept(self)
763
write(" = ")
764
fi
765
766
arguments.expressions[i].accept(self)
767
first = false
768
od
769
770
// Written hard against the argument it trails, inside the nest,
771
// so a broken layout puts it at the end of that argument's line
772
// and leaves the closing bracket on its own.
773
if arguments.has_trailing_comma then
774
_builder.text(",")
775
fi
776
777
_builder.end_nest()
778
_builder.soft_line()
779
_builder.end_group()
780
si
781
782
_has_arguments(arguments: Expressions.LIST) -> bool is
783
for a in arguments do
784
return true
785
od
786
return false
787
si
788
si
789
si