in utils/trees.py [0:0]
def _linearized_rep_to_tree_rep(self, flat_string):
'''
Get the tree representation for flat input string `flat_string`
Example input string:
"(ORDER can i have (PIZZAORDER (NUMBER a ) (SIZE large ) (TOPPING bbq pulled pork ) ) please )"
Invalid flat strings include those with misplaced brackets, mismatched brackets,
or semantic nodes with no children
:param flat_string: (str) input flat string to construct a tree, if possible.
:raises ValueError: when s is not a valid flat string
:raises IndexError: when s is not a valid flat string
:return: (AnyNode) returns a pointer to a tree node.
'''
# Keep track of all the semantics in the input string.
semantic_stack = [AnyNode(id=TopSemanticTree.ROOT_SYMBOL)]
for token in flat_string.split():
if '(' in token:
node = AnyNode(id=token.strip('('), parent=semantic_stack[-1])
semantic_stack.append(node)
elif token == ')':
# If the string is not valid an error will be thrown here.
# E.g. (PIZZAORDER (SIZE LARGE ) ) ) ) ) ) )
try:
# If there are no children within this semantic node, throw an error
# E.g. (PIZZAORDER (SIZE LARGE ) (NOT ) )
if not semantic_stack[-1].children:
raise Exception("Semantic node with no children")
semantic_stack.pop()
except Exception as e:
raise IndexError(e) from e
else:
AnyNode(id=token, parent=semantic_stack[-1])
# If there are more than one elements in semantic stack, that means
# the input string is malformed, i.e. it cant be used to construct a tree
if len(semantic_stack) > 1:
raise ValueError()
return semantic_stack[-1]