summaryrefslogtreecommitdiffstats
path: root/tools/net/sunrpc/xdrgen/xdr_ast.py
blob: 9dab8bc545b0a9df7bf5793caa106500c1d366ed (plain)
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
#!/usr/bin/env python3
# ex: set filetype=python:

"""Define and implement the Abstract Syntax Tree for the XDR language."""

import sys
from typing import List
from dataclasses import dataclass, KW_ONLY

from lark import ast_utils, Transformer
from lark.tree import Meta

this_module = sys.modules[__name__]

big_endian = []
excluded_apis = []
header_name = "none"
public_apis = []
structs = set()
pass_by_reference = set()

constants = {}


def xdr_quadlen(val: str) -> int:
    """Return integer XDR width of an XDR type"""
    if val in constants:
        octets = constants[val]
    else:
        octets = int(val)
    return int((octets + 3) / 4)


symbolic_widths = {
    "void": ["XDR_void"],
    "bool": ["XDR_bool"],
    "short": ["XDR_short"],
    "unsigned_short": ["XDR_unsigned_short"],
    "int": ["XDR_int"],
    "unsigned_int": ["XDR_unsigned_int"],
    "long": ["XDR_long"],
    "unsigned_long": ["XDR_unsigned_long"],
    "hyper": ["XDR_hyper"],
    "unsigned_hyper": ["XDR_unsigned_hyper"],
}

# Numeric XDR widths are tracked in a dictionary that is keyed
# by type_name because sometimes a caller has nothing more than
# the type_name to use to figure out the numeric width.
max_widths = {
    "void": 0,
    "bool": 1,
    "short": 1,
    "unsigned_short": 1,
    "int": 1,
    "unsigned_int": 1,
    "long": 1,
    "unsigned_long": 1,
    "hyper": 2,
    "unsigned_hyper": 2,
}


@dataclass
class _XdrAst(ast_utils.Ast):
    """Base class for the XDR abstract syntax tree"""

    # Source position of the construct's declared identifier, when
    # the transformer records one, so semantic diagnostics can point
    # at the exact declaration. The KW_ONLY marker makes the fields
    # keyword-only, so they never disturb the positional child
    # ordering lark uses to build each node; 0 means the position was
    # not recorded.
    _: KW_ONLY
    line: int = 0
    column: int = 0


@dataclass
class _XdrIdentifier(_XdrAst):
    """Corresponds to 'identifier' in the XDR language grammar"""

    symbol: str


@dataclass
class _XdrValue(_XdrAst):
    """Corresponds to 'value' in the XDR language grammar"""

    value: str


@dataclass
class _XdrConstantValue(_XdrAst):
    """Corresponds to 'constant' in the XDR language grammar"""

    value: int


@dataclass
class _XdrTypeSpecifier(_XdrAst):
    """Corresponds to 'type_specifier' in the XDR language grammar"""

    type_name: str
    c_classifier: str = ""


@dataclass
class _XdrDefinedType(_XdrTypeSpecifier):
    """Corresponds to a type defined by the input specification"""

    def symbolic_width(self) -> List:
        """Return list containing XDR width of type's components"""
        return [get_header_name().upper() + "_" + self.type_name + "_sz"]

    def __post_init__(self):
        if self.type_name in structs:
            self.c_classifier = "struct "
        symbolic_widths[self.type_name] = self.symbolic_width()


@dataclass
class _XdrBuiltInType(_XdrTypeSpecifier):
    """Corresponds to a built-in XDR type"""

    def symbolic_width(self) -> List:
        """Return list containing XDR width of type's components"""
        return symbolic_widths[self.type_name]


@dataclass
class _XdrDeclaration(_XdrAst):
    """Base class of XDR type declarations"""


