예제 #1
0
 def p_body(self, p):
     """body : LBRACE CODE_BLOCK RBRACE
             | instruction"""
     if len(p) == 2:
         p[0] = ast.Instruction(p[1])
     else:
         p[0] = ast.Instruction(p[2])
예제 #2
0
 def p_range(self, p):
     """range : expression RANGE expression RANGE expression
              | expression RANGE expression"""
     if len(p) == 4:
         p[0] = ast.Range(p[1], p[3])
     else:
         p[0] = ast.Range(p[1], p[3], p[5])
예제 #3
0
	def create_arithmetric(self, op, left, right):
		operation = Ast.operation()
		operation.type = self.get_opertype(left, right)
		operation.op = self.get_op(op)
		operation.left = left.id
		operation.right = right.id
		return operation
예제 #4
0
def main():
    global path, goal_node

    # Obtain information from calling parameters
    method = input("Enter your search type :#ast bfs dfs# ")
    if method == "ast":
        heuristics = input("Enter heuristics fun :#hattan  Euclidean# ")
    lst1 = [
        int(item)
        for item in input("Enter initialBoard :#1,2,3,4,5,6,7,8,0 ").split(',')
    ]
    # Build initial board state
    InitialState = list(convert(lst1))

    for i in range(len(InitialState)):
        for j in range(len(InitialState[i])):
            if (InitialState[i][j] == 0):
                x = i
                y = j
                break

    # Start operation
    start = timeit.default_timer()

    if (method == "bfs"):
        print("BFS >>>>>")
        print(InitialState)
        goal_node = BFS(InitialState, x, y)
    if (method == "dfs"):
        print("DFS >>>>>")
        goal_node = DFS(InitialState, x, y)
    if (method == "ast"):
        print("AST >>>>>")
        goal_node = Ast.A_star(InitialState, heuristics)
        exit(0)
    stop = timeit.default_timer()
    time = stop - start

    # Print path
    print("Path :")
    path = find_path(goal_node, path, False)

    for node in path:
        printNode(node.array)
        print(node.direction)

    #print
    print()
    print("Path Cost :", len(path))
    print("Running time :", format(time, '.8f'))
    print("Search Depth ", goal_node.depth)
    print()
    print("## Expanded Nodes ## : ", expandned_nodes)
    for node in expanded:
        printNode(node)
        print(",")
예제 #5
0
 def p_code_block_braces(self, p):
     """
     CODE_BLOCK : CODE_BLOCK LBRACE CODE_BLOCK RBRACE
           | LBRACE CODE_BLOCK RBRACE
     """
     if len(p) == 5:
         p[1].instructions.append(p[3])
         p[0] = p[1]
     else:
         p[0] = ast.CodeBlock(p[2])
예제 #6
0
 def p_sequence(self, p):
     """
     sequence : sequence COMMA expression
              | expression
     """
     if len(p) == 4:
         p[1].expressions.append(p[3])
         p[0] = p[1]
     else:
         p[0] = ast.Sequence(p[1])
예제 #7
0
 def p_code_block(self, p):
     """
     CODE_BLOCK : CODE_BLOCK instruction
           | instruction
     """
     if len(p) == 3:
         p[1].instructions.append(p[2])
         p[0] = p[1]
     else:
         p[0] = ast.CodeBlock(p[1])
예제 #8
0
 def p_rows(self, p):
     """
     rows : rows SEMICOLON sequence
          | sequence
     """
     if len(p) == 2:
         p[0] = ast.Rows(p[1])
     else:
         p[1].row_list.append(p[3])
         p[0] = p[1]
예제 #9
0
    def p_value(self, p):
        """
        value : FLOAT
              | INT
              | STRING
              | matrix
              | variable_attribute
        """

        p[0] = ast.Value(p[1])
