-
Notifications
You must be signed in to change notification settings - Fork 35
/
Copy pathasdl_rs.py
executable file
·2232 lines (1900 loc) · 71.1 KB
/
asdl_rs.py
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
# spell-checker:words dfn dfns
# ! /usr/bin/env python
"""Generate Rust code from an ASDL description."""
import sys
import json
import textwrap
import re
from argparse import ArgumentParser
from pathlib import Path
from typing import Optional, Dict, Any
import asdl
TABSIZE = 4
AUTO_GEN_MESSAGE = "// File automatically generated by {}.\n\n"
BUILTIN_TYPE_NAMES = {
"identifier": "Identifier",
"string": "String",
"int": "Int",
"constant": "Constant",
}
assert BUILTIN_TYPE_NAMES.keys() == asdl.builtin_types
BUILTIN_INT_NAMES = {
"simple": "bool",
"is_async": "bool",
"conversion": "ConversionFlag",
}
RENAME_MAP = {
"cmpop": "cmp_op",
"unaryop": "unary_op",
"boolop": "bool_op",
"excepthandler": "except_handler",
"withitem": "with_item",
}
RUST_KEYWORDS = {
"if",
"while",
"for",
"return",
"match",
"try",
"await",
"yield",
"in",
"mod",
"type",
}
attributes = [
asdl.Field("int", "lineno"),
asdl.Field("int", "col_offset"),
asdl.Field("int", "end_lineno"),
asdl.Field("int", "end_col_offset"),
]
ORIGINAL_NODE_WARNING = "NOTE: This type is different from original Python AST."
arg_with_default = asdl.Type(
"arg_with_default",
asdl.Product(
[
asdl.Field("arg", "def"),
asdl.Field(
"expr", "default", opt=True
), # order is important for cost-free borrow!
],
),
)
arg_with_default.doc = f"""
An alternative type of AST `arg`. This is used for each function argument that might have a default value.
Used by `Arguments` original type.
{ORIGINAL_NODE_WARNING}
""".strip()
alt_arguments = asdl.Type(
"alt:arguments",
asdl.Product(
[
asdl.Field("arg_with_default", "posonlyargs", seq=True),
asdl.Field("arg_with_default", "args", seq=True),
asdl.Field("arg", "vararg", opt=True),
asdl.Field("arg_with_default", "kwonlyargs", seq=True),
asdl.Field("arg", "kwarg", opt=True),
]
),
)
alt_arguments.doc = f"""
An alternative type of AST `arguments`. This is parser-friendly and human-friendly definition of function arguments.
This form also has advantage to implement pre-order traverse.
`defaults` and `kw_defaults` fields are removed and the default values are placed under each `arg_with_default` typed argument.
`vararg` and `kwarg` are still typed as `arg` because they never can have a default value.
The matching Python style AST type is [PythonArguments]. While [PythonArguments] has ordered `kwonlyargs` fields by
default existence, [Arguments] has location-ordered kwonlyargs fields.
{ORIGINAL_NODE_WARNING}
""".strip()
# Must be used only for rust types, not python types
CUSTOM_TYPES = [
alt_arguments,
arg_with_default,
]
CUSTOM_REPLACEMENTS = {
"arguments": alt_arguments,
}
CUSTOM_ATTACHMENTS = [
arg_with_default,
]
def maybe_custom(type):
return CUSTOM_REPLACEMENTS.get(type.name, type)
def rust_field_name(name):
name = rust_type_name(name)
return re.sub(r"(?<!^)(?=[A-Z])", "_", name).lower()
def rust_type_name(name):
"""Return a string for the C name of the type.
This function special cases the default types provided by asdl.
"""
name = RENAME_MAP.get(name, name)
if name in asdl.builtin_types:
builtin = BUILTIN_TYPE_NAMES[name]
return builtin
elif name.islower():
return "".join(part.capitalize() for part in name.split("_"))
else:
return name
def is_simple(sum):
"""Return True if a sum is a simple.
A sum is simple if its types have no fields, e.g.
unaryop = Invert | Not | UAdd | USub
"""
for t in sum.types:
if t.fields:
return False
return True
def asdl_of(name, obj):
if isinstance(obj, asdl.Product) or isinstance(obj, asdl.Constructor):
fields = ", ".join(map(str, obj.fields))
if fields:
fields = "({})".format(fields)
return "{}{}".format(name, fields)
else:
if is_simple(obj):
types = " | ".join(type.name for type in obj.types)
else:
sep = "\n{}| ".format(" " * (len(name) + 1))
types = sep.join(asdl_of(type.name, type) for type in obj.types)
return "{} = {}".format(name, types)
class TypeInfo:
type: asdl.Type
enum_name: Optional[str]
has_user_data: Optional[bool]
has_attributes: bool
is_simple: bool
children: set
fields: Optional[Any]
boxed: bool
def __init__(self, type):
self.type = type
self.enum_name = None
self.has_user_data = None
self.has_attributes = False
self.is_simple = False
self.children = set()
self.fields = None
self.boxed = False
def __repr__(self):
return f"<TypeInfo: {self.name}>"
@property
def name(self):
return self.type.name
@property
def is_type(self):
return isinstance(self.type, asdl.Type)
@property
def is_product(self):
return self.is_type and isinstance(self.type.value, asdl.Product)
@property
def is_sum(self):
return self.is_type and isinstance(self.type.value, asdl.Sum)
@property
def has_expr(self):
return self.is_product and any(
f.type != "identifier" for f in self.type.value.fields
)
@property
def is_custom(self):
return self.type.name in [t.name for t in CUSTOM_TYPES]
@property
def is_custom_replaced(self):
return self.type.name in CUSTOM_REPLACEMENTS
@property
def custom(self):
if self.type.name in CUSTOM_REPLACEMENTS:
return CUSTOM_REPLACEMENTS[self.type.name]
return self.type
def no_cfg(self, typeinfo):
if self.is_product:
return self.has_attributes
elif self.enum_name:
return typeinfo[self.enum_name].has_attributes
else:
return self.has_attributes
@property
def rust_name(self):
return rust_type_name(self.name)
@property
def full_field_name(self):
name = self.name
if name.startswith("alt:"):
name = name[4:]
if self.enum_name is None:
return name
else:
return f"{self.enum_name}_{rust_field_name(name)}"
@property
def full_type_name(self):
name = self.name
if name.startswith("alt:"):
name = name[4:]
rust_name = rust_type_name(name)
if self.enum_name is not None:
rust_name = rust_type_name(self.enum_name) + rust_name
if self.is_custom_replaced:
rust_name = "Python" + rust_name
return rust_name
def determine_user_data(self, type_info, stack):
if self.name in stack:
return None
stack.add(self.name)
for child, child_seq in self.children:
if child in asdl.builtin_types:
continue
child_info = type_info[child]
child_has_user_data = child_info.determine_user_data(type_info, stack)
if self.has_user_data is None and child_has_user_data is True:
self.has_user_data = True
stack.remove(self.name)
return self.has_user_data
class TypeInfoMixin:
type_info: Dict[str, TypeInfo]
def customized_type_info(self, type_name):
info = self.type_info[type_name]
return self.type_info[info.custom.name]
def has_user_data(self, typ):
return self.type_info[typ].has_user_data
def apply_generics(self, typ, *generics):
needs_generics = not self.type_info[typ].is_simple
if needs_generics:
return [f"<{g}>" for g in generics]
else:
return ["" for g in generics]
class EmitVisitor(asdl.VisitorBase, TypeInfoMixin):
"""Visit that emits lines"""
def __init__(self, file, type_info):
self.file = file
self.type_info = type_info
self.identifiers = set()
super(EmitVisitor, self).__init__()
def emit_identifier(self, name):
name = str(name)
if name in self.identifiers:
return
self.emit("_Py_IDENTIFIER(%s);" % name, 0)
self.identifiers.add(name)
def emit(self, line, depth):
if line:
line = (" " * TABSIZE * depth) + textwrap.dedent(line)
self.file.write(line + "\n")
class FindUserDataTypesVisitor(asdl.VisitorBase):
def __init__(self, type_info):
self.type_info = type_info
super().__init__()
def visitModule(self, mod):
for dfn in mod.dfns + CUSTOM_TYPES:
self.visit(dfn)
stack = set()
for info in self.type_info.values():
info.determine_user_data(self.type_info, stack)
def visitType(self, type):
key = type.name
info = self.type_info[key] = TypeInfo(type)
self.visit(type.value, info)
def visitSum(self, sum, info):
type = info.type
info.is_simple = is_simple(sum)
for cons in sum.types:
self.visit(cons, type, info.is_simple)
if info.is_simple:
info.has_user_data = False
return
for t in sum.types:
self.add_children(t.name, t.fields)
if len(sum.types) > 1:
info.boxed = True
if sum.attributes:
# attributes means located, which has the `range: R` field
info.has_user_data = True
info.has_attributes = True
for variant in sum.types:
self.add_children(type.name, variant.fields)
def visitConstructor(self, cons, type, simple):
info = self.type_info[cons.name] = TypeInfo(cons)
info.enum_name = type.name
info.is_simple = simple
def visitProduct(self, product, info):
type = info.type
if product.attributes:
# attributes means located, which has the `range: R` field
info.has_user_data = True
info.has_attributes = True
if len(product.fields) > 2:
info.boxed = True
self.add_children(type.name, product.fields)
def add_children(self, name, fields):
self.type_info[name].children.update(
(field.type, field.seq) for field in fields
)
def rust_field(field_name):
if field_name in RUST_KEYWORDS:
field_name += "_"
return field_name
class StructVisitor(EmitVisitor):
"""Visitor to generate type-defs for AST."""
def __init__(self, *args, **kw):
super().__init__(*args, **kw)
def emit_attrs(self, depth):
self.emit("#[derive(Clone, Debug, PartialEq)]", depth)
def emit_range(self, has_attributes, depth):
if has_attributes:
self.emit("pub range: R,", depth + 1)
else:
self.emit("pub range: OptionalRange<R>,", depth + 1)
def visitModule(self, mod):
self.emit_attrs(0)
self.emit(
"""
#[derive(is_macro::Is)]
pub enum Ast<R=TextRange> {
""",
0,
)
for dfn in mod.dfns:
info = self.customized_type_info(dfn.name)
dfn = info.custom
rust_name = info.full_type_name
generics = "" if self.type_info[dfn.name].is_simple else "<R>"
if dfn.name == "mod":
# This is exceptional rule to other enums.
# Unlike other enums, this is justified because `Mod` is only used as
# the top node of parsing result and never a child node of other nodes.
# Because it will be very rarely used in very particular applications,
# "ast_" prefix to everywhere seems less useful.
self.emit('#[is(name = "module")]', 1)
self.emit(f"{rust_name}({rust_name}{generics}),", 1)
self.emit(
"""
}
impl<R> Node for Ast<R> {
const NAME: &'static str = "AST";
const FIELD_NAMES: &'static [&'static str] = &[];
}
""",
0,
)
for dfn in mod.dfns:
info = self.customized_type_info(dfn.name)
rust_name = info.full_type_name
generics = "" if self.type_info[dfn.name].is_simple else "<R>"
self.emit(
f"""
impl<R> From<{rust_name}{generics}> for Ast<R> {{
fn from(node: {rust_name}{generics}) -> Self {{
Ast::{rust_name}(node)
}}
}}
""",
0,
)
for dfn in mod.dfns + CUSTOM_TYPES:
self.visit(dfn)
def visitType(self, type, depth=0):
if hasattr(type, "doc"):
doc = "/// " + type.doc.replace("\n", "\n/// ") + "\n"
else:
doc = f"/// See also [{type.name}](https://docs.python.org/3/library/ast.html#ast.{type.name})"
self.emit(doc, depth)
self.visit(type.value, type, depth)
def visitSum(self, sum, type, depth):
if is_simple(sum):
self.simple_sum(sum, type, depth)
else:
self.sum_with_constructors(sum, type, depth)
(generics_applied,) = self.apply_generics(type.name, "R")
self.emit(
f"""
impl{generics_applied} Node for {rust_type_name(type.name)}{generics_applied} {{
const NAME: &'static str = "{type.name}";
const FIELD_NAMES: &'static [&'static str] = &[];
}}
""",
depth,
)
def simple_sum(self, sum, type, depth):
rust_name = rust_type_name(type.name)
self.emit_attrs(depth)
self.emit("#[derive(is_macro::Is, Copy, Hash, Eq)]", depth)
self.emit(f"pub enum {rust_name} {{", depth)
for cons in sum.types:
self.emit(f"{cons.name},", depth + 1)
self.emit("}", depth)
self.emit(f"impl {rust_name} {{", depth)
needs_escape = any(rust_field_name(t.name) in RUST_KEYWORDS for t in sum.types)
if needs_escape:
prefix = rust_field_name(type.name) + "_"
else:
prefix = ""
for cons in sum.types:
self.emit(
f"""
#[inline]
pub const fn {prefix}{rust_field_name(cons.name)}(&self) -> Option<{rust_name}{cons.name}> {{
match self {{
{rust_name}::{cons.name} => Some({rust_name}{cons.name}),
_ => None,
}}
}}
""",
depth,
)
self.emit("}", depth)
self.emit("", depth)
for cons in sum.types:
self.emit(
f"""
pub struct {rust_name}{cons.name};
impl From<{rust_name}{cons.name}> for {rust_name} {{
fn from(_: {rust_name}{cons.name}) -> Self {{
{rust_name}::{cons.name}
}}
}}
impl<R> From<{rust_name}{cons.name}> for Ast<R> {{
fn from(_: {rust_name}{cons.name}) -> Self {{
{rust_name}::{cons.name}.into()
}}
}}
impl Node for {rust_name}{cons.name} {{
const NAME: &'static str = "{cons.name}";
const FIELD_NAMES: &'static [&'static str] = &[];
}}
impl std::cmp::PartialEq<{rust_name}> for {rust_name}{cons.name} {{
#[inline]
fn eq(&self, other: &{rust_name}) -> bool {{
matches!(other, {rust_name}::{cons.name})
}}
}}
""",
0,
)
def sum_with_constructors(self, sum, type, depth):
type_info = self.type_info[type.name]
rust_name = rust_type_name(type.name)
self.emit_attrs(depth)
self.emit("#[derive(is_macro::Is)]", depth)
self.emit(f"pub enum {rust_name}<R = TextRange> {{", depth)
needs_escape = any(rust_field_name(t.name) in RUST_KEYWORDS for t in sum.types)
for t in sum.types:
if needs_escape:
self.emit(
f'#[is(name = "{rust_field_name(t.name)}_{rust_name.lower()}")]',
depth + 1,
)
self.emit(f"{t.name}({rust_name}{t.name}<R>),", depth + 1)
self.emit("}", depth)
self.emit("", depth)
for t in sum.types:
self.sum_subtype_struct(type_info, t, rust_name, depth)
def sum_subtype_struct(self, sum_type_info, t, rust_name, depth):
self.emit(f"""/// See also [{t.name}](https://docs.python.org/3/library/ast.html#ast.{t.name})""", depth)
self.emit_attrs(depth)
payload_name = f"{rust_name}{t.name}"
self.emit(f"pub struct {payload_name}<R = TextRange> {{", depth)
self.emit_range(sum_type_info.has_attributes, depth)
for f in t.fields:
self.visit(f, sum_type_info, "pub ", depth + 1, t.name)
assert sum_type_info.has_attributes == self.type_info[t.name].no_cfg(
self.type_info
)
self.emit("}", depth)
field_names = [f'"{f.name}"' for f in t.fields]
self.emit(
f"""
impl<R> Node for {payload_name}<R> {{
const NAME: &'static str = "{t.name}";
const FIELD_NAMES: &'static [&'static str] = &[{', '.join(field_names)}];
}}
impl<R> From<{payload_name}<R>> for {rust_name}<R> {{
fn from(payload: {payload_name}<R>) -> Self {{
{rust_name}::{t.name}(payload)
}}
}}
impl<R> From<{payload_name}<R>> for Ast<R> {{
fn from(payload: {payload_name}<R>) -> Self {{
{rust_name}::from(payload).into()
}}
}}
""",
depth,
)
self.emit("", depth)
def visitConstructor(self, cons, parent, depth):
if cons.fields:
self.emit(f"{cons.name} {{", depth)
for f in cons.fields:
self.visit(f, parent, "", depth + 1, cons.name)
self.emit("},", depth)
else:
self.emit(f"{cons.name},", depth)
def visitField(self, field, parent, vis, depth, constructor=None):
try:
field_type = self.customized_type_info(field.type)
typ = field_type.full_type_name
except KeyError:
field_type = None
typ = rust_type_name(field.type)
if field_type and not field_type.is_simple:
typ = f"{typ}<R>"
# don't box if we're doing Vec<T>, but do box if we're doing Vec<Option<Box<T>>>
if (
field_type
and field_type.boxed
and (not (parent.is_product or field.seq) or field.opt)
):
typ = f"Box<{typ}>"
if field.opt or (
# When a dictionary literal contains dictionary unpacking (e.g., `{**d}`),
# the expression to be unpacked goes in `values` with a `None` at the corresponding
# position in `keys`. To handle this, the type of `keys` needs to be `Option<Vec<T>>`.
constructor == "Dict"
and field.name == "keys"
):
typ = f"Option<{typ}>"
if field.seq:
typ = f"Vec<{typ}>"
if typ == "Int":
typ = BUILTIN_INT_NAMES.get(field.name, typ)
name = rust_field(field.name)
self.emit(f"{vis}{name}: {typ},", depth)
def visitProduct(self, product, type, depth):
type_info = self.type_info[type.name]
product_name = type_info.full_type_name
self.emit_attrs(depth)
self.emit(f"pub struct {product_name}<R = TextRange> {{", depth)
self.emit_range(product.attributes, depth + 1)
for f in product.fields:
self.visit(f, type_info, "pub ", depth + 1)
assert bool(product.attributes) == type_info.no_cfg(self.type_info)
self.emit("}", depth)
field_names = [f'"{f.name}"' for f in product.fields]
self.emit(
f"""
impl<R> Node for {product_name}<R> {{
const NAME: &'static str = "{type.name}";
const FIELD_NAMES: &'static [&'static str] = &[
{', '.join(field_names)}
];
}}
""",
depth,
)
class FoldTraitDefVisitor(EmitVisitor):
def visitModule(self, mod, depth):
self.emit("pub trait Fold<U> {", depth)
self.emit("type TargetU;", depth + 1)
self.emit("type Error;", depth + 1)
self.emit("type UserContext;", depth + 1)
self.emit(
"""
fn will_map_user(&mut self, user: &U) -> Self::UserContext;
#[cfg(feature = "all-nodes-with-ranges")]
fn will_map_user_cfg(&mut self, user: &U) -> Self::UserContext {
self.will_map_user(user)
}
#[cfg(not(feature = "all-nodes-with-ranges"))]
fn will_map_user_cfg(&mut self, _user: &crate::EmptyRange<U>) -> crate::EmptyRange<Self::TargetU> {
crate::EmptyRange::default()
}
fn map_user(&mut self, user: U, context: Self::UserContext) -> Result<Self::TargetU, Self::Error>;
#[cfg(feature = "all-nodes-with-ranges")]
fn map_user_cfg(&mut self, user: U, context: Self::UserContext) -> Result<Self::TargetU, Self::Error> {
self.map_user(user, context)
}
#[cfg(not(feature = "all-nodes-with-ranges"))]
fn map_user_cfg(
&mut self,
_user: crate::EmptyRange<U>,
_context: crate::EmptyRange<Self::TargetU>,
) -> Result<crate::EmptyRange<Self::TargetU>, Self::Error> {
Ok(crate::EmptyRange::default())
}
""",
depth + 1,
)
self.emit(
"""
fn fold<X: Foldable<U, Self::TargetU>>(&mut self, node: X) -> Result<X::Mapped, Self::Error> {
node.fold(self)
}""",
depth + 1,
)
for dfn in mod.dfns + [arg_with_default]:
dfn = maybe_custom(dfn)
self.visit(dfn, depth + 2)
self.emit("}", depth)
def visitType(self, type, depth):
info = self.type_info[type.name]
apply_u, apply_target_u = self.apply_generics(info.name, "U", "Self::TargetU")
enum_name = info.full_type_name
self.emit(
f"fn fold_{info.full_field_name}(&mut self, node: {enum_name}{apply_u}) -> Result<{enum_name}{apply_target_u}, Self::Error> {{",
depth,
)
self.emit(f"fold_{info.full_field_name}(self, node)", depth + 1)
self.emit("}", depth)
if isinstance(type.value, asdl.Sum) and not is_simple(type.value):
for cons in type.value.types:
self.visit(cons, type, depth)
def visitConstructor(self, cons, type, depth):
info = self.type_info[type.name]
apply_u, apply_target_u = self.apply_generics(type.name, "U", "Self::TargetU")
enum_name = rust_type_name(type.name)
func_name = f"fold_{info.full_field_name}_{rust_field_name(cons.name)}"
self.emit(
f"fn {func_name}(&mut self, node: {enum_name}{cons.name}{apply_u}) -> Result<{enum_name}{cons.name}{apply_target_u}, Self::Error> {{",
depth,
)
self.emit(f"{func_name}(self, node)", depth + 1)
self.emit("}", depth)
class FoldImplVisitor(EmitVisitor):
def visitModule(self, mod, depth):
for dfn in mod.dfns + [arg_with_default]:
dfn = maybe_custom(dfn)
self.visit(dfn, depth)
def visitType(self, type, depth=0):
self.visit(type.value, type, depth)
def visitSum(self, sum, type, depth):
name = type.name
apply_t, apply_u, apply_target_u = self.apply_generics(
name, "T", "U", "F::TargetU"
)
enum_name = rust_type_name(name)
simple = is_simple(sum)
self.emit(f"impl<T, U> Foldable<T, U> for {enum_name}{apply_t} {{", depth)
self.emit(f"type Mapped = {enum_name}{apply_u};", depth + 1)
self.emit(
"fn fold<F: Fold<T, TargetU = U> + ?Sized>(self, folder: &mut F) -> Result<Self::Mapped, F::Error> {",
depth + 1,
)
self.emit(f"folder.fold_{name}(self)", depth + 2)
self.emit("}", depth + 1)
self.emit("}", depth)
self.emit(
f"pub fn fold_{name}<U, F: Fold<U> + ?Sized>(#[allow(unused)] folder: &mut F, node: {enum_name}{apply_u}) -> Result<{enum_name}{apply_target_u}, F::Error> {{",
depth,
)
if simple:
self.emit("Ok(node) }", depth + 1)
return
self.emit("let folded = match node {", depth + 1)
for cons in sum.types:
self.emit(
f"{enum_name}::{cons.name}(cons) => {enum_name}::{cons.name}(Foldable::fold(cons, folder)?),",
depth + 1,
)
self.emit("};", depth + 1)
self.emit("Ok(folded)", depth + 1)
self.emit("}", depth)
for cons in sum.types:
self.visit(cons, type, depth)
def visitConstructor(self, cons, type, depth):
apply_t, apply_u, apply_target_u = self.apply_generics(
type.name, "T", "U", "F::TargetU"
)
info = self.type_info[type.name]
enum_name = info.full_type_name
cons_type_name = f"{enum_name}{cons.name}"
self.emit(f"impl<T, U> Foldable<T, U> for {cons_type_name}{apply_t} {{", depth)
self.emit(f"type Mapped = {cons_type_name}{apply_u};", depth + 1)
self.emit(
"fn fold<F: Fold<T, TargetU = U> + ?Sized>(self, folder: &mut F) -> Result<Self::Mapped, F::Error> {",
depth + 1,
)
self.emit(
f"folder.fold_{info.full_field_name}_{rust_field_name(cons.name)}(self)",
depth + 2,
)
self.emit("}", depth + 1)
self.emit("}", depth)
self.emit(
f"pub fn fold_{info.full_field_name}_{rust_field_name(cons.name)}<U, F: Fold<U> + ?Sized>(#[allow(unused)] folder: &mut F, node: {cons_type_name}{apply_u}) -> Result<{enum_name}{cons.name}{apply_target_u}, F::Error> {{",
depth,
)
fields_pattern = self.make_pattern(cons.fields)
map_user_suffix = "" if info.has_attributes else "_cfg"
self.emit(
f"""
let {cons_type_name} {{ {fields_pattern} }} = node;
let context = folder.will_map_user{map_user_suffix}(&range);
""",
depth + 3,
)
self.fold_fields(cons.fields, depth + 3)
self.emit(
f"let range = folder.map_user{map_user_suffix}(range, context)?;",
depth + 3,
)
self.composite_fields(f"{cons_type_name}", cons.fields, depth + 3)
self.emit("}", depth + 2)
def visitProduct(self, product, type, depth):
info = self.type_info[type.name]
name = type.name
apply_t, apply_u, apply_target_u = self.apply_generics(
name, "T", "U", "F::TargetU"
)
struct_name = info.full_type_name
has_attributes = bool(product.attributes)
self.emit(f"impl<T, U> Foldable<T, U> for {struct_name}{apply_t} {{", depth)
self.emit(f"type Mapped = {struct_name}{apply_u};", depth + 1)
self.emit(
"fn fold<F: Fold<T, TargetU = U> + ?Sized>(self, folder: &mut F) -> Result<Self::Mapped, F::Error> {",
depth + 1,
)
self.emit(f"folder.fold_{info.full_field_name}(self)", depth + 2)
self.emit("}", depth + 1)
self.emit("}", depth)
self.emit(
f"pub fn fold_{info.full_field_name}<U, F: Fold<U> + ?Sized>(#[allow(unused)] folder: &mut F, node: {struct_name}{apply_u}) -> Result<{struct_name}{apply_target_u}, F::Error> {{",
depth,
)
fields_pattern = self.make_pattern(product.fields)
self.emit(f"let {struct_name} {{ {fields_pattern} }} = node;", depth + 1)
map_user_suffix = "" if has_attributes else "_cfg"
self.emit(
f"let context = folder.will_map_user{map_user_suffix}(&range);", depth + 3
)
self.fold_fields(product.fields, depth + 1)
self.emit(
f"let range = folder.map_user{map_user_suffix}(range, context)?;", depth + 3
)
self.composite_fields(struct_name, product.fields, depth + 1)
self.emit("}", depth)
def make_pattern(self, fields):
body = ",".join(rust_field(f.name) for f in fields)
if body:
body += ","
body += "range"
return body
def fold_fields(self, fields, depth):
for field in fields:
name = rust_field(field.name)
self.emit(f"let {name} = Foldable::fold({name}, folder)?;", depth + 1)
def composite_fields(self, header, fields, depth):
self.emit(f"Ok({header} {{", depth)
for field in fields:
name = rust_field(field.name)
self.emit(f"{name},", depth + 1)
self.emit("range,", depth + 1)
self.emit("})", depth)
class FoldModuleVisitor(EmitVisitor):
def visitModule(self, mod):
depth = 0
FoldTraitDefVisitor(self.file, self.type_info).visit(mod, depth)
FoldImplVisitor(self.file, self.type_info).visit(mod, depth)
class VisitorModuleVisitor(StructVisitor):
def full_name(self, name):
type_info = self.type_info[name]
if type_info.enum_name:
return f"{type_info.enum_name}_{name}"
else:
return name
def node_type_name(self, name):
type_info = self.type_info[name]
if type_info.enum_name:
return f"{rust_type_name(type_info.enum_name)}{rust_type_name(name)}"
else:
return rust_type_name(name)
def visitModule(self, mod, depth=0):
self.emit("#[allow(unused_variables)]", depth)
self.emit("pub trait Visitor<R=crate::text_size::TextRange> {", depth)
for dfn in mod.dfns:
dfn = self.customized_type_info(dfn.name).type
self.visit(dfn, depth + 1)
self.emit("}", depth)
def visitType(self, type, depth=0):
self.visit(type.value, type.name, depth)
def visitSum(self, sum, name, depth):
if is_simple(sum):
self.simple_sum(sum, name, depth)
else:
self.sum_with_constructors(sum, name, depth)
def emit_visitor(self, nodename, depth, has_node=True):
type_info = self.type_info[nodename]
node_type = type_info.full_type_name
(generic,) = self.apply_generics(nodename, "R")
self.emit(
f"fn visit_{type_info.full_field_name}(&mut self, node: {node_type}{generic}) {{",
depth,
)
if has_node:
self.emit(
f"self.generic_visit_{type_info.full_field_name}(node)", depth + 1
)
self.emit("}", depth)
def emit_generic_visitor_signature(self, nodename, depth, has_node=True):
type_info = self.type_info[nodename]
if has_node:
node_type = type_info.full_type_name
else:
node_type = "()"
(generic,) = self.apply_generics(nodename, "R")
self.emit(
f"fn generic_visit_{type_info.full_field_name}(&mut self, node: {node_type}{generic}) {{",
depth,
)
def emit_empty_generic_visitor(self, nodename, depth):
self.emit_generic_visitor_signature(nodename, depth)
self.emit("}", depth)
def simple_sum(self, sum, name, depth):
self.emit_visitor(name, depth)
self.emit_empty_generic_visitor(name, depth)
def visit_match_for_type(self, nodename, rust_name, type_, depth):
self.emit(f"{rust_name}::{type_.name}", depth)
self.emit("(data)", depth)
self.emit(
f"=> self.visit_{nodename}_{rust_field_name(type_.name)}(data),", depth
)
def visit_sum_type(self, name, type_, depth):
self.emit_visitor(type_.name, depth, has_node=type_.fields)
if not type_.fields:
return
self.emit_generic_visitor_signature(type_.name, depth, has_node=True)
for field in type_.fields:
if field.type in CUSTOM_REPLACEMENTS:
type_name = CUSTOM_REPLACEMENTS[field.type].name
else:
type_name = field.type
field_name = rust_field(field.name)
field_type = self.type_info.get(type_name)
if not (field_type and field_type.has_user_data):
continue
if field.opt:
self.emit(f"if let Some(value) = node.{field_name} {{", depth + 1)
elif field.seq:
iterable = f"node.{field_name}"
if type_.name == "Dict" and field.name == "keys":
iterable = f"{iterable}.into_iter().flatten()"
self.emit(f"for value in {iterable} {{", depth + 1)
else:
self.emit("{", depth + 1)
self.emit(f"let value = node.{field_name};", depth + 2)
variable = "value"
if field_type.boxed and (not field.seq or field.opt):