@dataclass
class _XdrFixedLengthOpaque(_XdrDeclaration):
    """A fixed-length opaque declaration"""

    name: str
    size: str
    template: str = "fixed_length_opaque"

    def max_width(self) -> int:
        """Return width of type in XDR_UNITS"""
        return xdr_quadlen(self.size)

    def symbolic_width(self) -> List:
        """Return list containing XDR width of type's components"""
        return ["XDR_QUADLEN(" + self.size + ")"]

    def __post_init__(self):
        max_widths[self.name] = self.max_width()
        symbolic_widths[self.name] = self.symbolic_width()


@dataclass
class _XdrVariableLengthOpaque(_XdrDeclaration):
    """A variable-length opaque declaration"""

    name: str
    maxsize: str
    template: str = "variable_length_opaque"

    def max_width(self) -> int:
        """Return width of type in XDR_UNITS"""
        return 1 + xdr_quadlen(self.maxsize)

    def symbolic_width(self) -> List:
        """Return list containing XDR width of type's components"""
        widths = ["XDR_unsigned_int"]
        if self.maxsize != "0":
            widths.append("XDR_QUADLEN(" + self.maxsize + ")")
        return widths

    def __post_init__(self):
        max_widths[self.name] = self.max_width()
        symbolic_widths[self.name] = self.symbolic_width()


@dataclass
class _XdrString(_XdrDeclaration):
    """A (NUL-terminated) variable-length string declaration"""

    name: str
    maxsize: str
    template: str = "string"

    def max_width(self) -> int:
        """Return width of type in XDR_UNITS"""
        return 1 + xdr_quadlen(self.maxsize)

    def symbolic_width(self) -> List:
        """Return list containing XDR width of type's components"""
        widths = ["XDR_unsigned_int"]
        if self.maxsize != "0":
            widths.append("XDR_QUADLEN(" + self.maxsize + ")")
        return widths

    def __post_init__(self):
        max_widths[self.name] = self.max_width()
        symbolic_widths[self.name] = self.symbolic_width()


@dataclass
class _XdrFixedLengthArray(_XdrDeclaration):
    """A fixed-length array declaration"""

    name: str
    spec: _XdrTypeSpecifier
    size: str
    template: str = "fixed_length_array"

    def max_width(self) -> int:
        """Return width of type in XDR_UNITS"""
        return xdr_quadlen(self.size) * max_widths[self.spec.type_name]

    def symbolic_width(self) -> List:
        """Return list containing XDR width of type's components"""
        item_width = " + ".join(symbolic_widths[self.spec.type_name])
        return ["(" + self.size + " * (" + item_width + "))"]

    def __post_init__(self):
        max_widths[self.name] = self.max_width()
        symbolic_widths[self.name] = self.symbolic_width()


@dataclass
class _XdrVariableLengthArray(_XdrDeclaration):
    """A variable-length array declaration"""

    name: str
    spec: _XdrTypeSpecifier
    maxsize: str
    template: str = "variable_length_array"

    def max_width(self) -> int:
        """Return width of type in XDR_UNITS"""
        return 1 + (xdr_quadlen(self.maxsize) * max_widths[self.spec.type_name])

    def symbolic_width(self) -> List:
        """Return list containing XDR width of type's components"""
        widths = ["XDR_unsigned_int"]
        if self.maxsize != "0":
            item_width = " + ".join(symbolic_widths[self.spec.type_name])
            widths.append("(" + self.maxsize + " * (" + item_width + "))")
        return widths

    def __post_init__(self):
        max_widths[self.name] = self.max_width()
        symbolic_widths[self.name] = self.symbolic_width()


@dataclass
class _XdrOptionalData(_XdrDeclaration):
    """An 'optional_data' declaration"""

    name: str
    spec: _XdrTypeSpecifier
    template: str = "optional_data"

    def max_width(self) -> int:
        """Return width of type in XDR_UNITS"""
        return 1

    def symbolic_width(self) -> List:
        """Return list containing XDR width of type's components"""
        return ["XDR_bool"]

    def __post_init__(self):
        structs.add(self.name)
        pass_by_reference.add(self.name)
        max_widths[self.name] = self.max_width()
        symbolic_widths[self.name] = self.symbolic_width()