예제 #10
0
 def p_bin_expressions(self, p):
     """
     expression : expression PLUS expression
                | expression MINUS expression
                | expression TIMES expression
                | expression DIVIDE expression
                | expression MPLUS expression
                | expression MMINUS expression
                | expression MTIMES expression
                | expression MDIVIDE expression
     """
     p[0] = ast.BinaryExpression(p[1], p[2], p[3])
예제 #11
0
    def generateIR(self, ast: Ast):
        # we should also generate declaration for standard library
        for funcName, funcType in LLVMCodeGenerator.standardLibraryFunctions:
            func = ir.Function(self.module, funcType, funcName)
            self.symbolTable.put(funcName, func)

        # declare extern NVector struct (empty it's defined in runtime library)

        # start by generating main function
        functionName = 'main'
        functionType = ir.FunctionType(irIntType(), [], False)
        func = ir.Function(self.module, functionType, functionName)
        self.symbolTable.put(functionName, func)

        entryBlock = func.append_basic_block('entry')
        self.builder = ir.IRBuilder(entryBlock)

        # traverse ast and generate code
        ast.codegen(self)

        retVal = ir.Constant(irIntType(), 0)
        self.builder.ret(retVal)

        return self.module
예제 #12
0
 def p_if_else_statement(self, p):
     """
     if_statement : IF LBRACKET relation RBRACKET body ELSE body
     """
     p[0] = ast.If(p[3], p[5], p[7])
예제 #13
0
 def p_while_statement(self, p):
     """while_statement : WHILE LBRACKET relation RBRACKET body"""
     p[0] = ast.While(p[3], p[5])
예제 #14
0
	def current_variable(self, node,datatype):
		variable = Ast.id()
		variable.id =  "%{}.{}".format(node.id, self.allocated_objects[node.id])
		variable.type = datatype
		return variable
예제 #15
0
 def p_if_statement(self, p):
     """
     if_statement : IF LBRACKET relation RBRACKET body %prec IF
     """
     p[0] = ast.If(p[3], p[5])
예제 #16
0
 def p_keyword_return(self, p):
     """
     keyword : RETURN expression
     """
     p[0] = ast.Return(p[2])
예제 #17
0
 def p_relation(self, p):
     """relation : expression logic_operator expression"""
     p[0] = ast.BinaryExpression(p[1], p[2], p[3])
예제 #18
0
	def create_temp(self, type):
		self.allocated_temp += 1
		temp = Ast.temp()
		temp.id = "%{}".format(self.allocated_temp)
		temp.type = type
		return temp
예제 #19
0
 def p_expression_negation(self, p):
     """
     expression : MINUS expression %prec UMINUS
     """
     p[0] = ast.Negation(p[2])
예제 #20
0
 def p_assignment(self, p):
     """
     assignment : variable assignment_operator expression
     """
     p[0] = ast.Assignment(p[1], p[2], p[3])
예제 #21
0
 def p_program(self, p):
     """PROGRAM : CODE_BLOCK"""
     p[0] = ast.Program(p[1])
예제 #22
0
 def p_matrix(self, p):
     """
     matrix : LSQUARE rows RSQUARE
     """
     p[0] = ast.Matrix(p[2])
예제 #23
0
 def p_expression_transposition(self, p):
     """
     expression : LBRACKET expression RBRACKET TRANSPOSITION
     """
     p[0] = ast.Transposition(p[2])
예제 #24
0
 def p_id_transposition(self, p):
     """
     expression : ID TRANSPOSITION
     """
     p[0] = ast.Transposition(ast.Variable(p[1]))
예제 #25
0
 def p_for_statement(self, p):
     """for_statement : FOR ID ASSIGN range body"""
     p[0] = ast.For(p[2], p[4], p[5])
예제 #26
0
 def p_keyword_continue(self, p):
     """
     keyword : CONTINUE
     """
     p[0] = ast.Continue()
예제 #27
0
 def p_variable_attribute(self, p):
     """
     variable_attribute : ID LSQUARE sequence RSQUARE
     """
     p[0] = ast.VariableAttribute(p[1], p[3])
