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