tabnas-c 0.6.2

C23 concrete-syntax-tree grammar plugin for the tabnas parsing engine, over the jsonic base grammar
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
; C's render: the reader's tree, a concrete syntax tree, written back as C
; source. This is a library of definitions, each named `c-...`, which a
; host links with its own program (alchemy's `compile_sources`); its entry
; point is `c-render`, and nothing else here is the host's to call.
;
; The render writes the reader's own tree and no other, as the
; translation design says a render of a format whose value has a shape of
; its own does: the manifest names that shape as the schema `c`, and a
; host composes into this render only from a source of the same schema or
; from a program that builds the tree. The contract is the round trip: the
; text it writes reads back, through this repository's reader, as the tree
; it was given, spans included, apart from what the manifest's loss list
; says.
;
; The tree is concrete: every token the reader keeps is a node of kind
; `token` with its text (`src`), its name (`tname`) and its span (`start`,
; `end`, `line`, `col`), comments and line continuations among them, in
; source order along the `children` lists, and a comment the legacy
; expression path moved off its place in a node's `trivia`. The other
; members a node holds (`operand`, `cond`, `typeName` and the like)
; repeat subtrees that `children` already holds, so only `children` and
; `trivia` are followed. What the tree keeps outside tokens is written
; from the node that keeps it:
;
; - an operator, which the reader keeps as a node's `op` and not as a
;   token: between the operands of a binary or an assignment expression,
;   before a unary operand, after a postfix one, and between a member
;   expression's object and member;
; - the `?` and `:` of a conditional expression, the commas of a comma
;   expression and of an argument list, a call's parentheses, a
;   subscript's brackets, a cast's parentheses and a `*` the reader holds
;   as an empty token, wherever the node does not hold them as tokens of
;   its own, since some of the reader's paths keep them and some do not;
; - a prefix operator standing alone as a brace-initializer item, which the
;   TypeScript reader keeps as a raw operator array, `[operator, operand]`,
;   the operator holding its token's position, so it is written as a token
;   there (the Go reader keeps the array in a wrapper, `Val`, its operator
;   with no position, so it is written as a piece);
; - the parentheses of a call of no arguments, the shape the reader also
;   gives an expression in parentheses: an identifier alone is written as
;   a call, `f()`, where that keeps the next token where its span says,
;   and in parentheses otherwise; anything else in parentheses;
; - the width of a `_BitInt`, which the reader drops, as `()`, which reads
;   back as the same tree;
; - a space between an object-like macro's name and a body that begins
;   with `(`, which would otherwise read back as a function-like macro.
;
; Each token is written where its span puts it, so the reader gives it the
; same span again: line breaks up to its line, then spaces up to its
; column, and spaces at the end of the line before, where the offsets say
; the line held more than its tokens. A piece the tree keeps outside
; tokens has no span. It is written right after the text before it, with
; a space where the two would read as one token (`a - -b`, `sizeof x`),
; and where the next token begins a later line, the pieces that do not
; fit in the room the offsets leave at the end of the line before are
; written just before that token instead (`x = a` over `+ b`). Where a
; span cannot be kept, because a token has none (a tree a program built)
; or the pieces before it took its place, the token follows with a space
; where one is needed, a line break after a line comment and before a
; directive's `#`, and the columns after it on its line, and the offsets
; after it, move with it.
;
; alchemy has no loop over a vector and no way to join two vectors, so the
; render works in two passes over one string. The walk writes the tree as
; that string: each token as the separator c-tsep and its fields, each
; piece kept outside tokens as c-ssep and its text, a token's text escaped
; so that neither separator can occur in it. The layout splits it at the
; tokens, element k being token k and the pieces after it (element 0 the
; pieces before the first token), and writes each element, its token, its
; pieces and what goes up to the next token, from itself and the two
; elements after it, read through copies of the element list shifted by
; one and two. Numbers are added and subtracted as the lengths of strings
; of spaces, since alchemy has no arithmetic either; an offset is
; subtracted only where a token begins a line.
;
; The tree is captured whole, with only the members the render reads
; (c-keep-key), since the layout of each token depends on the tokens after
; it. A root that is not a node fails with TARGET_VALUE_UNREPRESENTABLE.
; Anything else in the tree that is not a node or a token, and a token
; without text, writes nothing.

; ---- the separators of the walk's string

def c-tsep "\u0001\u0003"

def c-ssep "\u0001\u0004"

def c-fsep "\u0001\u0005"

; A token's text with every U+0001 doubled into U+0001 U+0002, so that no
; separator, each U+0001 and a code other than U+0002, occurs in it.
def c-esc [s]
  string-join "\u0001\u0002" (split "\u0001" s)

def c-unesc [s]
  string-join "\u0001" (split "\u0001\u0002" s)

; ---- values

def c-at [v i]
  get-path (as-path [i]) v

def c-less [a b]
  match (compare a b)
    case :less true
    case _ false

def c-nonzero [n]
  match n
    case 0 false
    case _ true

def c-not [b]
  match b
    case true false
    case _ true

def c-both [a b]
  match [a b]
    case [true true] true
    case _ false

def c-either [a b]
  match [a b]
    case [false false] false
    case _ true

; The vector without its first item.
def c-drop1 [v]
  map (fn [i] (c-at v i)) (filter (fn [i] (c-less 0 i)) (indices v))

def c-join [v]
  string-join "" v

def c-nonempty [s]
  match s
    case "" false
    case _ true

; Whether the string s begins, or ends, with the string c, which is not
; empty: split cuts at every occurrence, so the first or the last string
; it gives is empty exactly then.
def c-starts [c s]
  match s
    case "" false
    case _
      match (c-at (split c s) 0)
        case "" true
        case _ false

def c-ends [c s]
  match s
    case "" false
    case _
      match (top (split c s))
        case "" true
        case _ false

; ---- numbers, as lengths

def c-add [a b]
  length (string-join "" [(repeat a " ") (repeat b " ")])

; a - b for a at least b; -1 where a is less. A string of b spaces and a
; mark occurs once in one of a spaces and a mark, at a - b.
def c-diff [a b]
  match (compare a b)
    case :less -1
    case _ (length (c-at (split (string-join "" [(repeat b " ") "|"]) (string-join "" [(repeat a " ") "|"])) 0))

; The digits of a whole number, as a span holds one, or "" for any other
; value: its text is digits, or digits and a fraction of zeros, as the
; Rust reader's tree spells every number (`4.0`).
def c-int-text [v]
  match (kind v)
    case :number
      let [t (scalar-text csv-options v)]
        match (chars-within [[48 57]] t)
          case true t
          case false
            let [parts (split "." t)]
              match (count parts)
                case 2
                  match [(c-nonempty (c-at parts 0)) (chars-within [[48 57]] (c-at parts 0)) (c-nonempty (c-at parts 1)) (chars-within [[48 48]] (c-at parts 1))]
                    case [true true true true] (c-at parts 0)
                    case _ ""
                case _ ""
    case _ ""

; Whether v is a whole number of at least the floor given.
def c-whole [floor v]
  match (c-int-text v)
    case "" false
    case t (c-not (c-less (number t) floor))

; ---- the tree

def c-str [k o]
  match (kind (get k o))
    case :string (get k o)
    case _ ""

def c-node-like [n]
  match (kind n)
    case :record
      match (kind (get "kind" n))
        case :string true
        case _ false
    case _ false

; A node's children; a raw operator array's items, or those of the
; wrapper (`Val`) the Go reader keeps one in.
def c-kids [n]
  match (kind n)
    case :record
      match (kind (get "children" n))
        case :vector (as-vector (get "children" n))
        case _
          match [(kind (get "kind" n)) (kind (get "Val" n))]
            case [:missing :vector] (as-vector (get "Val" n))
            case _ []
    case :vector (as-vector n)
    case _ []

def c-is-token [n]
  match (c-node-like n)
    case true
      match (get "kind" n)
        case "token" true
        case _ false
    case false false

def c-trivia [tname]
  match tname
    case "TRIVIA_BLOCK_COMMENT" true
    case "TRIVIA_LINE_COMMENT" true
    case "TRIVIA_LINE_CONT" true
    case _ false

; A token that is a construct's own: not a comment, a line continuation or
; the empty token the reader leaves where a rule matched none.
def c-own-token [c]
  match (c-is-token c)
    case true
      match [(c-str "src" c) (c-trivia (c-str "tname" c))]
        case ["" _] false
        case [_ true] false
        case _ true
    case false false

def c-has-token [n]
  c-nonzero (count (filter c-own-token (c-kids n)))

def c-has-token-where [pred n]
  c-nonzero (count (filter (fn [c] (c-both (c-own-token c) (pred (c-str "tname" c)))) (c-kids n)))

def c-member-token [tname]
  match tname
    case "PUNC_DOT" true
    case "PUNC_ARROW" true
    case _ false

def c-pointer-token [tname]
  match tname
    case "PUNC_STAR" true
    case "PUNC_CARET" true
    case _ false

def c-token-named [tname c]
  match (c-is-token c)
    case true
      match [tname (c-str "tname" c)]
        case ["KW__BITINT" "KW__BITINT"] true
        case ["PUNC_LPAREN" "PUNC_LPAREN"] true
        case _ false
    case false false

def c-kind-is [k n]
  match (c-node-like n)
    case true
      match [k (get "kind" n)]
        case ["macro_body" "macro_body"] true
        case ["argument_list" "argument_list"] true
        case ["identifier_expression" "identifier_expression"] true
        case _ false
    case false false

; ---- the walk

; A piece the tree keeps outside tokens.
def c-s [text]
  string-join "" [c-ssep text]

def c-num [v]
  c-int-text v

def c-span [t]
  match (kind (get "span" t))
    case :record (get "span" t)
    case _ (record)

; A token: its name, line, column, start, end and escaped text.
def c-token [t]
  match (c-str "src" t)
    case "" ""
    case src
      let [sp (c-span t)]
        string-join c-fsep
          vector
            string-join "" [c-tsep (c-str "tname" t)]
            c-num (get "line" sp)
            c-num (get "col" sp)
            c-num (get "start" sp)
            c-num (get "end" sp)
            c-esc src

; Whether a walk's string begins with a token of the name given.
def c-begins [enc tname]
  c-starts (string-join "" [c-tsep tname c-fsep]) enc

def c-op [n]
  c-str "op" n

def c-rest [encs]
  c-join (c-drop1 encs)

; A comment or a line continuation among a node's children: the tree
; keeps one where the token it precedes is the node's, a token the tree
; drops among them, so it stands where that token stood.
def c-trivia-child [c]
  match (c-is-token c)
    case true (c-trivia (c-str "tname" c))
    case false false

; The positions of a node's operands, its children that are not comments.
def c-operands [n]
  let [kids (c-kids n)]
    filter (fn [i] (c-not (c-trivia-child (c-at kids i)))) (indices kids)

; Whether the operand `j` stands before position `i`.
def c-operand-before [ops i j]
  match (c-less j (count ops))
    case true (c-less (c-at ops j) i)
    case false false

; The operand a position holds, counted from 0 and at most 3, or -1 for a
; comment. No piece placed among the operands tells the fourth operand
; from a later one, so the count stops at 3, and a child costs the same
; however many operands its node has.
def c-ordinal [kids ops i]
  match (c-trivia-child (c-at kids i))
    case true -1
    case false (count (filter (partial c-operand-before ops i) [0 1 2]))

; The children's strings with the pieces the tree keeps outside tokens
; placed among the operands: `(before k)` just before operand k, and
; `close` after the last child. A comment before a dropped token is a
; child before the operand that follows it, so the piece is written
; after the comment, where the token stood.
def c-around [n encs before close]
  let [kids (c-kids n) ops (c-operands n)]
    string-join ""
      vector
        c-join
          map
            fn [i]
              match (c-ordinal kids ops i)
                case -1 (c-at encs i)
                case k (string-join "" [(before k) (c-at encs i)])
            indices encs
        close

def c-infix [n encs]
  match [(c-has-token n) (c-less (count (c-operands n)) 2)]
    case [false false]
      c-around n encs (fn [k] (match k (case 1 (c-s (c-op n))) (case _ ""))) ""
    case _ (c-join encs)

def c-prefix [n encs]
  match [(c-has-token n) (count (c-operands n))]
    case [true _] (c-join encs)
    case [false 0] (string-join "" [(c-s (c-op n)) (c-join encs)])
    case _ (c-around n encs (fn [k] (match k (case 0 (c-s (c-op n))) (case _ ""))) "")

def c-postfix [n encs]
  match (c-has-token n)
    case false (string-join "" [(c-join encs) (c-s (c-op n))])
    case true (c-join encs)

def c-conditional [n encs]
  match [(c-has-token n) (c-less (count (c-operands n)) 3)]
    case [false false]
      c-around n encs (fn [k] (match k (case 1 (c-s "?")) (case 2 (c-s ":")) (case _ ""))) ""
    case _ (c-join encs)

def c-comma [n encs]
  match (c-has-token n)
    case false (c-around n encs (fn [k] (match k (case 0 "") (case _ (c-s ",")))) "")
    case true (c-join encs)

def c-member [n encs]
  match [(c-has-token-where c-member-token n) (c-less (count (c-operands n)) 2)]
    case [false false]
      c-around n encs (fn [k] (match k (case 1 (c-s (c-op n))) (case _ ""))) ""
    case _ (c-join encs)

; A list a node opens and closes with pieces: the opener before its first
; operand, a separator before each later one, and the closer last; with no
; operand, the opener first.
def c-enclosed [n encs open sep close]
  match (count (c-operands n))
    case 0 (string-join "" [(c-s open) (c-join encs) (c-s close)])
    case _ (c-around n encs (fn [k] (match k (case 0 (c-s open)) (case _ sep))) (c-s close))

def c-index [n encs]
  match (c-has-token n)
    case false (c-enclosed n encs "[" "" "]")
    case true (c-join encs)

def c-arguments [n encs]
  match (c-has-token n)
    case false (c-enclosed n encs "(" (c-s ",") ")")
    case true (c-join encs)

; A cast's parentheses are kept as its own tokens or as its type name's
; first and last, by every path of the reader seen; written only where
; neither holds them.
def c-cast [n encs]
  match [(c-has-token n) (c-less (count encs) 1)]
    case [false false]
      match (c-begins (c-at encs 0) "PUNC_LPAREN")
        case false (string-join "" [(c-s "(") (c-at encs 0) (c-s ")") (c-rest encs)])
        case true (c-join encs)
    case _ (c-join encs)

def c-parens [n encs]
  match (c-has-token n)
    case false (c-enclosed n encs "(" "" ")")
    case true (c-join encs)

def c-pointer [n encs]
  match (c-has-token-where c-pointer-token n)
    case false (string-join "" [(c-s "*") (c-join encs)])
    case true (c-join encs)

; An object-like macro whose body begins with `(` keeps a space before its
; body, or it would read back as a function-like one.
def c-define [n encs]
  match (c-str "macroKind" n)
    case "object-like"
      let [kids (c-kids n)]
        c-join
          map
            fn [i]
              match [(c-kind-is "macro_body" (c-at kids i)) (c-begins (c-at encs i) "PUNC_LPAREN")]
                case [true true] (string-join "" [(c-s " ") (c-at encs i)])
                case _ (c-at encs i)
            indices encs
    case _ (c-plain n encs)

def c-last [v]
  match (count v)
    case 0 missing
    case _ (top v)

def c-no-arguments [a]
  match (c-kind-is "argument_list" a)
    case true
      match [(c-has-token a) (count (c-kids a))]
        case [false 0] true
        case _ false
    case false false

; A call of no arguments. A node with a span is a call wherever it is: the
; reader gives an expression in parentheses a node of its own. A node
; without one is the 0.5 tree's, whose expression path gives an
; expression in parentheses the same shape as a call of no arguments:
; there an identifier alone gets the two markers the layout decides by the
; space after it, and anything else is written in parentheses.
def c-call [n encs]
  let [kids (c-kids n)]
    match [(c-no-arguments (c-last kids)) (kind (get "span" n))]
      case [true :record] (c-plain n encs)
      case [false _] (c-plain n encs)
      case _
        let [callee (c-join (pop encs))]
          match [(count encs) (c-kind-is "identifier_expression" (c-at kids 0)) (count (split c-tsep callee))]
            case [2 true 2] (string-join "" [(c-s "(?") callee (c-s ")?")])
            case _ (string-join "" [(c-s "(") callee (c-s ")")])

; The children in order, and `()` after a `_BitInt` the reader kept
; without its width.
def c-plain [n encs]
  let [kids (c-kids n)]
    match (c-nonzero (count (filter (partial c-token-named "KW__BITINT") kids)))
      case false (c-join encs)
      case true
        let [after (c-drop1 kids)]
          c-join
            map
              fn [i]
                match [(c-token-named "KW__BITINT" (c-at kids i)) (c-token-named "PUNC_LPAREN" (c-at after i))]
                  case [true false] (string-join "" [(c-at encs i) (c-s "(") (c-s ")")])
                  case _ (c-at encs i)
              indices encs

; A member under either of two names: an operator the TypeScript reader
; keeps raw spells its members `src`, `prefix` and `suffix`, and the Go
; reader's `Src`, `Prefix` and `Suffix`.
def c-member-of [a b o]
  match (kind (get a o))
    case :missing (get b o)
    case _ (get a o)

; An operator kept raw: an object with its text in `src` and no `kind`.
def c-operator-like [op]
  match (kind op)
    case :record
      match [(kind (get "kind" op)) (kind (c-member-of "src" "Src" op))]
        case [:missing :string] true
        case _ false
    case _ false

; The operator, as a token where its `token` keeps where it was (`sI`,
; `rI`, `cI`, `len`, as the TypeScript reader's does), and otherwise as a
; piece with no span.
def c-operator-text [op]
  let [src (c-member-of "src" "Src" op)]
    let [tk (match (kind (get "token" op)) (case :record (get "token" op)) (case _ (record)))]
      match [src (c-whole 0 (get "sI" tk)) (c-whole 1 (get "rI" tk)) (c-whole 1 (get "cI" tk)) (c-whole 0 (get "len" tk))]
        case ["" _ _ _ _] ""
        case [_ true true true true]
          string-join c-fsep
            vector
              string-join "" [c-tsep (c-str "name" tk)]
              c-num (get "rI" tk)
              c-num (get "cI" tk)
              c-num (get "sI" tk)
              c-num (c-add (number (c-int-text (get "sI" tk))) (number (c-int-text (get "len" tk))))
              c-esc src
        case _ (c-s src)

; A raw operator array, `[operator, operand]`: the operator before its
; operand, or after it where it is a suffix alone. An operator a host
; handed over as something else (its text, say) writes nothing, and the
; operand is written.
def c-operator-array [a encs]
  let [op (c-at a 0)]
    match (c-operator-like op)
      case false (c-join encs)
      case true
        match [(c-member-of "suffix" "Suffix" op) (c-member-of "prefix" "Prefix" op)]
          case [true true] (string-join "" [(c-operator-text op) (c-rest encs)])
          case [true _] (string-join "" [(c-rest encs) (c-operator-text op)])
          case _ (string-join "" [(c-operator-text op) (c-rest encs)])

def c-shape [n k encs]
  match k
    case "token" (c-token n)
    case "binary_expression" (c-infix n encs)
    case "assignment_expression" (c-infix n encs)
    case "member_expression" (c-member n encs)
    case "unary_expression" (c-prefix n encs)
    case "postfix_unary_expression" (c-postfix n encs)
    case "conditional_expression" (c-conditional n encs)
    case "comma_expression" (c-comma n encs)
    case "index_list" (c-index n encs)
    case "argument_list" (c-arguments n encs)
    case "cast_expression" (c-cast n encs)
    case "paren_expression" (c-parens n encs)
    case "pointer" (c-pointer n encs)
    case "define_directive" (c-define n encs)
    case "call_expression" (c-call n encs)
    case _ (c-plain n encs)

def c-assemble [n encs]
  match (kind n)
    case :vector (c-operator-array n encs)
    case :record
      match (c-node-like n)
        case true (c-shape n (get "kind" n) encs)
        case false
          match (kind (get "Val" n))
            case :vector (c-operator-array (as-vector (get "Val" n)) encs)
            case _ ""
    case _ ""

; The tokens a node's `trivia` holds before it (`leading`) or after it
; (`trailing`): the reader's legacy expression path keeps there a comment
; that stood before an infix operator, in its left operand's trailing
; trivia.
def c-trivia-token [t]
  match (c-is-token t)
    case true (c-token t)
    case false ""

def c-trivia-of [k n]
  match (kind n)
    case :record
      match (kind (get "trivia" n))
        case :record
          match (kind (get k (get "trivia" n)))
            case :vector (c-join (map c-trivia-token (as-vector (get k (get "trivia" n)))))
            case _ ""
        case _ ""
    case _ ""

; The walk, the one definition the render recurses through, as `self`:
; the children's strings first, then the node's own, between its trivia.
; It nests a few evaluation levels a level of the tree.
def c-walk [self n]
  string-join "" [(c-trivia-of "leading" n) (c-assemble n (map (fn [c] (self self c)) (c-kids n))) (c-trivia-of "trailing" n)]

; ---- the layout: elements

def c-int [s]
  match (is-number s)
    case true (number s)
    case false null

def c-decode-token [s]
  match s
    case "" null
    case _
      let [f (split c-fsep s)]
        record
          entry :tname (c-at f 0)
          entry :line (c-int (c-at f 1))
          entry :col (c-int (c-at f 2))
          entry :start (c-int (c-at f 3))
          entry :end (c-int (c-at f 4))
          entry :text (c-unesc (c-at f 5))

def c-decode [e]
  let [parts (split c-ssep e)]
    record
      entry :tok (c-decode-token (c-at parts 0))
      entry :synth (c-drop1 parts)

; A piece written: its text, and its token's name, or "" for one the tree
; keeps outside tokens.
def c-piece [text tname]
  record
    entry :text text
    entry :tname tname

def c-token-piece [tok]
  c-piece (get :text tok) (get :tname tok)

def c-first-piece [e]
  match (kind (get :tok e))
    case :record (c-token-piece (get :tok e))
    case _ (c-piece "" "")

def c-line-comment [p]
  match (get :tname p)
    case "TRIVIA_LINE_COMMENT" true
    case _ false

; ---- the layout: whether two pieces would read as one token

def c-word-chars [[36 36] [48 57] [65 90] [95 95] [97 122]]

def c-word-text [s]
  match s
    case "" false
    case _ (chars-within c-word-chars s)

def c-wordish [tname]
  match tname
    case "ID" true
    case "TYPEDEF_NAME" true
    case "MACRO_NAME" true
    case "LIT_INT" true
    case "LIT_FLOAT" true
    case _ (c-starts "KW_" tname)

def c-number-piece [p]
  match (get :tname p)
    case "LIT_INT" true
    case "LIT_FLOAT" true
    case _ false

def c-quote-first [s]
  c-either (c-starts "\"" s) (c-starts "'" s)

def c-ends-word [p]
  match (get :tname p)
    case "" (c-word-text (get :text p))
    case t (c-wordish t)

def c-starts-word [p]
  match (get :tname p)
    case "" (c-word-text (get :text p))
    case "LIT_INT" (c-not (c-starts "." (get :text p)))
    case "LIT_FLOAT" (c-not (c-starts "." (get :text p)))
    case "LIT_STRING" (c-not (c-quote-first (get :text p)))
    case "LIT_CHAR" (c-not (c-quote-first (get :text p)))
    case t (c-wordish t)

; The first characters after a punctuator that this lexer's longest match
; would take into it: `+` and `+` are `++`, `/` and `*` begin a comment.
def c-glue-next [t]
  match t
    case "+" ["+" "="]
    case "-" ["-" ">" "="]
    case "&" ["&" "="]
    case "|" ["|" "="]
    case "<" ["<" "=" ":" "%"]
    case "<<" ["="]
    case ">" [">" "="]
    case ">>" ["="]
    case "=" ["="]
    case "!" ["="]
    case "*" ["="]
    case "/" ["=" "/" "*"]
    case "%" ["=" ":" ">"]
    case "^" ["="]
    case ":" [">"]
    case "#" ["#"]
    case _ []

def c-starts-any [cs s]
  c-nonzero (count (filter (fn [c] (c-starts c s)) cs))

def c-punct-piece [p]
  match (get :tname p)
    case "" true
    case t (c-starts "PUNC_" t)

def c-prefix-glue [a bt]
  match (get :tname a)
    case "ID" (c-quote-first bt)
    case _ false

def c-glue-punct [a b]
  let [bt (get :text b)]
    match (get :text a)
      case "." (c-either (c-starts ".." bt) (c-both (c-number-piece b) (c-not (c-starts "." bt))))
      case "%:" (c-starts "%:" bt)
      case "L" (c-prefix-glue a bt)
      case "u" (c-prefix-glue a bt)
      case "U" (c-prefix-glue a bt)
      case "u8" (c-prefix-glue a bt)
      case at
        match (c-number-piece a)
          case true (c-starts "." bt)
          case false
            match (c-punct-piece a)
              case true (c-starts-any (c-glue-next at) bt)
              case false false

; Whether a then b, with nothing between, would lex as other tokens: two
; words, a number and a dot, a dot and a digit, a literal's prefix and its
; quote, or a punctuator the lexer would extend.
def c-glue [a b]
  match [(get :text a) (get :text b)]
    case ["" _] false
    case [_ ""] false
    case _
      match [(c-ends-word a) (c-starts-word b)]
        case [true true] true
        case _ (c-glue-punct a b)

; What goes between two pieces written with no span between them.
def c-sep [a b]
  match (c-line-comment a)
    case true "\n"
    case false
      match (c-glue a b)
        case true " "
        case false ""

; ---- the layout: positions

; A position: a line and a column, and an offset kept as the end of the
; token before (base) and what was written after it (extra), so that only
; a token beginning a line subtracts an offset.
def c-pos [line col base extra]
  record
    entry :line line
    entry :col col
    entry :base base
    entry :extra extra

def c-start-pos
  c-pos 1 1 0 0

def c-has-pos [tok]
  match (kind tok)
    case :record
      match [(c-whole 1 (get :line tok)) (c-whole 1 (get :col tok)) (c-whole 0 (get :start tok)) (c-whole 0 (get :end tok))]
        case [true true true true] true
        case _ false
    case _ false

def c-ascii [s]
  chars-within [[0 127]] s

; Where a token ends; null where that cannot be told. A token holding a
; character outside ASCII is measured by its offsets, which count in the
; reader's own units, as its columns do; the column after a token that
; spans lines and ends in such a character is not known (null), and a
; token after it on that line is placed by the offsets alone.
def c-end-of [tok]
  match (c-has-pos tok)
    case false null
    case true
      let [text (get :text tok)]
        let [segs (split "\n" text)]
          match (count segs)
            case 1
              match [(c-ascii text) (c-less (get :end tok) (get :start tok))]
                case [true _] (c-pos (get :line tok) (c-add (get :col tok) (length text)) (get :end tok) 0)
                case [false false] (c-pos (get :line tok) (c-add (get :col tok) (c-diff (get :end tok) (get :start tok))) (get :end tok) 0)
                case _ null
            case _
              match (c-ascii (top segs))
                case true (c-pos (c-add (get :line tok) (count (pop segs))) (c-add 1 (length (top segs))) (get :end tok) 0)
                case false (c-pos (c-add (get :line tok) (count (pop segs))) null (get :end tok) 0)

; The position after text, written at pos.
def c-advance [pos text]
  match (kind pos)
    case :record
      let [segs (split "\n" text)]
        match [(count segs) (kind (get :col pos))]
          case [1 :number] (c-pos (get :line pos) (c-add (get :col pos) (length text)) (get :base pos) (c-add (get :extra pos) (length text)))
          case [1 _] (c-pos (get :line pos) null (get :base pos) (c-add (get :extra pos) (length text)))
          case _ (c-pos (c-add (get :line pos) (count (pop segs))) (c-add 1 (length (top segs))) (get :base pos) (c-add (get :extra pos) (length text)))
    case _ null

; Where element e's token ends, or where the text begins for element 0;
; null where that cannot be told.
def c-start-of [e]
  match (kind (get :tok e))
    case :record (c-end-of (get :tok e))
    case _ c-start-pos

def c-floor0 [n]
  match (c-less n 0)
    case true 0
    case false n

def c-at-line-start [p]
  match (get :text p)
    case "" true
    case t (c-ends "\n" t)

; Where a span cannot be kept: a line break after a line comment and
; before a directive's `#`, a space where the two would read as one.
def c-fallback [last tok]
  match (c-line-comment last)
    case true "\n"
    case false
      match [(get :tname tok) (c-at-line-start last)]
        case ["PP_HASH" false] "\n"
        case _
          match (c-glue last (c-token-piece tok))
            case true " "
            case false ""

; ---- the layout: an element

; The pieces after first, from the right: those before the last, what
; goes between, the last.
def c-pieces-text [self first ps]
  match (count ps)
    case 0 ""
    case _
      let [before (pop ps)]
        string-join ""
          vector
            self self first before
            c-sep (c-last-piece first before) (c-piece (top ps) "")
            top ps

def c-last-piece [first ps]
  match (count ps)
    case 0 first
    case _ (c-piece (top ps) "")

def c-take [s v]
  map (fn [i] (c-at v i)) (filter (fn [i] (c-less i s)) (indices v))

def c-skip [s v]
  map (fn [i] (c-at v i)) (filter (fn [i] (c-not (c-less i s))) (indices v))

def c-top-or [d v]
  match (count v)
    case 0 d
    case _ (top v)

; How element e's pieces go between its token and element n's: `head`
; after e's token, `tail` up to n's, and whether every span is kept
; (`exact`).
def c-planned [head tail exact]
  record
    entry :head head
    entry :tail tail
    entry :exact exact

; n's token on e's line: the pieces after e's token, then the spaces up to
; n's column, or, where the column after them is not known, up to n's
; offset.
def c-plan-inline [pos0 t ps first all]
  let [cursor (c-advance pos0 all)]
    let [last (c-last-piece first ps)]
      match (kind (get :col cursor))
        case :number (c-plan-gap all last t (compare (get :line t) (get :line cursor)) (c-diff (get :col t) (get :col cursor)))
        case _ (c-plan-gap all last t (compare (get :line t) (get :line cursor)) (c-diff (c-diff (get :start t) (get :base cursor)) (get :extra cursor)))

; The spaces g between the pieces and n's token on one line; -1 where the
; pieces took the token's place.
def c-plan-gap [all last t line g]
  match [line (c-line-comment last) (compare g 0)]
    case [:equal false :greater] (c-planned all (repeat g " ") true)
    case [:equal false :equal]
      match (c-glue last (c-token-piece t))
        case false (c-planned all "" true)
        case true (c-planned all " " false)
    case _ (c-planned all (c-fallback last t) false)

; The most pieces that fit in the room the line before has after e's
; token; none after a line comment, which would take them in.
def c-split-at [room ps first]
  match (c-line-comment first)
    case true 0
    case false
      c-top-or 0 (filter (fn [s] (c-not (c-less room (length (c-pieces-text c-pieces-text first (c-take s ps)))))) (indices (push "" ps)))

def c-suffix-text [rest]
  match (count rest)
    case 0 ""
    case _ (string-join "" [(c-at rest 0) (c-pieces-text c-pieces-text (c-piece (c-at rest 0) "") (c-drop1 rest))])

def c-suffix-gap [rest t]
  match (count rest)
    case 0 0
    case _
      match (c-glue (c-piece (top rest) "") (c-token-piece t))
        case true 1
        case false 0

; n's token on a later line: the room the offsets leave on the line before
; is the spaces at its end and the pieces that were there. The pieces
; that fit stay after e's token, the rest go just before n's, and the
; line before ends in the spaces left, so n's token keeps its line, column
; and offset. Where neither line holds them, every piece stays after e's
; token, and n's token keeps its line and column.
def c-plan-break [pos0 t ps first all]
  let [lines (c-diff (get :line t) (get :line pos0))]
    let [room (c-diff (c-diff (get :start t) (get :base pos0)) (c-add (c-add lines (c-diff (get :col t) 1)) (get :extra pos0)))]
      let [s (c-split-at room ps first)]
        let [head (c-pieces-text c-pieces-text first (c-take s ps))]
          let [rest (c-skip s ps)]
            let [suffix (c-suffix-text rest)]
              let [gap (c-suffix-gap rest t)]
                let [indent (c-diff (c-diff (get :col t) 1) (c-add (length suffix) gap))]
                  match [(c-less room (length head)) (c-less indent 0)]
                    case [false false] (c-planned head (string-join "" [(repeat (c-diff room (length head)) " ") (repeat lines "\n") (repeat indent " ") suffix (repeat gap " ")]) true)
                    case _ (c-planned all (string-join "" [(repeat (c-floor0 (c-diff room (length all))) " ") (repeat lines "\n") (repeat (c-diff (get :col t) 1) " ")]) false)

def c-plan-to [e n ps first all]
  let [t (get :tok n)]
    let [pos0 (c-start-of e)]
      match [(kind pos0) (c-has-pos t)]
        case [:record true]
          match (compare (get :line t) (get :line pos0))
            case :greater (c-plan-break pos0 t ps first all)
            case _ (c-plan-inline pos0 t ps first all)
        case _ (c-planned all (c-fallback (c-last-piece first ps) t) true)

def c-plan [e n ps]
  let [first (c-first-piece e)]
    let [all (c-pieces-text c-pieces-text first ps)]
      match (kind n)
        case :record (c-plan-to e n ps first all)
        case _ (c-planned all "" true)

; The pieces with the close marker after e's identifier taken as `()` and
; the open marker before the next one as empty, so that one decision
; never waits on the next.
def c-probe-piece [p]
  match p
    case "(?" ""
    case ")?" "()"
    case _ p

; Whether `()` after the identifier that is e's token keeps every span up
; to the token of element n.
def c-call-fits [e n]
  match [(kind e) (kind n)]
    case [:record :record] (get :exact (c-plan e n (filter c-nonempty (map c-probe-piece (get :synth e)))))
    case _ true

; A piece with its marker resolved: the open marker before an identifier,
; empty where the call form fits after it and `(` otherwise; the close
; marker after one, `()` or `)` the same way.
def c-resolve [e n1 n2 p]
  match p
    case "(?"
      match (c-call-fits n1 n2)
        case true ""
        case false "("
    case ")?"
      match (c-call-fits e n1)
        case true "()"
        case false ")"
    case _ p

def c-token-text [e]
  match (kind (get :tok e))
    case :record (get :text (get :tok e))
    case _ ""

; Element e, followed by n1 and n2: its token, its pieces and what goes up
; to n1's token.
def c-element [e n1 n2]
  let [p (c-plan e n1 (filter c-nonempty (map (fn [x] (c-resolve e n1 n2 x)) (get :synth e))))]
    string-join "" [(c-token-text e) (get :head p) (get :tail p)]

def c-layout [whole]
  let [d (map c-decode (split c-tsep whole))]
    let [d1 (c-drop1 d)]
      let [d2 (c-drop1 d1)]
        c-join (map (fn [k] (c-element (c-at d k) (c-at d1 k) (c-at d2 k))) (indices d))

; ---- the members the render reads

; The members the render reads: a node's kind, children, trivia and op, a
; define's macroKind, a token's name, text and span, and a raw operator's
; text, fixity and position, as each reader spells them. Every other
; member, the ones that repeat a subtree `children` holds among them, is
; dropped before the tree is captured, since a subtree repeated at every
; level of an expression makes the tree's events grow fast with its
; nesting.
def c-keep-key [k]
  match k
    case "kind" true
    case "children" true
    case "trivia" true
    case "leading" true
    case "trailing" true
    case "op" true
    case "macroKind" true
    case "tname" true
    case "src" true
    case "span" true
    case "start" true
    case "end" true
    case "line" true
    case "col" true
    case "prefix" true
    case "suffix" true
    case "token" true
    case "name" true
    case "sI" true
    case "rI" true
    case "cI" true
    case "len" true
    case "Val" true
    case "Src" true
    case "Prefix" true
    case "Suffix" true
    case _ false

; The state is empty, or [:pending] when the next value is a dropped
; member's, or a marker for each container of a dropped value that is
; open.
def c-filter-step [s event]
  match (count s)
    case 0
      match event
        case (key k)
          match (c-keep-key k)
            case true (transition [] [event])
            case false (transition [:pending] [])
        case _ (transition [] [event])
    case _
      match [(top s) event]
        case [:pending object-start] (transition [:open] [])
        case [:pending array-start] (transition [:open] [])
        case [:pending _] (transition [] [])
        case [_ object-start] (transition (push :open s) [])
        case [_ array-start] (transition (push :open s) [])
        case [_ object-end] (transition (pop s) [])
        case [_ array-end] (transition (pop s) [])
        case _ (transition s [])

def c-filter-finish [s] []

; ---- the file

def c-file [tree]
  match (c-node-like tree)
    case true (c-layout (c-walk c-walk tree))
    case false (fail :unrepresentable "the tree is not a C syntax tree: its root is not a node")

; The render: the tree's events in, the members it reads kept, the
; source's text out.
def c-render [input]
  concat-map c-file
    select root
      as-events (scan-emit [] c-filter-step c-filter-finish (events input))