-
Notifications
You must be signed in to change notification settings - Fork 0
/
node.py
61 lines (55 loc) · 2.16 KB
/
node.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
# -----------------------------------------------------------------------------
# narrtr: node.py
# This file defines the Node class for the narratr AST.
#
# Copyright (C) 2015 Team narratr
# All Rights Reserved
# Team narratr: Yelin Hong, Shloka Kini, Nivvedan Senthamil Selvan, Jonah
# Smith, Cecilia Watt
#
# File Created: 31 March 2015
# Primary Author: Jonah Smith
#
# Any questions, bug reports and complaints are to be directed at the primary
# author.
#
# -----------------------------------------------------------------------------
# Class for nodes in the narratr AST.
class Node:
def __init__(self, v, t, c=[], v_type=None, lineno=0, key=None):
"""Create node for narratr AST.
Constructor takes:
v the value of the node
t the variable type, defined by Lexer/Parser
c a list of children nodes (Optional)
v_type the type of the value (int, float, string, boolean,
id). Technically optional, but include for all new
nodes.
lineno The line number at which the node appears. Technically
optional, but include for all new nodes.
"""
self.value = v
self.type = t
self.children = c
self.v_type = v_type
self.lineno = lineno
self.key = key
# This method is helpful for string representations
def __repr__(self):
return "Node(%r, %r, %r, %r, %r, %r)" % (self.value, self.type,
self.children, self.v_type,
self.lineno, self.key)
def is_leaf(self):
"""This method checks if a node is a leaf node."""
if len(self.children) > 0:
return False
else:
return True
# This method overloads the indexing [] operator to return the child
# corresponding to the index.
def __getitem__(self, index):
if self.is_leaf():
raise Exception("Node has no children.")
if index >= len(self.children) or index < 0:
raise Exception("Node index out of bounds.")
return self.children[index]