@dataclass
class _XdrBasic(_XdrDeclaration):
    """A 'basic' declaration"""

    name: str
    spec: _XdrTypeSpecifier
    template: str = "basic"

    def max_width(self) -> int:
        """Return width of type in XDR_UNITS"""
        return max_widths[self.spec.type_name]

    def symbolic_width(self) -> List:
        """Return list containing XDR width of type's components"""
        return symbolic_widths[self.spec.type_name]

    def __post_init__(self):
        max_widths[self.name] = self.max_width()
        symbolic_widths[self.name] = self.symbolic_width()


@dataclass
class _XdrVoid(_XdrDeclaration):
    """A void declaration"""

    name: str = "void"
    template: str = "void"

    def max_width(self) -> int:
        """Return width of type in XDR_UNITS"""
        return 0

    def symbolic_width(self) -> List:
        """Return list containing XDR width of type's components"""
        return []


@dataclass
class _XdrConstant(_XdrAst):
    """Corresponds to 'constant_def' in the grammar"""

    name: str
    value: str

    def __post_init__(self):
        if self.value not in constants:
            constants[self.name] = int(self.value, 0)


@dataclass
class _XdrEnumerator(_XdrAst):
    """An 'identifier = value' enumerator"""

    name: str
    value: str

    def __post_init__(self):
        if self.value not in constants:
            constants[self.name] = int(self.value, 0)


@dataclass
class _XdrEnum(_XdrAst):
    """An XDR enum definition"""

    name: str
    enumerators: List[_XdrEnumerator]

    def max_width(self) -> int:
        """Return width of type in XDR_UNITS"""
        return 1

    def symbolic_width(self) -> List:
        """Return list containing XDR width of type's components"""
        return ["XDR_int"]

    def __post_init__(self):
        max_widths[self.name] = self.max_width()
        symbolic_widths[self.name] = self.symbolic_width()


@dataclass
class _XdrStruct(_XdrAst):
    """An XDR struct definition"""

    name: str
    fields: List[_XdrDeclaration]

    def max_width(self) -> int:
        """Return width of type in XDR_UNITS"""
        width = 0
        for field in self.fields:
            width += field.max_width()
        return width

    def symbolic_width(self) -> List:
        """Return list containing XDR width of type's components"""
        widths = []
        for field in self.fields:
            widths += field.symbolic_width()
        return widths

    def __post_init__(self):
        structs.add(self.name)
        pass_by_reference.add(self.name)
        max_widths[self.name] = self.max_width()
        symbolic_widths[self.name] = self.symbolic_width()


@dataclass
class _XdrPointer(_XdrAst):
    """An XDR pointer definition"""

    name: str
    fields: List[_XdrDeclaration]

    def max_width(self) -> int:
        """Return width of type in XDR_UNITS"""
        width = 1
        for field in self.fields[0:-1]:
            width += field.max_width()
        return width

    def symbolic_width(self) -> List:
        """Return list containing XDR width of type's components"""
        widths = []
        widths += ["XDR_bool"]
        for field in self.fields[0:-1]:
            widths += field.symbolic_width()
        return widths

    def __post_init__(self):
        structs.add(self.name)
        pass_by_reference.add(self.name)
        max_widths[self.name] = self.max_width()
        symbolic_widths[self.name] = self.symbolic_width()


@dataclass
class _XdrTypedef(_XdrAst):
    """An XDR typedef"""

    declaration: _XdrDeclaration

    def max_width(self) -> int:
        """Return width of type in XDR_UNITS"""
        return self.declaration.max_width()

    def symbolic_width(self) -> List:
        """Return list containing XDR width of type's components"""
        return self.declaration.symbolic_width()

    def __post_init__(self):
        if isinstance(self.declaration, _XdrBasic):
            new_type = self.declaration
            if isinstance(new_type.spec, _XdrDefinedType):
                if new_type.spec.type_name in pass_by_reference:
                    pass_by_reference.add(new_type.name)
                max_widths[new_type.name] = self.max_width()
                symbolic_widths[new_type.name] = self.symbolic_width()


