OILS / pgen2 / pnode.py View on Github | oilshell.org

67 lines, 30 significant
1#!/usr/bin/env python2
2"""
3pnode.py
4"""
5from __future__ import print_function
6
7from typing import TYPE_CHECKING, Optional, List
8
9if TYPE_CHECKING:
10 from _devbuild.gen.syntax_asdl import Token
11
12
13class PNode(object):
14 __slots__ = ('typ', 'tok', 'children')
15
16 def __init__(self, typ, tok, children):
17 # type: (int, Optional[Token], Optional[List[PNode]]) -> None
18 self.typ = typ # token or non-terminal
19 self.tok = tok # In Oil, this is syntax_asdl.Token. In OPy, it's a
20 # 3-tuple (val, prefix, loc)
21 # NOTE: This is None for the first entry in the stack?
22 self.children = children
23
24 def __repr__(self):
25 # type: () -> str
26 tok_str = str(self.tok) if self.tok else '-'
27 ch_str = 'with %d children' % len(self.children) \
28 if self.children is not None else ''
29 return '(PNode %s %s %s)' % (self.typ, tok_str, ch_str)
30
31 def AddChild(self, node):
32 # type: (PNode) -> None
33 """
34 Add `node` as a child.
35 """
36 self.children.append(node)
37
38 def GetChild(self, i):
39 # type: (int) -> PNode
40 """
41 Returns the `i`th uncomsumed child.
42 """
43 if i < 0:
44 return self.children[i]
45
46 return self.children[i]
47
48 def NumChildren(self):
49 # type: () -> int
50 """
51 Returns the number of unconsumed children.
52 """
53 return len(self.children)
54
55
56class PNodeAllocator(object):
57 def __init__(self):
58 # type: () -> None
59 return
60
61 def NewPNode(self, typ, tok):
62 # type: (int, Optional[Token]) -> PNode
63 return PNode(typ, tok, [])
64
65 def Clear(self):
66 # type: () -> None
67 return