summaryrefslogtreecommitdiff
path: root/lib/spack/spack/util/unparse/unparser.py
blob: c2e6376e509537cb538b7d4011d3768161ace181 (plain) (blame)
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
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
# Copyright (c) 2014-2021, Simon Percivall and Spack Project Developers.
#
# SPDX-License-Identifier: Python-2.0
"Usage: unparse.py <path to source file>"
import ast
import sys
from contextlib import contextmanager
from io import StringIO


# TODO: if we require Python 3.7, use its `nullcontext()`
@contextmanager
def nullcontext():
    yield


# Large float and imaginary literals get turned into infinities in the AST.
# We unparse those infinities to INFSTR.
INFSTR = "1e" + repr(sys.float_info.max_10_exp + 1)


class _Precedence:
    """Precedence table that originated from python grammar."""

    TUPLE = 0
    YIELD = 1  # 'yield', 'yield from'
    TEST = 2  # 'if'-'else', 'lambda'
    OR = 3  # 'or'
    AND = 4  # 'and'
    NOT = 5  # 'not'
    CMP = 6  # '<', '>', '==', '>=', '<=', '!=', 'in', 'not in', 'is', 'is not'
    EXPR = 7
    BOR = EXPR  # '|'
    BXOR = 8  # '^'
    BAND = 9  # '&'
    SHIFT = 10  # '<<', '>>'
    ARITH = 11  # '+', '-'
    TERM = 12  # '*', '@', '/', '%', '//'
    FACTOR = 13  # unary '+', '-', '~'
    POWER = 14  # '**'
    AWAIT = 15  # 'await'
    ATOM = 16


def pnext(precedence):
    return min(precedence + 1, _Precedence.ATOM)


def interleave(inter, f, seq):
    """Call f on each item in seq, calling inter() in between."""
    seq = iter(seq)
    try:
        f(next(seq))
    except StopIteration:
        pass
    else:
        for x in seq:
            inter()
            f(x)


_SINGLE_QUOTES = ("'", '"')
_MULTI_QUOTES = ('"""', "'''")
_ALL_QUOTES = _SINGLE_QUOTES + _MULTI_QUOTES


def is_simple_tuple(slice_value):
    # when unparsing a non-empty tuple, the parantheses can be safely
    # omitted if there aren't any elements that explicitly requires
    # parantheses (such as starred expressions).
    return (
        isinstance(slice_value, ast.Tuple)
        and slice_value.elts
        and not any(isinstance(elt, ast.Starred) for elt in slice_value.elts)
    )