@dataclass
class _XdrCaseSpec(_XdrAst):
    """One case in an XDR union"""

    values: List[str]
    arm: _XdrDeclaration
    template: str = "case_spec"


@dataclass
class _XdrDefaultSpec(_XdrAst):
    """Default case in an XDR union"""

    arm: _XdrDeclaration
    template: str = "default_spec"


@dataclass
class _XdrUnion(_XdrAst):
    """An XDR union"""

    name: str
    discriminant: _XdrDeclaration
    cases: List[_XdrCaseSpec]
    default: _XdrDeclaration

    def max_width(self) -> int:
        """Return width of type in XDR_UNITS"""
        max_width = 0
        for case in self.cases:
            if case.arm.max_width() > max_width:
                max_width = case.arm.max_width()
        if self.default:
            if self.default.arm.max_width() > max_width:
                max_width = self.default.arm.max_width()
        return 1 + max_width

    def symbolic_width(self) -> List:
        """Return list containing XDR width of type's components"""
        max_width = 0
        for case in self.cases:
            if case.arm.max_width() > max_width:
                max_width = case.arm.max_width()
                width = case.arm.symbolic_width()
        if self.default:
            if self.default.arm.max_width() > max_width:
                max_width = self.default.arm.max_width()
                width = self.default.arm.symbolic_width()
        return symbolic_widths[self.discriminant.name] + width

    def __post_init__(self):
        structs.add(self.name)
        pass_by_reference.add(self.name)
        max_widths[self.name] = self.max_width()
        symbolic_widths[self.name] = self.symbolic_width()


@dataclass
class _RpcProcedure(_XdrAst):
    """RPC procedure definition"""

    name: str
    number: int
    argument: _XdrTypeSpecifier
    result: _XdrTypeSpecifier


@dataclass
class _RpcVersion(_XdrAst):
    """RPC version definition"""

    name: str
    number: int
    procedures: List[_RpcProcedure]


@dataclass
class _RpcProgram(_XdrAst):
    """RPC program definition"""

    name: str
    number: int
    versions: List[_RpcVersion]


@dataclass
class _Pragma(_XdrAst):
    """Empty class for pragma directives"""


@dataclass
class _XdrPassthru(_XdrAst):
    """Passthrough line to emit verbatim in output"""

    content: str


@dataclass
class Definition(_XdrAst, ast_utils.WithMeta):
    """Corresponds to 'definition' in the grammar"""

    meta: Meta
    value: _XdrAst


@dataclass
class Specification(_XdrAst, ast_utils.AsList):
    """Corresponds to 'specification' in the grammar"""

    definitions: List[Definition]


