| 1 | """visitor.py."""
|
| 2 | from __future__ import print_function
|
| 3 |
|
| 4 | import sys
|
| 5 | from asdl import ast
|
| 6 | from asdl.ast import Module
|
| 7 | from typing import List, IO
|
| 8 |
|
| 9 |
|
| 10 | class AsdlVisitor:
|
| 11 | """Tree walker base class.
|
| 12 |
|
| 13 | This is NOT a visitor, since it doesn't have accept(self) and double
|
| 14 | dispatch.
|
| 15 |
|
| 16 | VisitModule uses the "template method pattern"
|
| 17 | https://en.wikipedia.org/wiki/Template_method_pattern
|
| 18 | """
|
| 19 |
|
| 20 | def __init__(self, f):
|
| 21 | # type: (IO) -> None
|
| 22 | self.f = f
|
| 23 | self.current_depth = 0 # the current number of indent levels
|
| 24 |
|
| 25 | def Indent(self):
|
| 26 | # type: () -> None
|
| 27 | self.current_depth += 1
|
| 28 |
|
| 29 | def Dedent(self):
|
| 30 | # type: () -> None
|
| 31 | self.current_depth -= 1
|
| 32 |
|
| 33 | def Emit(self, s, depth=-1, reflow=True):
|
| 34 | # type: (str, int, bool) -> None
|
| 35 | if depth == -1:
|
| 36 | depth = self.current_depth
|
| 37 | for line in FormatLines(s, depth, reflow=reflow):
|
| 38 | self.f.write(line)
|
| 39 |
|
| 40 | def VisitModule(self, mod, depth=0):
|
| 41 | # type: (Module, int) -> None
|
| 42 | """
|
| 43 | Template method
|
| 44 | """
|
| 45 | for dfn in mod.dfns:
|
| 46 | if isinstance(dfn, ast.SubTypeDecl):
|
| 47 | self.VisitSubType(dfn)
|
| 48 |
|
| 49 | elif isinstance(dfn, ast.TypeDecl):
|
| 50 | typ = dfn
|
| 51 | if isinstance(typ.value, ast.SimpleSum):
|
| 52 | self.VisitSimpleSum(typ.value, typ.name, depth)
|
| 53 |
|
| 54 | elif isinstance(typ.value, ast.Sum):
|
| 55 | self.VisitCompoundSum(typ.value, typ.name, depth)
|
| 56 |
|
| 57 | elif isinstance(typ.value, ast.Product):
|
| 58 | self.VisitProduct(typ.value, typ.name, depth)
|
| 59 |
|
| 60 | else:
|
| 61 | raise AssertionError(typ)
|
| 62 |
|
| 63 | else:
|
| 64 | raise AssertionError(dfn)
|
| 65 |
|
| 66 | self.EmitFooter()
|
| 67 |
|
| 68 | def VisitSubType(self, subtype):
|
| 69 | pass
|
| 70 |
|
| 71 | # Optionally overridden.
|
| 72 | def VisitSimpleSum(self, value, name, depth):
|
| 73 | pass
|
| 74 |
|
| 75 | def VisitCompoundSum(self, value, name, depth):
|
| 76 | pass
|
| 77 |
|
| 78 | def VisitProduct(self, value, name, depth):
|
| 79 | pass
|
| 80 |
|
| 81 | def EmitFooter(self):
|
| 82 | pass
|
| 83 |
|
| 84 |
|
| 85 | TABSIZE = 2
|
| 86 | MAX_COL = 80
|
| 87 |
|
| 88 | # Copied from asdl_c.py
|
| 89 |
|
| 90 |
|
| 91 | def _ReflowLines(s, depth):
|
| 92 | # type: (str, int) -> List[str]
|
| 93 | """Reflow the line s indented depth tabs.
|
| 94 |
|
| 95 | Return a sequence of lines where no line extends beyond MAX_COL when
|
| 96 | properly indented. The first line is properly indented based
|
| 97 | exclusively on depth * TABSIZE. All following lines -- these are
|
| 98 | the reflowed lines generated by this function -- start at the same
|
| 99 | column as the first character beyond the opening { in the first
|
| 100 | line.
|
| 101 | """
|
| 102 | size = MAX_COL - depth * TABSIZE
|
| 103 | if len(s) < size:
|
| 104 | return [s]
|
| 105 |
|
| 106 | lines = []
|
| 107 | cur = s
|
| 108 | padding = ""
|
| 109 | while len(cur) > size:
|
| 110 | i = cur.rfind(' ', 0, size)
|
| 111 | if i == -1:
|
| 112 | if 0:
|
| 113 | print(
|
| 114 | "Warning: No space to reflow line (size=%d, depth=%d, cur=%r): %r"
|
| 115 | % (size, depth, cur, s),
|
| 116 | file=sys.stderr)
|
| 117 | lines.append(padding + cur)
|
| 118 | break
|
| 119 |
|
| 120 | lines.append(padding + cur[:i])
|
| 121 | if len(lines) == 1:
|
| 122 | # find new size based on brace
|
| 123 | j = cur.find('{', 0, i)
|
| 124 | if j >= 0:
|
| 125 | j += 2 # account for the brace and the space after it
|
| 126 | size -= j
|
| 127 | padding = " " * j
|
| 128 | else:
|
| 129 | j = cur.find('(', 0, i)
|
| 130 | if j >= 0:
|
| 131 | j += 1 # account for the paren (no space after it)
|
| 132 | size -= j
|
| 133 | padding = " " * j
|
| 134 | cur = cur[i + 1:]
|
| 135 | else:
|
| 136 | lines.append(padding + cur)
|
| 137 | return lines
|
| 138 |
|
| 139 |
|
| 140 | def FormatLines(s, depth, reflow=True):
|
| 141 | # type: (str, int, bool) -> List[str]
|
| 142 | """Make the generated code readable.
|
| 143 |
|
| 144 | Args:
|
| 145 | depth: controls indentation
|
| 146 | reflow: line wrapping.
|
| 147 | """
|
| 148 | if reflow:
|
| 149 | lines = _ReflowLines(s, depth)
|
| 150 | else:
|
| 151 | lines = [s]
|
| 152 |
|
| 153 | result = []
|
| 154 | for line in lines:
|
| 155 | line = (" " * TABSIZE * depth) + line + "\n"
|
| 156 | result.append(line)
|
| 157 | return result
|
| 158 |
|
| 159 |
|
| 160 | """
|
| 161 | For */*_gen.py, and asdl/gen_*.py
|
| 162 |
|
| 163 | from asdl.util import Write
|
| 164 |
|
| 165 | def f():
|
| 166 | # constant string with leading stuff stripped off
|
| 167 | Write(f, '''
|
| 168 | hello
|
| 169 | there
|
| 170 | |''')
|
| 171 |
|
| 172 | # - option to reflow
|
| 173 | # - option to add MORE depth, in addition to stripping whitespace
|
| 174 | # - I wonder if YSH template strings could use something like that
|
| 175 | Write(f, '''
|
| 176 | a = {a}
|
| 177 | b = {b}
|
| 178 | |''', locals(), reflow=True, depth=2)
|
| 179 |
|
| 180 | with Printer(locals()) as p:
|
| 181 | p.Write('''
|
| 182 | a = {a}
|
| 183 | b = {b}
|
| 184 | |''')
|
| 185 | """
|