예제 #28
0
 def p_expression_id(self, p):
     """expression : ID"""
     p[0] = ast.Variable(p[1])
예제 #29
0
class Parser(object):

	# Constructeur
	def __init__(self):
		self.liste = Tokens()
		self.ast = Ast()
		self.indentation = 0
		self.nb_errors = 0
	# Destructeur
	def terminer(self):
		self.ast.terminer()

	# Printeur
	def __str__(self):
		return "it's me, Mario"

	# Tokenizer
	def read_tokens(self, file_path):
		fichier = open(file_path)
		lecteur = fichier.readline
		g = tokenize.generate_tokens(lecteur)
		for _, token, coord, _, _  in g:
			if token == "\n":
				continue
			self.liste.add(token, coord[0], coord[1])
		print self.liste

	# Commencer l'analyse
	def analyse(self):
		self.ast.add_brain(self.parse_brain())
		print "Nombre d'erreurs de parsing :\t", self.nb_errors
		self.ast.visiter()

	# Verifier si le token courant est bien de ce type et passer au suivant
	def expect(self, kind):
		token = self.liste.get()
		if re.search(kind, token):
			sys.stdout.write(self.liste.pick())
			sys.stdout.write(" ")
			return token
		else:
			self.endl()
			self.nb_errors += 1
			x, y = self.liste.coord()
			print "[Error] [" + str(x) + ";" + str(y) + "] Expected token : " + kind + ", get : " + token

	# Tester si le token actuel est de ce type
	def test(self, kind):
		return re.search(kind, self.liste.get())

	# Tester si le token suivant est de ce type
	def test_plus_1(self, kind):
		return re.search(kind, self.liste.get_plus_1())

	# Ajouter une indentation
	def indent(self):
		self.indentation += 1

	# Supprimer une indentation
	def desindent(self):
		self.indentation -= 1

	# Nouvelle ligne
	def endl(self):
		sys.stdout.write("\n")
		for i in range(self.indentation):
			sys.stdout.write("\t")