class ParseToAst(Transformer):
    """Functions that transform productions into AST nodes"""

    def identifier(self, children):
        """Instantiate one _XdrIdentifier object"""
        token = children[0]
        return _XdrIdentifier(token.value, line=token.line, column=token.column)

    def value(self, children):
        """Instantiate one _XdrValue object"""
        if isinstance(children[0], _XdrIdentifier):
            return _XdrValue(children[0].symbol)
        return _XdrValue(children[0].children[0].value)

    def constant(self, children):
        """Instantiate one _XdrConstantValue object"""
        match children[0].data:
            case "decimal_constant":
                value = int(children[0].children[0].value, base=10)
            case "hexadecimal_constant":
                value = int(children[0].children[0].value, base=16)
            case "octal_constant":
                value = int(children[0].children[0].value, base=8)
        return _XdrConstantValue(value)

    def type_specifier(self, children):
        """Instantiate one _XdrTypeSpecifier object"""
        if isinstance(children[0], _XdrIdentifier):
            name = children[0].symbol
            return _XdrDefinedType(type_name=name)

        name = children[0].data.value
        return _XdrBuiltInType(type_name=name)

    def constant_def(self, children):
        """Instantiate one _XdrConstant object"""
        ident = children[0]
        value = children[1].value
        return _XdrConstant(ident.symbol, value, line=ident.line, column=ident.column)

    def enum(self, children):
        """Instantiate one _XdrEnum object"""
        name_ident = children[0]

        i = 0
        enumerators = []
        body = children[1]
        while i < len(body.children):
            ident = body.children[i]
            value = body.children[i + 1].value
            enumerators.append(
                _XdrEnumerator(
                    ident.symbol, value, line=ident.line, column=ident.column
                )
            )
            i = i + 2

        return _XdrEnum(
            name_ident.symbol,
            enumerators,
            line=name_ident.line,
            column=name_ident.column,
        )

    def fixed_length_opaque(self, children):
        """Instantiate one _XdrFixedLengthOpaque declaration object"""
        ident = children[0]
        size = children[1].value

        return _XdrFixedLengthOpaque(
            ident.symbol, size, line=ident.line, column=ident.column
        )

    def variable_length_opaque(self, children):
        """Instantiate one _XdrVariableLengthOpaque declaration object"""
        ident = children[0]
        if children[1] is not None:
            maxsize = children[1].value
        else:
            maxsize = "0"

        return _XdrVariableLengthOpaque(
            ident.symbol, maxsize, line=ident.line, column=ident.column
        )

    def string(self, children):
        """Instantiate one _XdrString declaration object"""
        ident = children[0]
        if children[1] is not None:
            maxsize = children[1].value
        else:
            maxsize = "0"

        return _XdrString(ident.symbol, maxsize, line=ident.line, column=ident.column)

    def fixed_length_array(self, children):
        """Instantiate one _XdrFixedLengthArray declaration object"""
        spec = children[0]
        ident = children[1]
        size = children[2].value

        return _XdrFixedLengthArray(
            ident.symbol, spec, size, line=ident.line, column=ident.column
        )

    def variable_length_array(self, children):
        """Instantiate one _XdrVariableLengthArray declaration object"""
        spec = children[0]
        ident = children[1]
        if children[2] is not None:
            maxsize = children[2].value
        else:
            maxsize = "0"

        return _XdrVariableLengthArray(
            ident.symbol, spec, maxsize, line=ident.line, column=ident.column
        )

    def optional_data(self, children):
        """Instantiate one _XdrOptionalData declaration object"""
        spec = children[0]
        ident = children[1]

        return _XdrOptionalData(
            ident.symbol, spec, line=ident.line, column=ident.column
        )

    def basic(self, children):
        """Instantiate one _XdrBasic object"""
        spec = children[0]
        ident = children[1]

        return _XdrBasic(ident.symbol, spec, line=ident.line, column=ident.column)

    def void(self, children):
        """Instantiate one _XdrVoid declaration object"""

        return _XdrVoid()

    def struct(self, children):
        """Instantiate one _XdrStruct object"""
        ident = children[0]
        name = ident.symbol
        fields = children[1].children
        pos = {"line": ident.line, "column": ident.column}

        last_field = fields[-1]
        if (
            isinstance(last_field, _XdrOptionalData)
            and name == last_field.spec.type_name
        ):
            return _XdrPointer(name, fields, **pos)

        return _XdrStruct(name, fields, **pos)

    def typedef(self, children):
        """Instantiate one _XdrTypedef object"""
        new_type = children[0]

        return _XdrTypedef(new_type)

    def case_spec(self, children):
        """Instantiate one _XdrCaseSpec object"""
        values = []
        for item in children[0:-1]:
            values.append(item.value)
        arm = children[-1]

        return _XdrCaseSpec(values, arm)

    def default_spec(self, children):
        """Instantiate one _XdrDefaultSpec object"""
        arm = children[0]

        return _XdrDefaultSpec(arm)

    def union(self, children):
        """Instantiate one _XdrUnion object"""
        ident = children[0]

        body = children[1]
        discriminant = body.children[0].children[0]
        cases = body.children[1:-1]
        default = body.children[-1]

        return _XdrUnion(
            ident.symbol,
            discriminant,
            cases,
            default,
            line=ident.line,
            column=ident.column,
        )

    def procedure_def(self, children):
        """Instantiate one _RpcProcedure object"""
        result = children[0]
        ident = children[1]
        argument = children[2]
        number = children[3].value

        return _RpcProcedure(
            ident.symbol,
            number,
            argument,
            result,
            line=ident.line,
            column=ident.column,
        )

    def version_def(self, children):
        """Instantiate one _RpcVersion object"""
        ident = children[0]
        number = children[-1].value
        procedures = children[1:-1]

        return _RpcVersion(
            ident.symbol, number, procedures, line=ident.line, column=ident.column
        )

    def program_def(self, children):
        """Instantiate one _RpcProgram object"""
        ident = children[0]
        number = children[-1].value
        versions = children[1:-1]

        return _RpcProgram(
            ident.symbol, number, versions, line=ident.line, column=ident.column
        )

    def pragma_def(self, children):
        """Instantiate one _Pragma object"""
        directive = children[0].children[0].data
        match directive:
            case "big_endian_directive":
                big_endian.append(children[1].symbol)
            case "exclude_directive":
                excluded_apis.append(children[1].symbol)
            case "header_directive":
                global header_name
                header_name = children[1].symbol
            case "public_directive":
                public_apis.append(children[1].symbol)
            case _:
                raise NotImplementedError("Directive not supported")
        return _Pragma()

    def passthru_def(self, children):
        """Instantiate one _XdrPassthru object"""
        token = children[0]
        content = token.value[1:]
        return _XdrPassthru(content)


