def make_tree(terminal_rules, nonterminal_rules, str, table, s, i1, i2): if i1 < i2: for m in range(i1, i2): for (lhs, r1, r2) in nonterminal_rules: if lhs == s and table[r1][i1][m] and table[r2][m + 1][i2]: t1 = make_tree(terminal_rules, nonterminal_rules, str, table, r1, i1, m) t2 = make_tree(terminal_rules, nonterminal_rules, str, table, r2, m + 1, i2) tree = Tree(s) tree.children = [t1, t2] return tree else: tree = Tree(s) tree.children = [str[i1]] return tree
class ApiFs(LoggingMixIn, Operations): 'Api filesystem for http://korchasa.host' def __init__(self, loader): self.tree = Tree() self.loader = loader self.fd = 0 def create(self, path, mode=0o644): self.files[path] = self._file(mode) self.fd += 1 return self.fd getxattr = None def getattr(self, path, fh=None): if len(path) > 1 and path[1] == '.': raise FuseOSError(ENOENT) node = self.tree.load(path, self.loader) if node: return self._fs_node(node) else: raise FuseOSError(ENOENT) def open(self, path, flags): self.fd += 1 return self.fd def read(self, path, size, offset, fh): return self.tree.node(path)['data'][offset:offset + size] def readdir(self, path, fh): node = self.tree.nearest(path) if not node.get('loaded'): self.loader(path, self.tree) children = ['.', '..'] + [url.lstrip('/') for url in list(self.tree.children(path).keys()) if url != '/'] return children def statfs(self, path): return dict(f_bsize=512, f_blocks=4096, f_bavail=2048) def _fs_node(self, tree_node): if tree_node.get('dir'): return dict( st_mode=(S_IFDIR | 0o755), st_ctime=time(), st_mtime=time(), st_atime=time(), st_nlink=2 ) else: return dict( st_mode=(S_IFREG | 0o644), st_nlink=1, st_size=len(tree_node.get('data')), st_ctime=time(), st_mtime=time(), st_atime=time() )
def convert_json_tree(json): for key, val in json.items(): node = Tree(pos_tag=key) if(type(val) == type("")): node.value = val node.children = None elif(type(val) == type([])): for child in val: node.add_child(convert_json_tree(child)) else: continue return node
depth = 1 maximum_depth = depth for child in tree.children: child_max_depth = helper(child, depth + 1, tree.value) if child_max_depth > maximum_depth: maximum_depth = child_max_depth return maximum_depth def lcb(root): return helper(root, 0, None) root = Tree(0) t1 = Tree(1) t2 = Tree(2) t3 = Tree(1) t4 = Tree(2) t5 = Tree(1) t6 = Tree(3) t7 = Tree(4) t6.children = [t7] t8 = Tree(5) t7.children = [t8] root.children.extend([t1, t2]) t1.children.extend([t3, t4]) t2.children.extend([t5, t6]) print('longest consecutive branch is: ', lcb(root))
def parse2ast(parse_tree): """ Converts a parse tree into an AST. """ for node in list(parse_tree.postfix_iter()): if node.node_type == 'token': if node.token_type in ('SOF', 'EOF', 'punc'): # go ahead and filter unncessary punctuation tokens node.kill() elif node.token_type in ('str', 'int', 'bool'): # it's a literal node.node_type = 'literal' setattr(node, 'ice9_type', node.token_type) if node.ice9_type == 'str': node.value = node.value[1:-1] # remove the quotes elif node.ice9_type == 'int': node.value = int(node.value) elif node.ice9_type == 'bool': if node.value == 'true': node.value = True elif node.value == 'false': node.value = False elif node.token_type == 'ident': node.node_type = 'ident' elif node.value in ('write', 'writes', 'break', 'exit', 'return', 'read'): node.parent.node_type = 'operator' node.parent.value = node.value assert node.parent.children.pop(0) == node elif node.node_type == 'rule-expansion': if (len(node.children) == 0 and node.value != 'proc_call' and node.value != 'program' and node.value != 'stms'): # Empty node, let's just kill it and go onto the next node.kill() continue elif len(node.children) >= 2: if (node.children[0].node_type == 'token' and node.children[0].value in UNARY_OPS and node.value == 'high'): # node.parent node.parent # | | # node => op # / \ | # op right right p = node.parent op = node.children[0].value node.node_type = 'operator' node.value = op node.line = node.children[0].line node.children.pop(0) continue elif (node.children[0].node_type == 'token' and node.children[0].value in BINARY_OPS and node.parent.node_type == 'rule-expansion'): if (node.parent.value != node.value): # end of the chain # node.parent # / \ # a ( node ) # / / | \ \ # op1 b op2 c ... p = node.parent index = p.children.index(node) a = p.children.pop(index - 1) # node contains an expression a OP b OP c ... # where OP are all of the same precedence. We # need to turn it into a left oriented tree. leftnode = a children = node.children while len(children) > 0: op = children.pop(0) operand = children.pop(0) newleft = Tree(value=op.value, node_type='operator', line=op.line) newleft.children = [leftnode, operand] leftnode.parent = newleft operand.parent = leftnode leftnode = newleft leftnode.parent = node node.children = [leftnode] node.remove_and_promote() continue if node.value in transform_rules: transform_rules[node.value](node) return parse_tree
class openstackData(): def __init__(self): self.resources = Tree() self.resources.create_node('CMS', 'CMS') def insert_resource(self, tag, parent, os_data=None, vsd_data=None, vsc_data=None, vrs_data=None, user_data=None): self.resources.create_node(tag, tag, parent=parent, os_data=os_data, vrs_data=vrs_data, vsd_data=vsd_data, vsc_data=vsc_data, user_data=user_data) def print_openstackData(self): self.resources.show(line_type="ascii-em") def delete_resource(self, tag): resp = self.resources.remove_node(tag) if resp < 1: raise Exception("Resource removal failed.") def get_resource(self, tag): resp = self.resources.get_node(tag) if not isinstance(resp, Node): raise Exception("Returned node is not of type Node") return resp def get_children_resources(self, tag): resp = self.resources.children(tag) if not isinstance(resp, list): raise Exception("Did not get a list") return resp def is_resource_present(self, tag): resp = self.resources.contains(tag) return resp def move_resource(self, tag, new_parent): self.resources.move_node(tag, new_parent) def update_resource(self, tag, os_data=None, vsd_data=None, vsc_data=None, vrs_data=None, user_data=None): self.resources.update_node(tag, os_data=os_data, vsd_data=vsd_data, vsc_data=vsc_data, vrs_data=vrs_data, user_data=user_data)
def memlookup(varname, ast): """ Returns a tuple (code5, memloc, relreg) meaning after code5, varname will be in memory[memloc + reg[relreg]]. """ code5 = [] memloc, relreg = first_definition(variables, varname) if ast and len(ast.children) > 0: # array reference. We need to do all our index calculations and such p = ast.parent while True: if hasattr(p, 'vars') and any(x == varname for x, t in p.vars): break else: p = p.parent arrayindexes = [] vartype = dict(p.vars)[varname] while type(vartype) is list and vartype[0] == "array": arrayindexes.append(vartype[2]) vartype = vartype[1] code5 += comment('%s is an array of size %s' % (varname, arrayindexes)) from tree import Tree fakeast = Tree(node_type='operator', value='write') fakeast.children = [Tree(node_type='literal', value='Arrays bounds violation', ice9_type='str')] failcode = comment('Array out of bounds error code:') failcode += generate_code(fakeast) failcode += [('HALT', 0, 0, 0, 'Array out of bounds')] failcode += comment('End array out of bounds error code') indexcode = comment('Calculating memory location:') if relreg == FP: # we're in a proc, so what we have is a pointer that we'll # still need to dereference again indexcode += [('LD', AC4, memloc, relreg, 'Go ahead and dereference %s' % varname)] memloc, relreg = 0, AC4 else: # we're just in the main body, so we already know the # direct location of the array. indexcode += [('LDA', AC4, memloc, relreg, 'Start array indexing at 0')] memloc, relreg = 0, AC4 iteration = izip(ast.children, arrayindexes, arrayindexes[1:] + [1]) for indexast, dimension_size, mul_size in iteration: indexcode += push_register(AC4, "Pushing array address to stack") indexcode += generate_code(indexast) indexcode += pop_register(AC4, "Popping array address from stack") jumpsize = code_length(failcode + indexcode) indexcode += [('JLT', AC1, - jumpsize - 1, PC, 'Check index >= 0'), ('LDA', AC1, - dimension_size, AC1, 'Prepare for dimension check'), ('JGE', AC1, - jumpsize - 3, PC, 'Check index < size'), ('LDA', AC1, dimension_size, AC1, 'Undo dimension check'), ('LDC', AC2, mul_size, 0, 'Prepare for dimension multiply'), ('MUL', AC2, AC2, AC1, 'Multiply index * arraysize'), ('ADD', AC4, AC4, AC2, 'Add this increment to our offset.')] code5 += [('JEQ', ZERO, code_length(failcode), PC, 'Skip array out of bounds failure.')] code5 += failcode code5 += indexcode return code5, memloc, relreg