######### Grammaire ...

	# Bloc principal de cerveau
	def parse_brain(self):
		self.expect(d.brain)
		token = self.expect(d.identifier)
		brain = T_brain(self.ast, token)
		self.expect(d.laccol)
		self.indent()
		self.endl()
		continuer = True
		while continuer:
			if self.test(d.raccol):
				continuer = False
			elif self.test(d.var):
				brain.add_b_var(self.parse_block_variables())
			elif self.test(d.layers):
				brain.add_b_layers(self.parse_block_layers())
			elif self.test(d.inp):
				brain.add_b_input(self.parse_block_input())
			elif self.test(d.out):
				brain.add_b_output(self.parse_block_output())
			elif self.test(d.obj):
				brain.add_b_goal(self.parse_block_goal())
			elif self.test(d.struct):
				brain.add_b_structure(self.parse_block_structure())
			elif self.test(d.interf):
				brain.add_b_interface(self.parse_block_interface())
			else:
				continuer = False
		self.desindent()
		self.expect(d.raccol)
		self.endl()
		return brain

	# Bloc declaration de variables
	def parse_block_variables(self):
		self.expect(d.var)
		self.expect(d.laccol)
		self.indent()
		self.endl()
		b_var = T_block_vars(self.ast, "variables")
		continuer = True
		while continuer:
			if self.test(d.raccol):
				continuer = False
			elif self.test(d.integer):
				b_var.add_int(self.parse_declaration_int())
			elif self.test(d.scale):
				b_var.add_scale(self.parse_declaration_scale())
			else:
				continuer = False
		self.desindent()
		self.expect(d.raccol)
		self.endl()
		return b_var

	# Bloc declaration d'inputs
	def parse_block_input(self):
		self.expect(d.inp)
		self.expect(d.laccol)
		self.indent()
		self.endl()
		b_input = T_block_inputs(self.ast, "inputs")
		continuer = True
		while continuer:
			if self.test(d.raccol):
				continuer = False
			elif self.test(d.identifier):
				b_input.add_input(self.parse_declaration_ioc())
			else:
				continuer = False
		self.desindent()
		self.expect(d.raccol)
		self.endl()
		return b_input

	# Bloc declaration d'outputs
	def parse_block_output(self):
		self.expect(d.out)
		self.expect(d.laccol)
		self.indent()
		self.endl()
		b_output = T_block_outputs(self.ast, "outputs")
		continuer = True
		while continuer:
			if self.test(d.raccol):
				continuer = False
			elif self.test(d.identifier):
				b_output.add_output(self.parse_declaration_ioc())
			else:
				continuer = False
		self.desindent()
		self.expect(d.raccol)
		self.endl()
		return b_output

	# Bloc declaration d'objectifs
	def parse_block_goal(self):
		self.expect(d.obj)
		self.expect(d.laccol)
		self.indent()
		self.endl()
		b_goal = T_block_goal(self.ast, "objectifs")
		continuer = True
		while continuer:
			if self.test(d.raccol):
				continuer = False
			elif self.test(d.identifier):
				b_goal.add_goal(self.parse_declaration_ioc())
			else:
				continuer = False
		self.desindent()
		self.expect(d.raccol)
		self.endl()
		return b_goal

	# Bloc declaration de couches
	def parse_block_layers(self):
		self.expect(d.layers)
		self.expect(d.laccol)
		self.indent()
		self.endl()
		b_couche = T_block_couches(self.ast, "couches")
		continuer = True
		while continuer:
			if self.test(d.raccol):
				continuer = False
			elif self.test(d.identifier):
				b_couche.add_couche(self.parse_declaration_ioc())
			else:
				continuer = False
		self.desindent()
		self.expect(d.raccol)
		self.endl()
		return b_couche

	# Bloc declaration de structure
	def parse_block_structure(self):
		self.expect(d.struct)
		self.expect(d.laccol)
		self.indent()
		self.endl()
		b_struct = T_block_struct(self.ast, "structures")
		continuer = True
		while continuer:
			if self.test(d.raccol):
				continuer = False
			elif self.test(d.identifier):
				b_struct.add_struct(self.parse_declaration_structure())
			else:
				continuer = False
		self.desindent()
		self.expect(d.raccol)
		self.endl()
		return b_struct

	# Bloc declaration d'interface
	def parse_block_interface(self):
		self.expect(d.interf)
		self.expect(d.laccol)
		self.indent()
		self.endl()
		b_interface = T_block_interface(self.ast, "interfaces")
		continuer = True
		while continuer:
			if self.test(d.raccol):
				continuer = False
			elif self.test(d.clock):
				b_interface.add_clock(self.parse_declaration_clock())
			elif self.test(d.reset):
				b_interface.add_reset(self.parse_declaration_reset())
			elif self.test(d.learn):
				b_interface.add_learn(self.parse_declaration_learn())
			else:
				continuer = False
		self.desindent()
		self.expect(d.raccol)
		self.endl()
		return b_interface

	# Declaration d'une constante
	def parse_declaration_int(self):
		self.expect(d.integer)
		token = self.expect(d.identifier)
		self.expect(d.equal)
		number = self.expect(d.number)
		self.expect(d.semicolon)
		self.endl()
		return T_int(self.ast, token, number)

	# Appel d'un nombre ou d'une constante
	def parse_const(self):
		if self.test(d.number):
			return self.expect(d.number)
		else:
			return T_const(self.ast, self.expect(d.identifier))

	# Declaration d'une echelle
	def parse_declaration_scale(self):
		self.expect(d.scale)
		token = self.expect(d.identifier)
		self.expect(d.equal)
		n1 = self.parse_const()
		self.expect(d.comma)
		n2 = self.parse_const()
		self.expect(d.semicolon)
		self.endl()
		return T_scale(self.ast, token, n1, n2)

	# Corps de declaration d'une input, output ou couche
	def parse_declaration_ioc(self):
		name = self.expect(d.identifier)
		size_tab = 1
		scale = T_scale(self.ast, "1_scale_unitaire", 0, 1)
		if self.test(d.lbracket):
			self.expect(d.lbracket)
			size_tab = self.parse_const()
			self.expect(d.rbracket)
		if self.test(d.semicolon):
			self.expect(d.semicolon)
			self.endl()
		else:
			self.expect(d.scale)
			if self.test_plus_1(d.comma):
				n1 = self.parse_const()
				self.expect(d.comma)
				n2 = self.parse_const()
				scale = T_scale(self.ast, "0_scale_perso", n1, n2)
				self.expect(d.semicolon)
				self.endl()
			else:
				scale = T_scale(self.ast, self.expect(d.identifier), 0, 0)
				self.expect(d.semicolon)
				self.endl()
		return T_ioc(self.ast, name, size_tab, scale)

	# Declaration d'une structure
	def parse_declaration_structure(self):
		liste_structures = []
		id1 = self.expect(d.identifier)
		id1_from = -1
		id1_to = -1
		if self.test(d.lbracket):
			self.expect(d.lbracket)
			id1_from = self.parse_const()
			self.expect(d.to)
			id1_to = self.parse_const()
			self.expect(d.rbracket)
		continuer = True
		while continuer:
			if self.test(d.semicolon):
				self.expect(d.semicolon)
				continuer = False
			elif self.test(d.substract):
				self.expect(d.substract)
				self.expect(d.sup)
				id2 = self.expect(d.identifier)
				id2_from = -1
				id2_to = -1
				if self.test(d.lbracket):
					self.expect(d.lbracket)
					id2_from = self.parse_const()
					self.expect(d.to)
					id2_to = self.parse_const()
					self.expect(d.rbracket)
				liste_structures.append(T_structure(self.ast, id1, id1_from, id1_to, id2, id2_from, id2_to))
				id1 = id2
				id1_from = id2_from
				id1_to = id2_to
			else:
				continuer = False
		self.endl()
		return liste_structures

	# Declaration de l'horloge
	def parse_declaration_clock(self):
		self.expect(d.clock)
		clock = T_clock(self.ast, self.expect(d.identifier))
		self.expect(d.semicolon)
		self.endl()
		return clock

	# Declaration du reset
	def parse_declaration_reset(self):
		self.expect(d.reset)
		reset = T_reset(self.ast, self.expect(d.identifier))
		self.expect(d.semicolon)
		self.endl()
		return reset

	# Declaration de l'activateur d'apprentissage
	def parse_declaration_learn(self):
		self.expect(d.learn)
		learn = T_learn(self.ast, self.expect(d.identifier))
		self.expect(d.semicolon)
		self.endl()
		return learn
예제 #30
0
	def visit_Num(self, node):
		num =  Ast.id()
		num.id = node.n
		num.type = self.get_datatype(num.id)
		return num
예제 #31
0
 def p_statement(self, p):
     """
     statement : assignment
               | keyword
     """
     p[0] = ast.Instruction(p[1])
예제 #32
0
 def p_expression_fun(self, p):
     """
     expression : function LBRACKET expression RBRACKET
                | function LBRACKET sequence RBRACKET
     """
     p[0] = ast.Function(p[1], p[3])
예제 #33
0
 def p_variable(self, p):
     """
     variable : ID
              | variable_attribute
     """
     p[0] = ast.Variable(p[1])
예제 #34
0
 def p_keyword_print(self, p):
     """
     keyword : PRINT sequence
     """
     p[0] = ast.Print(p[2])
예제 #35
0
 def p_keyword_break(self, p):
     """
     keyword : BREAK
     """
     p[0] = ast.Break()
예제 #36
0
	def __init__(self):
		self.liste = Tokens()
		self.ast = Ast()
		self.indentation = 0
		self.nb_errors = 0