transformer = ast_utils.create_transformer(this_module, ParseToAst())


def _merge_consecutive_passthru(definitions: List[Definition]) -> List[Definition]:
    """Merge consecutive passthru definitions into single nodes"""
    result = []
    i = 0
    while i < len(definitions):
        if isinstance(definitions[i].value, _XdrPassthru):
            lines = [definitions[i].value.content]
            meta = definitions[i].meta
            j = i + 1
            while j < len(definitions) and isinstance(
                definitions[j].value, _XdrPassthru
            ):
                lines.append(definitions[j].value.content)
                j += 1
            merged = _XdrPassthru("\n".join(lines))
            result.append(Definition(meta, merged))
            i = j
        else:
            result.append(definitions[i])
            i += 1
    return result


def _meta_line(meta) -> int:
    """Return the 1-based source line for a node's meta, or 0 if unknown"""
    try:
        return meta.line
    except AttributeError:
        return 0


class XdrSemanticError(Exception):
    """A specification that parses but violates an XDR semantic rule.

    Detection lives in the language-independent front end because a
    duplicate name is malformed XDR regardless of the output language.
    """

    def __init__(self, message: str, meta):
        super().__init__(message)
        self.message = message
        self.line = _meta_line(meta)
        self.column = getattr(meta, "column", 0)


def _introduced_names(value):
    """Yield (name, node) for each identifier a definition introduces."""
    if isinstance(value, (_XdrStruct, _XdrUnion, _XdrPointer)):
        yield value.name, value
    elif isinstance(value, _XdrEnum):
        yield value.name, value
        for enumerator in value.enumerators:
            yield enumerator.name, enumerator
    elif isinstance(value, _XdrTypedef):
        yield value.declaration.name, value.declaration
    elif isinstance(value, _XdrConstant):
        yield value.name, value
    elif isinstance(value, _RpcProgram):
        yield value.name, value


