OILS / asdl / runtime.py View on Github | oils.pub

68 lines, 23 significant
1"""runtime.py.
2
3- Base classes for generated code
4- Nodes for pretty printing
5"""
6from __future__ import print_function
7
8from _devbuild.gen.hnode_asdl import hnode, color_t, color_e
9
10from typing import Optional, Dict
11
12# Used throughout the "LST" to indicate we don't have location info.
13NO_SPID = -1
14
15
16def NewRecord(node_type):
17 # type: (str) -> hnode.Record
18
19 # TODO: could CreateNull(alloc_lists=True) to optimize?
20 return hnode.Record(
21 node_type,
22 '(',
23 ')',
24 [], # fields
25 None, # unnamed fields
26 )
27
28
29def NewLeaf(s, e_color):
30 # type: (Optional[str], color_t) -> hnode.Leaf
31 """
32 TODO: _EmitCodeForField in asdl/gen_{cpp,python}.py does something like
33 this for non-string types. We should keep the style consistent.
34
35 It's related to the none_guard return value of _HNodeExpr().
36
37 The problem there is that we call i0->PrettyTree() or
38 i0->AbbreviatedTree(). Although it's not actually polymorphic in C++, only
39 Python, so we could handle the nullptr case.
40
41 i.e. PrettyTree() could be a free function using static dispatch, not a
42 member. And then it can handle the nullptr case.
43 """
44 # for repr of BashArray, which can have 'None'
45 if s is None:
46 return hnode.Leaf('_', color_e.OtherConst)
47 else:
48 return hnode.Leaf(s, e_color)
49
50
51class TraversalState:
52
53 def __init__(self):
54 # type: () -> None
55
56 # So PrettyTree() and AbbreviatedTree() don't go into infinite loops.
57
58 self.seen = {} # type: Dict[int, bool]
59
60 # If you have a ref count of 2 or more, you can print a stable ID for
61 # the record the FIRST time around. Then future records will refer to that ID.
62 # For a ref count of 1, don't bother printing it.
63 self.ref_count = {} # type: Dict[int, int]
64
65
66# Constants to avoid 'StrFromC("T")' in ASDL-generated code
67TRUE_STR = 'T'
68FALSE_STR = 'F'