class Unparser:
    """Methods in this class recursively traverse an AST and
    output source code for the abstract syntax; original formatting
    is disregarded."""

    def __init__(self, py_ver_consistent=False, _avoid_backslashes=False):
        """Traverse an AST and generate its source.

        Arguments:
            py_ver_consistent (bool): if True, generate unparsed code that is
                consistent between Python versions 3.5-3.11.

        For legacy reasons, consistency is achieved by unparsing Python3 unicode literals
        the way Python 2 would. This preserved Spack package hash consistency during the
        python2/3 transition
        """
        self.future_imports = []
        self._indent = 0
        self._py_ver_consistent = py_ver_consistent
        self._precedences = {}
        self._avoid_backslashes = _avoid_backslashes

    def items_view(self, traverser, items):
        """Traverse and separate the given *items* with a comma and append it to
        the buffer. If *items* is a single item sequence, a trailing comma
        will be added."""
        if len(items) == 1:
            traverser(items[0])
            self.write(",")
        else:
            interleave(lambda: self.write(", "), traverser, items)

    def visit(self, tree, output_file):
        """Traverse tree and write source code to output_file."""
        self.f = output_file
        self.dispatch(tree)
        self.f.flush()

    def fill(self, text=""):
        "Indent a piece of text, according to the current indentation level"
        self.f.write("\n" + "    " * self._indent + text)

    def write(self, text):
        "Append a piece of text to the current line."
        self.f.write(str(text))

    class _Block:
        """A context manager for preparing the source for blocks. It adds
        the character ':', increases the indentation on enter and decreases
        the indentation on exit."""

        def __init__(self, unparser):
            self.unparser = unparser

        def __enter__(self):
            self.unparser.write(":")
            self.unparser._indent += 1

        def __exit__(self, exc_type, exc_value, traceback):
            self.unparser._indent -= 1

    def block(self):
        return self._Block(self)

    @contextmanager
    def delimit(self, start, end):
        """A context manager for preparing the source for expressions. It adds
        *start* to the buffer and enters, after exit it adds *end*."""

        self.write(start)
        yield
        self.write(end)

    def delimit_if(self, start, end, condition):
        if condition:
            return self.delimit(start, end)
        else:
            return nullcontext()

    def require_parens(self, precedence, node):
        """Shortcut to adding precedence related parens"""
        return self.delimit_if("(", ")", self.get_precedence(node) > precedence)

    def get_precedence(self, node):
        return self._precedences.get(node, _Precedence.TEST)

    def set_precedence(self, precedence, *nodes):
        for node in nodes:
            self._precedences[node] = precedence

    def dispatch(self, tree):
        "Dispatcher function, dispatching tree type T to method _T."
        if isinstance(tree, list):
            for node in tree:
                self.dispatch(node)
            return
        meth = getattr(self, "visit_" + tree.__class__.__name__)
        meth(tree)

    #
    # Unparsing methods
    #
    # There should be one method per concrete grammar type Constructors
    # should be # grouped by sum type. Ideally, this would follow the order
    # in the grammar, but currently doesn't.

    def visit_Module(self, tree):
        for stmt in tree.body:
            self.dispatch(stmt)

    def visit_Interactive(self, tree):
        for stmt in tree.body:
            self.dispatch(stmt)

    def visit_Expression(self, tree):
        self.dispatch(tree.body)

    # stmt
    def visit_Expr(self, tree):
        self.fill()
        self.set_precedence(_Precedence.YIELD, tree.value)
        self.dispatch(tree.value)

    def visit_NamedExpr(self, tree):
        with self.require_parens(_Precedence.TUPLE, tree):
            self.set_precedence(_Precedence.ATOM, tree.target, tree.value)
            self.dispatch(tree.target)
            self.write(" := ")
            self.dispatch(tree.value)

    def visit_Import(self, node):
        self.fill("import ")
        interleave(lambda: self.write(", "), self.dispatch, node.names)

    def visit_ImportFrom(self, node):
        # A from __future__ import may affect unparsing, so record it.
        if node.module and node.module == "__future__":
            self.future_imports.extend(n.name for n in node.names)

        self.fill("from ")
        self.write("." * node.level)
        if node.module:
            self.write(node.module)
        self.write(" import ")
        interleave(lambda: self.write(", "), self.dispatch, node.names)

    def visit_Assign(self, node):
        self.fill()
        for target in node.targets:
            self.dispatch(target)
            self.write(" = ")
        self.dispatch(node.value)

    def visit_AugAssign(self, node):
        self.fill()
        self.dispatch(node.target)
        self.write(" " + self.binop[node.op.__class__.__name__] + "= ")
        self.dispatch(node.value)

    def visit_AnnAssign(self, node):
        self.fill()
        with self.delimit_if("(", ")", not node.simple and isinstance(node.target, ast.Name)):
            self.dispatch(node.target)
        self.write(": ")
        self.dispatch(node.annotation)
        if node.value:
            self.write(" = ")
            self.dispatch(node.value)

    def visit_Return(self, node):
        self.fill("return")
        if node.value:
            self.write(" ")
            self.dispatch(node.value)

    def visit_Pass(self, node):
        self.fill("pass")

    def visit_Break(self, node):
        self.fill("break")

    def visit_Continue(self, node):
        self.fill("continue")

    def visit_Delete(self, node):
        self.fill("del ")
        interleave(lambda: self.write(", "), self.dispatch, node.targets)

    def visit_Assert(self, node):
        self.fill("assert ")
        self.dispatch(node.test)
        if node.msg:
            self.write(", ")
            self.dispatch(node.msg)

    def visit_Exec(self, node):
        self.fill("exec ")
        self.dispatch(node.body)
        if node.globals:
            self.write(" in ")
            self.dispatch(node.globals)
        if node.locals:
            self.write(", ")
            self.dispatch(node.locals)

    def visit_Global(self, node):
        self.fill("global ")
        interleave(lambda: self.write(", "), self.write, node.names)

    def visit_Nonlocal(self, node):
        self.fill("nonlocal ")
        interleave(lambda: self.write(", "), self.write, node.names)

    def visit_Await(self, node):
        with self.require_parens(_Precedence.AWAIT, node):
            self.write("await")
            if node.value:
                self.write(" ")
                self.set_precedence(_Precedence.ATOM, node.value)
                self.dispatch(node.value)

    def visit_Yield(self, node):
        with self.require_parens(_Precedence.YIELD, node):
            self.write("yield")
            if node.value:
                self.write(" ")
                self.set_precedence(_Precedence.ATOM, node.value)
                self.dispatch(node.value)

    def visit_YieldFrom(self, node):
        with self.require_parens(_Precedence.YIELD, node):
            self.write("yield from")
            if node.value:
                self.write(" ")
                self.set_precedence(_Precedence.ATOM, node.value)
                self.dispatch(node.value)

    def visit_Raise(self, node):
        self.fill("raise")
        if not node.exc:
            assert not node.cause
            return
        self.write(" ")
        self.dispatch(node.exc)
        if node.cause:
            self.write(" from ")
            self.dispatch(node.cause)

    def visit_Try(self, node):
        self.fill("try")
        with self.block():
            self.dispatch(node.body)
        for ex in node.handlers:
            self.dispatch(ex)
        if node.orelse:
            self.fill("else")
            with self.block():
                self.dispatch(node.orelse)
        if node.finalbody:
            self.fill("finally")
            with self.block():
                self.dispatch(node.finalbody)

    def visit_TryExcept(self, node):
        self.fill("try")
        with self.block():
            self.dispatch(node.body)

        for ex in node.handlers:
            self.dispatch(ex)
        if node.orelse:
            self.fill("else")
            with self.block():
                self.dispatch(node.orelse)

    def visit_TryFinally(self, node):
        if len(node.body) == 1 and isinstance(node.body[0], ast.TryExcept):
            # try-except-finally
            self.dispatch(node.body)
        else:
            self.fill("try")
            with self.block():
                self.dispatch(node.body)

        self.fill("finally")
        with self.block():
            self.dispatch(node.finalbody)

    def visit_ExceptHandler(self, node):
        self.fill("except")
        if node.type:
            self.write(" ")
            self.dispatch(node.type)
        if node.name:
            self.write(" as ")
            self.write(node.name)
        with self.block():
            self.dispatch(node.body)

    def visit_ClassDef(self, node):
        self.write("\n")
        for deco in node.decorator_list:
            self.fill("@")
            self.dispatch(deco)
        self.fill("class " + node.name)
        if getattr(node, "type_params", False):
            self.write("[")
            interleave(lambda: self.write(", "), self.dispatch, node.type_params)
            self.write("]")
        with self.delimit_if("(", ")", condition=node.bases or node.keywords):
            comma = False
            for e in node.bases:
                if comma:
                    self.write(", ")
                else:
                    comma = True
                self.dispatch(e)
            for e in node.keywords:
                if comma:
                    self.write(", ")
                else:
                    comma = True
                self.dispatch(e)
        with self.block():
            self.dispatch(node.body)

    def visit_FunctionDef(self, node):
        self.__FunctionDef_helper(node, "def")

    def visit_AsyncFunctionDef(self, node):
        self.__FunctionDef_helper(node, "async def")

    def __FunctionDef_helper(self, node, fill_suffix):
        self.write("\n")
        for deco in node.decorator_list:
            self.fill("@")
            self.dispatch(deco)
        def_str = fill_suffix + " " + node.name
        self.fill(def_str)
        if getattr(node, "type_params", False):
            self.write("[")
            interleave(lambda: self.write(", "), self.dispatch, node.type_params)
            self.write("]")
        with self.delimit("(", ")"):
            self.dispatch(node.args)
        if getattr(node, "returns", False):
            self.write(" -> ")
            self.dispatch(node.returns)
        with self.block():
            self.dispatch(node.body)

    def visit_For(self, node):
        self.__For_helper("for ", node)

    def visit_AsyncFor(self, node):
        self.__For_helper("async for ", node)

    def __For_helper(self, fill, node):
        self.fill(fill)
        self.dispatch(node.target)
        self.write(" in ")
        self.dispatch(node.iter)
        with self.block():
            self.dispatch(node.body)
        if node.orelse:
            self.fill("else")
            with self.block():
                self.dispatch(node.orelse)

    def visit_If(self, node):
        self.fill("if ")
        self.dispatch(node.test)
        with self.block():
            self.dispatch(node.body)
        # collapse nested ifs into equivalent elifs.
        while node.orelse and len(node.orelse) == 1 and isinstance(node.orelse[0], ast.If):
            node = node.orelse[0]
            self.fill("elif ")
            self.dispatch(node.test)
            with self.block():
                self.dispatch(node.body)
        # final else
        if node.orelse:
            self.fill("else")
            with self.block():
                self.dispatch(node.orelse)

    def visit_While(self, node):
        self.fill("while ")
        self.dispatch(node.test)
        with self.block():
            self.dispatch(node.body)
        if node.orelse:
            self.fill("else")
            with self.block():
                self.dispatch(node.orelse)

    def _generic_With(self, node, async_=False):
        self.fill("async with " if async_ else "with ")
        if hasattr(node, "items"):
            interleave(lambda: self.write(", "), self.dispatch, node.items)
        else:
            self.dispatch(node.context_expr)
            if node.optional_vars:
                self.write(" as ")
                self.dispatch(node.optional_vars)
        with self.block():
            self.dispatch(node.body)

    def visit_With(self, node):
        self._generic_With(node)

    def visit_AsyncWith(self, node):
        self._generic_With(node, async_=True)

    def _str_literal_helper(
        self, string, quote_types=_ALL_QUOTES, escape_special_whitespace=False
    ):
        """Helper for writing string literals, minimizing escapes.
        Returns the tuple (string literal to write, possible quote types).
        """

        def escape_char(c):
            # \n and \t are non-printable, but we only escape them if
            # escape_special_whitespace is True
            if not escape_special_whitespace and c in "\n\t":
                return c
            # Always escape backslashes and other non-printable characters
            if c == "\\" or not c.isprintable():
                return c.encode("unicode_escape").decode("ascii")
            return c

        escaped_string = "".join(map(escape_char, string))
        possible_quotes = quote_types
        if "\n" in escaped_string:
            possible_quotes = [q for q in possible_quotes if q in _MULTI_QUOTES]
        possible_quotes = [q for q in possible_quotes if q not in escaped_string]
        if not possible_quotes:
            # If there aren't any possible_quotes, fallback to using repr
            # on the original string. Try to use a quote from quote_types,
            # e.g., so that we use triple quotes for docstrings.
            string = repr(string)
            quote = next((q for q in quote_types if string[0] in q), string[0])
            return string[1:-1], [quote]
        if escaped_string:
            # Sort so that we prefer '''"''' over """\""""
            possible_quotes.sort(key=lambda q: q[0] == escaped_string[-1])
            # If we're using triple quotes and we'd need to escape a final
            # quote, escape it
            if possible_quotes[0][0] == escaped_string[-1]:
                assert len(possible_quotes[0]) == 3
                escaped_string = escaped_string[:-1] + "\\" + escaped_string[-1]
        return escaped_string, possible_quotes

    def _write_str_avoiding_backslashes(self, string, quote_types=_ALL_QUOTES):
        """Write string literal value w/a best effort attempt to avoid backslashes."""
        string, quote_types = self._str_literal_helper(string, quote_types=quote_types)
        quote_type = quote_types[0]
        self.write("{quote_type}{string}{quote_type}".format(quote_type=quote_type, string=string))

    # expr
    def visit_Bytes(self, node):
        self.write(repr(node.s))

    def visit_Str(self, tree):
        # Python 3.5, 3.6, and 3.7 can't tell if something was written as a
        # unicode constant. Try to make that consistent with 'u' for '\u- literals
        if self._py_ver_consistent and repr(tree.s).startswith("'\\u"):
            self.write("u")
        self._write_constant(tree.s)

    def visit_JoinedStr(self, node):
        # JoinedStr(expr* values)
        self.write("f")

        if self._avoid_backslashes:
            string = StringIO()
            self._fstring_JoinedStr(node, string.write)
            self._write_str_avoiding_backslashes(string.getvalue())
            return

        # If we don't need to avoid backslashes globally (i.e., we only need
        # to avoid them inside FormattedValues), it's cosmetically preferred
        # to use escaped whitespace. That is, it's preferred to use backslashes
        # for cases like: f"{x}\n". To accomplish this, we keep track of what
        # in our buffer corresponds to FormattedValues and what corresponds to
        # Constant parts of the f-string, and allow escapes accordingly.
        buffer = []
        for value in node.values:
            meth = getattr(self, "_fstring_" + type(value).__name__)
            string = StringIO()
            meth(value, string.write)
            buffer.append((string.getvalue(), isinstance(value, ast.Constant)))
        new_buffer = []
        quote_types = _ALL_QUOTES
        for value, is_constant in buffer:
            # Repeatedly narrow down the list of possible quote_types
            value, quote_types = self._str_literal_helper(
                value, quote_types=quote_types, escape_special_whitespace=is_constant
            )
            new_buffer.append(value)
        value = "".join(new_buffer)
        quote_type = quote_types[0]
        self.write("{quote_type}{value}{quote_type}".format(quote_type=quote_type, value=value))

    def visit_FormattedValue(self, node):
        # FormattedValue(expr value, int? conversion, expr? format_spec)
        self.write("f")
        string = StringIO()
        self._fstring_JoinedStr(node, string.write)
        self._write_str_avoiding_backslashes(string.getvalue())

    def _fstring_JoinedStr(self, node, write):
        for value in node.values:
            print("   ", value)
            meth = getattr(self, "_fstring_" + type(value).__name__)
            print(meth)
            meth(value, write)

    def _fstring_Str(self, node, write):
        value = node.s.replace("{", "{{").replace("}", "}}")
        write(value)

    def _fstring_Constant(self, node, write):
        assert isinstance(node.value, str)
        value = node.value.replace("{", "{{").replace("}", "}}")
        write(value)

    def _fstring_FormattedValue(self, node, write):
        write("{")

        expr = StringIO()
        unparser = type(self)(py_ver_consistent=self._py_ver_consistent, _avoid_backslashes=True)
        unparser.set_precedence(pnext(_Precedence.TEST), node.value)
        unparser.visit(node.value, expr)
        expr = expr.getvalue().rstrip("\n")

        if expr.startswith("{"):
            write(" ")  # Separate pair of opening brackets as "{ {"
        if "\\" in expr:
            raise ValueError("Unable to avoid backslash in f-string expression part")
        write(expr)
        if node.conversion != -1:
            conversion = chr(node.conversion)
            assert conversion in "sra"
            write("!{conversion}".format(conversion=conversion))
        if node.format_spec:
            write(":")
            meth = getattr(self, "_fstring_" + type(node.format_spec).__name__)
            meth(node.format_spec, write)
        write("}")

    def visit_Name(self, node):
        self.write(node.id)

    def visit_NameConstant(self, node):
        self.write(repr(node.value))

    def visit_Repr(self, node):
        self.write("`")
        self.dispatch(node.value)
        self.write("`")

    def _write_constant(self, value):
        if isinstance(value, (float, complex)):
            # Substitute overflowing decimal literal for AST infinities.
            self.write(repr(value).replace("inf", INFSTR))
        elif isinstance(value, str) and self._py_ver_consistent:
            # emulate a python 2 repr with raw unicode escapes
            # see _Str for python 2 counterpart
            raw = repr(value.encode("raw_unicode_escape")).lstrip("b")
            if raw.startswith(r"'\\u"):
                raw = "'\\" + raw[3:]
            self.write(raw)
        elif self._avoid_backslashes and isinstance(value, str):
            self._write_str_avoiding_backslashes(value)
        else:
            self.write(repr(value))

    def visit_Constant(self, node):
        value = node.value
        if isinstance(value, tuple):
            with self.delimit("(", ")"):
                self.items_view(self._write_constant, value)
        elif value is Ellipsis:  # instead of `...` for Py2 compatibility
            self.write("...")
        else:
            if node.kind == "u":
                self.write("u")
            self._write_constant(node.value)

    def visit_Num(self, node):
        repr_n = repr(node.n)
        self.write(repr_n.replace("inf", INFSTR))

    def visit_List(self, node):
        with self.delimit("[", "]"):
            interleave(lambda: self.write(", "), self.dispatch, node.elts)

    def visit_ListComp(self, node):
        with self.delimit("[", "]"):
            self.dispatch(node.elt)
            for gen in node.generators:
                self.dispatch(gen)

    def visit_GeneratorExp(self, node):
        with self.delimit("(", ")"):
            self.dispatch(node.elt)
            for gen in node.generators:
                self.dispatch(gen)

    def visit_SetComp(self, node):
        with self.delimit("{", "}"):
            self.dispatch(node.elt)
            for gen in node.generators:
                self.dispatch(gen)

    def visit_DictComp(self, node):
        with self.delimit("{", "}"):
            self.dispatch(node.key)
            self.write(": ")
            self.dispatch(node.value)
            for gen in node.generators:
                self.dispatch(gen)

    def visit_comprehension(self, node):
        if getattr(node, "is_async", False):
            self.write(" async for ")
        else:
            self.write(" for ")
        self.set_precedence(_Precedence.TUPLE, node.target)
        self.dispatch(node.target)
        self.write(" in ")
        self.set_precedence(pnext(_Precedence.TEST), node.iter, *node.ifs)
        self.dispatch(node.iter)
        for if_clause in node.ifs:
            self.write(" if ")
            self.dispatch(if_clause)

    def visit_IfExp(self, node):
        with self.require_parens(_Precedence.TEST, node):
            self.set_precedence(pnext(_Precedence.TEST), node.body, node.test)
            self.dispatch(node.body)
            self.write(" if ")
            self.dispatch(node.test)
            self.write(" else ")
            self.set_precedence(_Precedence.TEST, node.orelse)
            self.dispatch(node.orelse)

    def visit_Set(self, node):
        assert node.elts  # should be at least one element
        with self.delimit("{", "}"):
            interleave(lambda: self.write(", "), self.dispatch, node.elts)

    def visit_Dict(self, node):
        def write_key_value_pair(k, v):
            self.dispatch(k)
            self.write(": ")
            self.dispatch(v)

        def write_item(item):
            k, v = item
            if k is None:
                # for dictionary unpacking operator in dicts {**{'y': 2}}
                # see PEP 448 for details
                self.write("**")
                self.set_precedence(_Precedence.EXPR, v)
                self.dispatch(v)
            else:
                write_key_value_pair(k, v)

        with self.delimit("{", "}"):
            interleave(lambda: self.write(", "), write_item, zip(node.keys, node.values))

    def visit_Tuple(self, node):
        with self.delimit("(", ")"):
            self.items_view(self.dispatch, node.elts)

    unop = {"Invert": "~", "Not": "not", "UAdd": "+", "USub": "-"}

    unop_precedence = {
        "~": _Precedence.FACTOR,
        "not": _Precedence.NOT,
        "+": _Precedence.FACTOR,
        "-": _Precedence.FACTOR,
    }

    def visit_UnaryOp(self, node):
        operator = self.unop[node.op.__class__.__name__]
        operator_precedence = self.unop_precedence[operator]
        with self.require_parens(operator_precedence, node):
            self.write(operator)
            # factor prefixes (+, -, ~) shouldn't be separated
            # from the value they belong, (e.g: +1 instead of + 1)
            if operator_precedence != _Precedence.FACTOR:
                self.write(" ")
            self.set_precedence(operator_precedence, node.operand)
            self.dispatch(node.operand)

    binop = {
        "Add": "+",
        "Sub": "-",
        "Mult": "*",
        "MatMult": "@",
        "Div": "/",
        "Mod": "%",
        "LShift": "<<",
        "RShift": ">>",
        "BitOr": "|",
        "BitXor": "^",
        "BitAnd": "&",
        "FloorDiv": "//",
        "Pow": "**",
    }

    binop_precedence = {
        "+": _Precedence.ARITH,
        "-": _Precedence.ARITH,
        "*": _Precedence.TERM,
        "@": _Precedence.TERM,
        "/": _Precedence.TERM,
        "%": _Precedence.TERM,
        "<<": _Precedence.SHIFT,
        ">>": _Precedence.SHIFT,
        "|": _Precedence.BOR,
        "^": _Precedence.BXOR,
        "&": _Precedence.BAND,
        "//": _Precedence.TERM,
        "**": _Precedence.POWER,
    }

    binop_rassoc = frozenset(("**",))

    def visit_BinOp(self, node):
        operator = self.binop[node.op.__class__.__name__]
        operator_precedence = self.binop_precedence[operator]
        with self.require_parens(operator_precedence, node):
            if operator in self.binop_rassoc:
                left_precedence = pnext(operator_precedence)
                right_precedence = operator_precedence
            else:
                left_precedence = operator_precedence
                right_precedence = pnext(operator_precedence)

            self.set_precedence(left_precedence, node.left)
            self.dispatch(node.left)
            self.write(" %s " % operator)
            self.set_precedence(right_precedence, node.right)
            self.dispatch(node.right)

    cmpops = {
        "Eq": "==",
        "NotEq": "!=",
        "Lt": "<",
        "LtE": "<=",
        "Gt": ">",
        "GtE": ">=",
        "Is": "is",
        "IsNot": "is not",
        "In": "in",
        "NotIn": "not in",
    }

    def visit_Compare(self, node):
        with self.require_parens(_Precedence.CMP, node):
            self.set_precedence(pnext(_Precedence.CMP), node.left, *node.comparators)
            self.dispatch(node.left)
            for o, e in zip(node.ops, node.comparators):
                self.write(" " + self.cmpops[o.__class__.__name__] + " ")
                self.dispatch(e)

    boolops = {"And": "and", "Or": "or"}

    boolop_precedence = {"and": _Precedence.AND, "or": _Precedence.OR}

    def visit_BoolOp(self, node):
        operator = self.boolops[node.op.__class__.__name__]

        # use a dict instead of nonlocal for Python 2 compatibility
        op = {"precedence": self.boolop_precedence[operator]}

        def increasing_level_dispatch(node):
            op["precedence"] = pnext(op["precedence"])
            self.set_precedence(op["precedence"], node)
            self.dispatch(node)

        with self.require_parens(op["precedence"], node):
            s = " %s " % operator
            interleave(lambda: self.write(s), increasing_level_dispatch, node.values)

    def visit_Attribute(self, node):
        self.set_precedence(_Precedence.ATOM, node.value)
        self.dispatch(node.value)
        # Special case: 3.__abs__() is a syntax error, so if node.value
        # is an integer literal then we need to either parenthesize
        # it or add an extra space to get 3 .__abs__().
        num_type = getattr(ast, "Constant", getattr(ast, "Num", None))
        if isinstance(node.value, num_type) and isinstance(node.value.n, int):
            self.write(" ")
        self.write(".")
        self.write(node.attr)

    def visit_Call(self, node):
        self.set_precedence(_Precedence.ATOM, node.func)

        args = node.args
        self.dispatch(node.func)

        with self.delimit("(", ")"):
            comma = False

            # NOTE: this code is no longer compatible with python versions 2.7:3.4
            # If you run on python@:3.4, you will see instability in package hashes
            # across python versions

            for e in args:
                if comma:
                    self.write(", ")
                else:
                    comma = True
                self.dispatch(e)

            for e in node.keywords:
                if comma:
                    self.write(", ")
                else:
                    comma = True
                self.dispatch(e)

    def visit_Subscript(self, node):
        self.set_precedence(_Precedence.ATOM, node.value)
        self.dispatch(node.value)
        with self.delimit("[", "]"):
            if is_simple_tuple(node.slice):
                self.items_view(self.dispatch, node.slice.elts)
            else:
                self.dispatch(node.slice)

    def visit_Starred(self, node):
        self.write("*")
        self.set_precedence(_Precedence.EXPR, node.value)
        self.dispatch(node.value)

    # slice
    def visit_Ellipsis(self, node):
        self.write("...")

    # used in Python <= 3.8 -- see _Subscript for 3.9+
    def visit_Index(self, node):
        if is_simple_tuple(node.value):
            self.set_precedence(_Precedence.ATOM, node.value)
            self.items_view(self.dispatch, node.value.elts)
        else:
            self.set_precedence(_Precedence.TUPLE, node.value)
            self.dispatch(node.value)

    def visit_Slice(self, node):
        if node.lower:
            self.dispatch(node.lower)
        self.write(":")
        if node.upper:
            self.dispatch(node.upper)
        if node.step:
            self.write(":")
            self.dispatch(node.step)

    def visit_ExtSlice(self, node):
        interleave(lambda: self.write(", "), self.dispatch, node.dims)

    # argument
    def visit_arg(self, node):
        self.write(node.arg)
        if node.annotation:
            self.write(": ")
            self.dispatch(node.annotation)

    # others
    def visit_arguments(self, node):
        first = True
        # normal arguments
        all_args = getattr(node, "posonlyargs", []) + node.args
        defaults = [None] * (len(all_args) - len(node.defaults)) + node.defaults
        for index, elements in enumerate(zip(all_args, defaults), 1):
            a, d = elements
            if first:
                first = False
            else:
                self.write(", ")
            self.dispatch(a)
            if d:
                self.write("=")
                self.dispatch(d)
            if index == len(getattr(node, "posonlyargs", ())):
                self.write(", /")

        # varargs, or bare '*' if no varargs but keyword-only arguments present
        if node.vararg or getattr(node, "kwonlyargs", False):
            if first:
                first = False
            else:
                self.write(", ")
            self.write("*")
            if node.vararg:
                if hasattr(node.vararg, "arg"):
                    self.write(node.vararg.arg)
                    if node.vararg.annotation:
                        self.write(": ")
                        self.dispatch(node.vararg.annotation)
                else:
                    self.write(node.vararg)
                    if getattr(node, "varargannotation", None):
                        self.write(": ")
                        self.dispatch(node.varargannotation)

        # keyword-only arguments
        if getattr(node, "kwonlyargs", False):
            for a, d in zip(node.kwonlyargs, node.kw_defaults):
                if first:
                    first = False
                else:
                    self.write(", ")
                self.dispatch(a),
                if d:
                    self.write("=")
                    self.dispatch(d)

        # kwargs
        if node.kwarg:
            if first:
                first = False
            else:
                self.write(", ")
            if hasattr(node.kwarg, "arg"):
                self.write("**" + node.kwarg.arg)
                if node.kwarg.annotation:
                    self.write(": ")
                    self.dispatch(node.kwarg.annotation)
            else:
                self.write("**" + node.kwarg)
                if getattr(node, "kwargannotation", None):
                    self.write(": ")
                    self.dispatch(node.kwargannotation)

    def visit_keyword(self, node):
        if node.arg is None:
            # starting from Python 3.5 this denotes a kwargs part of the invocation
            self.write("**")
        else:
            self.write(node.arg)
            self.write("=")
        self.dispatch(node.value)

    def visit_Lambda(self, node):
        with self.require_parens(_Precedence.TEST, node):
            self.write("lambda ")
            self.dispatch(node.args)
            self.write(": ")
            self.set_precedence(_Precedence.TEST, node.body)
            self.dispatch(node.body)

    def visit_alias(self, node):
        self.write(node.name)
        if node.asname:
            self.write(" as " + node.asname)

    def visit_withitem(self, node):
        self.dispatch(node.context_expr)
        if node.optional_vars:
            self.write(" as ")
            self.dispatch(node.optional_vars)

    def visit_Match(self, node):
        self.fill("match ")
        self.dispatch(node.subject)
        with self.block():
            for case in node.cases:
                self.dispatch(case)

    def visit_match_case(self, node):
        self.fill("case ")
        self.dispatch(node.pattern)
        if node.guard:
            self.write(" if ")
            self.dispatch(node.guard)
        with self.block():
            self.dispatch(node.body)

    def visit_MatchValue(self, node):
        self.dispatch(node.value)

    def visit_MatchSingleton(self, node):
        self._write_constant(node.value)

    def visit_MatchSequence(self, node):
        with self.delimit("[", "]"):
            interleave(lambda: self.write(", "), self.dispatch, node.patterns)

    def visit_MatchStar(self, node):
        name = node.name
        if name is None:
            name = "_"
        self.write("*{}".format(name))

    def visit_MatchMapping(self, node):
        def write_key_pattern_pair(pair):
            k, p = pair
            self.dispatch(k)
            self.write(": ")
            self.dispatch(p)

        with self.delimit("{", "}"):
            keys = node.keys
            interleave(lambda: self.write(", "), write_key_pattern_pair, zip(keys, node.patterns))
            rest = node.rest
            if rest is not None:
                if keys:
                    self.write(", ")
                self.write("**{}".format(rest))

    def visit_MatchClass(self, node):
        self.set_precedence(_Precedence.ATOM, node.cls)
        self.dispatch(node.cls)
        with self.delimit("(", ")"):
            patterns = node.patterns
            interleave(lambda: self.write(", "), self.dispatch, patterns)
            attrs = node.kwd_attrs
            if attrs:

                def write_attr_pattern(pair):
                    attr, pattern = pair
                    self.write("{}=".format(attr))
                    self.dispatch(pattern)

                if patterns:
                    self.write(", ")
                interleave(
                    lambda: self.write(", "), write_attr_pattern, zip(attrs, node.kwd_patterns)
                )

    def visit_MatchAs(self, node):
        name = node.name
        pattern = node.pattern
        if name is None:
            self.write("_")
        elif pattern is None:
            self.write(node.name)
        else:
            with self.require_parens(_Precedence.TEST, node):
                self.set_precedence(_Precedence.BOR, node.pattern)
                self.dispatch(node.pattern)
                self.write(" as {}".format(node.name))

    def visit_MatchOr(self, node):
        with self.require_parens(_Precedence.BOR, node):
            self.set_precedence(pnext(_Precedence.BOR), *node.patterns)
            interleave(lambda: self.write(" | "), self.dispatch, node.patterns)

    def visit_TypeAlias(self, node):
        self.fill("type ")
        self.dispatch(node.name)
        self.write(" = ")
        self.dispatch(node.value)

    def visit_TypeVar(self, node):
        self.write(node.name)
        if node.bound:
            self.write(": ")
            self.dispatch(node.bound)

    def visit_TypeVarTuple(self, node):
        self.write("*")
        self.write(node.name)

    def visit_ParamSpec(self, node):
        self.write("**")
        self.write(node.name)