def _check_rpc_scope_names(program: "_RpcProgram") -> None:
    """Enforce RFC 5531 Section 12.3 scoping within an RPC program.

    A version name and number are unique within the program and a
    procedure name and number are unique within its version.
    """
    version_names = set()
    version_numbers = set()
    for version in program.versions:
        if version.name in version_names:
            raise XdrSemanticError(
                f"duplicate version name '{version.name}'"
                f" in program '{program.name}'",
                version,
            )
        version_names.add(version.name)
        if version.number in version_numbers:
            raise XdrSemanticError(
                f"duplicate version number {version.number}"
                f" in program '{program.name}'",
                version,
            )
        version_numbers.add(version.number)
        procedure_names = set()
        procedure_numbers = set()
        for procedure in version.procedures:
            if procedure.name in procedure_names:
                raise XdrSemanticError(
                    f"duplicate procedure name '{procedure.name}'"
                    f" in version '{version.name}'",
                    procedure,
                )
            procedure_names.add(procedure.name)
            if procedure.number in procedure_numbers:
                raise XdrSemanticError(
                    f"duplicate procedure number {procedure.number}"
                    f" in version '{version.name}'",
                    procedure,
                )
            procedure_numbers.add(procedure.number)


def check_duplicate_definitions(root: "Specification") -> None:
    """Reject a spec that declares an identifier more than once.

    RFC 4506 Section 6.4 places constant and type identifiers in a
    single name space that must be unique within a specification.
    RFC 5531 Section 12.3 adds RPC program names to that name space
    and scopes version names and numbers to their program and
    procedure names and numbers to their version.
    """
    seen = {}
    for definition in root.definitions:
        for name, node in _introduced_names(definition.value):
            where = node if node.line else definition.meta
            first = seen.get(name)
            if first is not None:
                raise XdrSemanticError(
                    f"duplicate identifier '{name}'"
                    f" (first declared at line {_meta_line(first)})",
                    where,
                )
            seen[name] = where
        if isinstance(definition.value, _RpcProgram):
            _check_rpc_scope_names(definition.value)


# RFC 5531 (Section 9) encodes program, version, and procedure numbers
# as unsigned 32-bit integers, so each must fall within [0, 2**32 - 1].
_RPC_NUMBER_MAX = 2**32 - 1


def _check_rpc_number(kind: str, number: int, scope: str, meta) -> None:
    """Reject one RPC number that is negative or wider than 32 bits."""
    if number < 0:
        raise XdrSemanticError(
            f"negative {kind} number {number} {scope}",
            meta,
        )
    if number > _RPC_NUMBER_MAX:
        raise XdrSemanticError(
            f"{kind} number {number} {scope} exceeds {_RPC_NUMBER_MAX}",
            meta,
        )


def check_rpc_number_range(root: "Specification") -> None:
    """Reject an out-of-range program, version, or procedure number.

    RFC 5531 assigns only unsigned constants to program, version, and
    procedure numbers (Section 12.3) and encodes each as an unsigned
    32-bit integer (Section 9). RFC 4506 Section 6.2 permits a signed
    decimal constant for XDR constants in general and sets no ceiling on
    magnitude, so the grammar accepts an out-of-range value; the range
    is enforced here instead. The parser retains no per-version or
    per-procedure source location, so a violation is reported against the
    program definition.
    """
    for definition in root.definitions:
        program = definition.value
        if not isinstance(program, _RpcProgram):
            continue
        _check_rpc_number(
            "program",
            program.number,
            f"in program '{program.name}'",
            definition.meta,
        )
        for version in program.versions:
            _check_rpc_number(
                "version",
                version.number,
                f"in program '{program.name}'",
                definition.meta,
            )
            for procedure in version.procedures:
                _check_rpc_number(
                    "procedure",
                    procedure.number,
                    f"in version '{version.name}'",
                    definition.meta,
                )


def transform_parse_tree(parse_tree):
    """Transform productions into an abstract syntax tree"""
    ast = transformer.transform(parse_tree)
    ast.definitions = _merge_consecutive_passthru(ast.definitions)
    check_duplicate_definitions(ast)
    check_rpc_number_range(ast)
    return ast


def get_header_name() -> str:
    """Return header name set by pragma header directive"""
    return header_name