Beispiel #1
0
    def start_game(self, code=None, counter=1):
        """" Start the game / next round"""
        if code is None:
            while True:
                opponent = input(
                    "Wil je spelen tegen een CPU of tegen een andere speler: "
                ).lower()
                if opponent == "cpu" or opponent == "speler":
                    break
                else:
                    print("Foutieve invoer!")
            if opponent == "cpu":
                code = CodeGenerator().generate_random_code()
            if opponent == "speler":
                code = CodeGenerator().get_user_code("Voer je code in: ", True)
                """Zet in je build configurations emulate terminal in output console aan (pycharm)"""

        print(f"Poging {counter}.")
        guess = CodeGenerator().get_user_code("Voer je gok in: ", False)
        feedback = CodeGenerator().generate_feedback(code, guess)
        if guess == code:
            print(f"Je hebt gewonnen! Het heeft je {counter} beurten gekost.")
        elif counter < 6:
            print(
                f"Je hebt {feedback[0]} op de juiste plaats en de juiste kleur, en {feedback[1]} "
                f"van de juiste kleur alleen.")
            self.start_game(code, counter + 1)

        else:
            print(f"Je hebt verloren! Het antwoord was: {code}.")
Beispiel #2
0
 def start_game(self,
                code=None,
                counter=1,
                feedback=None,
                algoritme=None,
                previous_guess=None):
     """Starts the game, or the next round."""
     if code is None:
         code = CodeGenerator().get_user_code("Voer je code in: ", False)
     if algoritme is None:
         algoritme = input(
             "Welk gok-algoritme wil je gebruiken?")  # unimplemented.
         algoritme = "test"
     if algoritme:
         guess = self.guess_standard(previous_guess, feedback)
         print(f"Ronde {counter}.")
         print(f"Computer gokt: {guess}")
     if code == guess:
         print(f"CPU wint in {counter} beurten!")
     elif counter < 6:
         input("Druk op enter om verder te gaan.")
         feedback = CodeGenerator().generate_feedback(code, guess)
         self.start_game(code, counter + 1, feedback, algoritme, guess)
     else:
         print("Speler wint!")
Beispiel #3
0
def main(argv):

    inputFile = FileStream(argv[1])
    lexer = CLexer(inputFile)
    stream = CommonTokenStream(lexer)
    parser = CParser(stream)
    tree = parser.prog()

    if parser.getNumberOfSyntaxErrors():
        return

    # Visualise parse tree
    parseTreeDotGen = ParseTreeDotGenerator()
    parseTreeDotGen.generateDOT(parser,
                                tree,
                                "output/parse_tree.gv",
                                render=False)

    # Build AST
    astBuilder = ASTBuilder()
    AST = astBuilder.visit(tree)

    # Semantic Validation
    semanticValidator = SemanticValidator()
    AST.accept(semanticValidator)

    # Print errors, if any
    if semanticValidator.errors:
        for error in semanticValidator.errors:
            print("ERROR: " + error)
        return

    # Code optimiser
    optimiser = Optimiser(semanticValidator.symbolTable)
    AST.accept(optimiser)

    # Print warnings, if any
    if optimiser.warnings:
        for warning in optimiser.warnings:
            print("WARNING: " + warning)

    # Visualise AST
    dotGraph = AST.visit(DotGraphBuilder)
    dotGraph.render("output/ast.gv", view=False)

    # Code generator
    codeGenerator = None
    if 2 <= len(argv) - 1:
        codeGenerator = CodeGenerator(optimiser.symbolTable, argv[2])
    else:
        codeGenerator = CodeGenerator(optimiser.symbolTable)
    AST.accept(codeGenerator)
Beispiel #4
0
    def compile(self, source, env=None, library=False):
        if env == None:
            env = Environment()

        # parse input
        (definitions, errors) = Parser().parse(source)

        # check for errors
        if len(errors) > 0:
            return ("", errors)

        # type checking
        for definition in definitions:
            TypeChecker().check(errors, env, definition)

        # check for errors
        if len(errors) > 0:
            return ("", errors)

        # code generation
        code = ""
        generator = CodeGenerator()
        for node in definitions:
            symbol = node[0].value()
            code += generator.generateDefinition(env, symbol, template)

        # generate library
        if library:
            code += generator.generateLibrary(template)

        return (code, errors)
Beispiel #5
0
class DriverGen(object):
    EOF = -1
    CR = '\r'
    LF = '\n'

    srcName = ''  # name of the attributed grammar file
    srcDir = ''  # directory of attributed grammar file

    codeGen = CodeGenerator()

    @staticmethod
    def WriteDriver():
        fr = str(Tab.gramSy.name + '.frame')
        fn = Tab.gramSy.name + '.py'
        fn = str(fn)
        DriverGen.codeGen.openFiles([fr, 'Driver.frame'],
                                    Tab.gramSy.name + '.atg', fn, True)
        DriverGen.codeGen.CopyFramePart('-->begin')
        #DriverGen.codeGen.CopyFramePart( '-->class' )
        #DriverGen.codeGen.write( Tab.gramSy.name )
        DriverGen.codeGen.CopyFramePart('$$$')
        DriverGen.codeGen.close()
        os.chmod(fn, 0755)

    @staticmethod
    def Init(f, dir):
        assert isinstance(f, str)
        assert isinstance(dir, str)
        DriverGen.srcName = f
        DriverGen.srcDir = dir
Beispiel #6
0
    def check(soldir, asttree, num):
        codeGen = CodeGenerator()
        path = os.path.join(soldir, str(num))
        if not os.path.isdir(path):
            os.mkdir(path)
        f = open(os.path.join(soldir, str(num) + ".txt"), "w")
        try:
            codeGen.gen(asttree, path)

            subprocess.call("java  -jar " + JASMIN_JAR + " " + path +
                            "/MPClass.j",
                            shell=True,
                            stderr=subprocess.STDOUT)
            cmd = "java -cp ./lib" + os.pathsep + ". MPClass"
            subprocess.run(cmd, shell=True, stdout=f, timeout=5)
        except StaticError as e:
            f.write(str(e))
        except subprocess.TimeoutExpired:
            f.write("Time out\n")
        except subprocess.CalledProcessError as e:
            raise RuntimeError(
                "command '{}' return with error (code {}): {}".format(
                    e.cmd, e.returncode, e.output))
        finally:
            f.close()
Beispiel #7
0
    def CTNGenerate_C(self, buildpath, locations):
        current_location = self.GetCurrentLocation()
        location_str = "_".join(map(str, current_location))
        codeGenerator = CodeGenerator(self)

        text = ""

        text += codeGenerator.GenerateCode()

        text += "int __init_%s(int argc,char **argv)\n{\n"%location_str
        text += "\t" + codeGenerator.GeneretaInit()
        text += "\n}\n\n"

        text += "void __cleanup_%s(void)\n{\n"%location_str
        text += "\n}\n\n"

        text += "void __retrieve_%s(void)\n{\n"%location_str
        text += "   ;\n"
        text += "\n}\n\n"

        text += "void __publish_%s(void)\n{\n"%location_str
        text += "\n"
        text += "\n}\n\n"

        Gen_Cfile_path = os.path.join(buildpath, "mbSlave_%s.c"%location_str)
        cfile = open(Gen_Cfile_path,'w')
        cfile.write(text)
        cfile.close()

        matiec_flags = '"-I%s"'%os.path.abspath(self.GetCTRoot().GetIECLibPath())

        return [(Gen_Cfile_path, str(matiec_flags))],str(""),True
Beispiel #8
0
    def __init__(self, view=None, path=None):
        self.view = view
        self.image_path = path

        self.processor = CodeMagnetsImageProcessor()
        self.processor.train(readFromFile=True, path="data.csv")
        self.code_generator = CodeGenerator()
        self.code_runner = CodeRunner()
Beispiel #9
0
    def test(input, expect, num):
        print('----')
        print('****')
        print('Test #', num)
        solpath = "./test/solutions/"
        dest = open(solpath + str(num) + ".txt", "w")

        if type(input) is str:
            # print("Input: ", input)
            inputfile = TestUtil.makeSource(input, num)
            lexer = BKITLexer(inputfile)
            tokens = CommonTokenStream(lexer)
            parser = BKITParser(tokens)
            tree = parser.program()
            asttree = ASTGeneration().visit(tree)
        else:
            # print('Input: ', input)
            inputfile = TestUtil.makeSource(str(input), num)
            asttree = input

        codeGen = CodeGenerator()

        path = solpath + str(num)
        if not os.path.isdir(path):
            os.mkdir(path)
        try:
            codeGen.gen(asttree, path)

            subprocess.call("java  -jar " + JASMIN_JAR + " " + path +
                            "/MCClass.j",
                            shell=True,
                            stderr=subprocess.STDOUT)

            f = open(solpath + str(num) + ".txt", "w")
            subprocess.call("java -cp ./lib" + os.pathsep + ". MCClass",
                            shell=True,
                            stdout=f)
            f.close()
        except StaticError as e:
            print('died')
            dest.write(str(e))
        except subprocess.CalledProcessError as e:
            print('died')
            raise RuntimeError(
                "command '{}' return with error (code {}): {}".format(
                    e.cmd, e.returncode, e.output))
        finally:
            dest.close()
        dest = open(solpath + str(num) + ".txt", "r")
        line = dest.read()

        if line != expect: print('f**k no')
        else: print('f**k yea')
        print('Expect: ', expect)
        print('Result: ', line)
        print('****')
        print('----')
        return line == expect
Beispiel #10
0
 def __init__(self, input_code: str):  # TODO initialize
     self.symbol_table = SymbolTable()
     self.symbol_table.new_scope()
     self.pars_stack = Stack()
     self.scanner = Scanner(input_code, symbol_table=self.symbol_table)
     self.dfa = TransitionDiagram()  # TODO
     self.dfa.make_diagrams()
     self.look_ahead = ""
     self.current_token = None
     self.current_token_info = None
     self.pars_stack.push(self.dfa.start_state)
     self.code_generator = CodeGenerator(self.symbol_table)
Beispiel #11
0
 def __init__(self, file_name):
     self.symbol_table = SymbolTable()
     self.pc = 2
     self.symbol_table.entries.append(
         SymbolTableEntry('output', 'ID', None, 1, None, None))
     self.scope_stack: List[int] = [0]
     self.memory_manager = MemoryManager()
     self.scanner = Scanner(file_name, self.symbol_table)
     self.semantic_analyser = SemanticAnalyser(self.symbol_table,
                                               self.scope_stack, self.pc,
                                               self.memory_manager)
     self.code_generator = CodeGenerator(self.symbol_table,
                                         self.memory_manager, self.pc,
                                         self.scope_stack)
Beispiel #12
0
def __main__():
    length, distance = read_inputs()

    code_generator = CodeGenerator(length, distance)

    code_words = code_generator.generate_code()

    if len(code_words) == 1:
        print("No code!")
    else:
        print(f"{len(code_words)} words:")
        for word in code_words:
            print(word)

    run_tests()
Beispiel #13
0
    def test_code_4(self):
        code_length = 10
        code_distance = 5

        code_generator = CodeGenerator(code_length, code_distance)
        code_words = code_generator.generate_code()

        for word in code_words:
            self.assertEqual(word.get_length(), code_length)

        for i in range(0, len(code_words)):
            for j in range(i + 1, len(code_words)):
                word_distance = CodeWord.get_distance(code_words[i],
                                                      code_words[j])
                self.assertEqual(word_distance >= code_distance, True)
Beispiel #14
0
    def printGeneratedCode(self, line):
        tokens = line.strip().split(' ')

        if len(tokens) < 2:
            print("No symbol specified")

        for symbol in tokens[1:]:
            if not symbol in self.env.elements:
                print("No symbol " + symbol)
                continue

            # code generation
            generator = CodeGenerator()
            code = generator.generateDefinition(self.env, symbol, template)
            if code == None:
                print("Native function")
            else:
                print(code.strip())
    def test(input, expect, num):
        solpath = "./test/solutions/"
        dest = open(solpath + str(num) + ".txt","w")
        
        if type(input) is str:
            inputfile = TestUtil.makeSource(input,num)
            lexer = BKITLexer(inputfile)
            tokens = CommonTokenStream(lexer)
            parser = BKITParser(tokens)
            tree = parser.program()
            asttree = ASTGeneration().visit(tree)
        else:
            inputfile = TestUtil.makeSource(str(input),num)
            asttree = input
        
        
        codeGen = CodeGenerator()
        
        path = solpath + str(num)
        if not os.path.isdir(path):
            os.mkdir(path)
        try:
            print("{0}{1}{0}".format('='*30, "Test "+ str(num)))
            codeGen.gen(asttree, path)
            
            subprocess.call("java  -jar "+ JASMIN_JAR + " " + path + "/MCClass.j",shell=True,stderr=subprocess.STDOUT)
            #print("java  -jar "+ JASMIN_JAR + " " + path + "/MCClass.j")

            f = open(solpath + str(num) + ".txt","w")
            subprocess.call("java -cp ./lib" + os.pathsep + ". MCClass",shell=True, stdout = f)
            #print("java -cp ./lib" + os.pathsep + ". MCClass")
            f.close()
        except StaticError as e:
            print(f"Error of test {num} is {e}")
            dest.write(str(e))
        except subprocess.CalledProcessError as e:
            raise RuntimeError("command '{}' return with error (code {}): {}".format(e.cmd, e.returncode, e.output))
        finally:
            dest.close()
        dest = open(solpath + str(num) + ".txt","r")
        line = dest.read()
        print(f"Result: {line}")
        print("{0}{1}{0}\n".format('='*30, "End test " + str(num)))
        return line == expect
Beispiel #16
0
def main():
    parser = OptionParser()
    parser.add_option("-i",
                      "--input",
                      dest="input",
                      help="input file. example: -i C:\\work\\Test.hlsl")
    parser.add_option("-o",
                      "--output",
                      dest="output",
                      help="output file. example: -o C:\\work\\Test.frag.spv")
    parser.add_option("-D",
                      "--define",
                      action='append',
                      dest="define",
                      help="example: -D DEBUG")
    parser.add_option("-I",
                      "--include",
                      action='append',
                      dest="include",
                      help="example: -I ../inc")
    parser.add_option("-t",
                      "--template",
                      dest='template',
                      help="example: -t ShaderLoadInterfaceTemplate.h")
    parser.add_option("-s", "--stage", dest='stage', help="example: -s Vertex")
    parser.add_option("-b",
                      "--binarylocation",
                      dest='binarylocation',
                      help="example: -b C:\\work\\some_vertex.vs.spv")
    parser.add_option("-x",
                      "--support_path",
                      dest='support_path',
                      help="example: -x C:\\work\\some_vertex.vs.support")

    options, arguments = parser.parse_args()

    with open(options.input, 'r') as file:
        preprocessor = Preprocessor(file, options.define, options.include)
        lexical_analyzer = LexicalAnalyzer(preprocessor)
        syntax_analyzer = SyntaxAnalyzer(lexical_analyzer)
        codeGenerator = CodeGenerator(
            syntax_analyzer.root_level_declarations(), options.template,
            options.output, options.stage, options.binarylocation,
            options.support_path, options.input)
def main(argv):
    input = FileStream(argv[1])
    print("\033[92mCompiling and executing {}\033[0m".format(argv[1]))

    lexer = C_GrammarLexer(input)
    stream = CommonTokenStream(lexer)
    parser = C_GrammarParser(stream)
    tree = parser.start()
    printer = GrammarListener()
    walker = ParseTreeWalker()
    walker.walk(printer, tree)

    symbol_table = SymbolTable()
    symbol_table.fill_tree(printer.AST_Root)

    CG = CodeGenerator(printer.AST_Root, symbol_table)
    CG.generate()
    symbol_table.to_dot()
    CG.writeToFile(argv[2])
    def __init__(self):
        self.tokens = []
        self.sintaxes = []
        self.automaton_state = SintaxAutomaton()
        self.codeGenerator = CodeGenerator()

        # current token none by default
        self.current_token = None
        self.current_token_id = 0

        # current variable being assigned
        self.current_variable = ""

        # global variable table
        self.variables = {}

        # global function table
        self.functions = {}

        # variables in FOR loops
        self.for_variables = {}
        self.last_for_loops = []
Beispiel #19
0
    def process(self):
        ''' Process the assembly code '''

        lexicalAnalyzer = LexicalAnalyzer(self.args)
        syntaxAnalyzer = SyntaxAnalyzer(self.args)
        codeGenerator = CodeGenerator(self.args)

        # lexical analysis
        ok = lexicalAnalyzer.analyze()
        if not ok:
            return False

        # syntax analysis
        ok = syntaxAnalyzer.analyze(lexicalAnalyzer.tokens)
        if not ok:
            return False

        # code generation
        ok = codeGenerator.generate(syntaxAnalyzer.expressions)
        if not ok:
            return False

        return True
Beispiel #20
0
class ParserGen( object ):
   maxTerm =    3    # sets of size < maxTerm are enumerated
   ls      = "\n"

   tErr    =    0    # error codes
   altErr  =    1
   syncErr =    2

   usingPos =  None  # usingPos: Position   "using" definitions from the attributed grammar

   errorNr   = 0      # highest parser error number
   curSy     = None   # symbol whose production is currently generated
   err       = None   # generated parser error messages
   srcName   = ''     # name of attributed grammar file
   srcDir    = ''     # directory of attributed grammar file
   symSet    = [ ]

   codeGen   = CodeGenerator( )
   
   @staticmethod
   def Overlaps( s1, s2 ):
      assert isinstance( s1, set )
      assert isinstance( s2, set )
      ln = len(s1)
      for i in xrange( 0, ln ):
         if (i in s1) and (i in s2):
            return True
      return False

   @staticmethod
   def GenErrorMsg( errTyp, sym ):
      assert isinstance( errTyp, int )
      assert isinstance( sym, Symbol )
      ParserGen.errorNr += 1
      ParserGen.err.write( ParserGen.ls + '      ' + str(ParserGen.errorNr) + ' : "' )
      if errTyp == ParserGen.tErr:
         if sym.name[0] == '"':
            ParserGen.err.write( str(DFA.Escape( sym.name )) + ' expected' )
         else:
            ParserGen.err.write( str(sym.name) + ' expected' )
      elif errTyp == ParserGen.altErr:
         ParserGen.err.write( 'invalid ' + str(sym.name) )
      elif errTyp == ParserGen.syncErr:
         ParserGen.err.write( 'this symbol not expected in ' + str(sym.name) )
      ParserGen.err.write('",' )

   @staticmethod
   def NewCondSet( s ):
      assert isinstance( s, set )
      for i in xrange( 1, len(ParserGen.symSet) ):
        # skip symSet[0] (reserved for union of SYNC sets)
        if s == ParserGen.symSet[i]: #s.equals( ParserGen.symSet[i] ):
           return i
      ParserGen.symSet.append( copy.copy(s) ) 
      return len(ParserGen.symSet) - 1

   @staticmethod
   def GenCond( s, p ):
      assert isinstance( s, set  )
      assert isinstance( p, Node )
      if p.typ == Node.rslv:
         ParserGen.codeGen.CopySourcePart( p.pos, 0 )
      else:
         n = len(s)
         if n == 0:
            ParserGen.codeGen.write( 'False' ) # should never happen
         elif n <= ParserGen.maxTerm:
            for i in xrange( 0, len(Symbol.terminals) ):
               sym = Symbol.terminals[i]
               assert isinstance( sym, Symbol )
               if sym.n in s:
                  ParserGen.codeGen.write( 'self.la.kind == ')
                  ParserGen.PrintTermName( sym )
                  n -= 1
                  if n > 0:
                     ParserGen.codeGen.write( ' or ' )
         else:
            ParserGen.codeGen.write( 'self.StartOf(' + str(ParserGen.NewCondSet( s )) + ')' )

   @staticmethod
   def GenCode( p, indent, isChecked ):
      #assert isinstance( p, Node )
      assert isinstance( indent, int )
      assert isinstance( isChecked, set )
      while p is not None:
         if p.typ == Node.nt:       # Non-Terminals
            ParserGen.codeGen.Indent( indent )
            if p.retVar is not None:
               ParserGen.codeGen.write( p.retVar + ' = ' )
            ParserGen.codeGen.write( 'self.' + p.sym.name + '(' )
            ParserGen.codeGen.CopySourcePart( p.pos, 0 )
            ParserGen.codeGen.write( ')\n' )
         elif p.typ == Node.t:      # Terminals
            ParserGen.codeGen.Indent( indent )
            if p.sym.n in isChecked:
               ParserGen.codeGen.write( 'self.Get( )\n' )
            else:
               ParserGen.codeGen.write( 'self.Expect(' )
               ParserGen.PrintTermName( p.sym )
               ParserGen.codeGen.write( ')\n' )
         elif p.typ == Node.wt:
            ParserGen.codeGen.Indent( indent )
            s1 = Tab.Expected( p.next, ParserGen.curSy )
            s1 |= Tab.allSyncSets
            ParserGen.codeGen.write( 'self.ExpectWeak(' )
            ParserGen.PrintTermName( p.sym )
            ParserGen.codeGen.write( ', ' + str(ParserGen.NewCondSet( s1 )) + ')\n' )
         elif p.typ == Node.any:
            ParserGen.codeGen.Indent( indent )
            ParserGen.codeGen.write( 'self.Get()\n' )
         elif p.typ == Node.eps:
            ParserGen.codeGen.Indent( indent )
            ParserGen.codeGen.write( 'pass\n' )
         elif p.typ == Node.rslv:
            #ParserGen.codeGen.Indent( indent )
            #ParserGen.codeGen.write( 'pass\n' )
            pass   # Nothing to do
         elif p.typ == Node.sem:
            ParserGen.codeGen.CopySourcePart( p.pos, indent )
         elif p.typ == Node.sync:
            ParserGen.codeGen.Indent( indent)
            ParserGen.GenErrorMsg( ParserGen.syncErr, ParserGen.curSy )
            s1 = copy.copy(p.set)
            ParserGen.codeGen.write( 'while not (' )
            ParserGen.GenCond( s1,p )
            ParserGen.codeGen.write( '):\n' )
            ParserGen.codeGen.Indent( indent+1 )
            ParserGen.codeGen.write( 'self.SynErr(' + str(ParserGen.errorNr) + ')\n' )
            ParserGen.codeGen.Indent( indent+1 )
            ParserGen.codeGen.write( 'self.Get()\n' )
         elif p.typ == Node.alt:
            s1 = Tab.First( p )
            p2 = p
            equal = (s1 == isChecked)
            while p2 is not None:
               s1 = Tab.Expected( p2.sub, ParserGen.curSy )
               ParserGen.codeGen.Indent( indent )
               if p2 == p:
                  ParserGen.codeGen.write( 'if ' )
                  ParserGen.GenCond( s1, p2.sub )
                  ParserGen.codeGen.write( ':\n' )
               elif p2.down is None and equal:
                  ParserGen.codeGen.write( 'else:\n' )
               else:
                  ParserGen.codeGen.write( 'elif ' )
                  ParserGen.GenCond( s1, p2.sub )
                  ParserGen.codeGen.write( ':\n' )
               s1 |= isChecked
               ParserGen.GenCode( p2.sub, indent+1, s1 )
               p2 = p2.down
            if not equal:
               ParserGen.codeGen.Indent( indent )
               ParserGen.GenErrorMsg( ParserGen.altErr, ParserGen.curSy )
               ParserGen.codeGen.write( 'else:\n' )
               ParserGen.codeGen.Indent( indent+1 )
               ParserGen.codeGen.write( 'self.SynErr(' + str(ParserGen.errorNr) + ')\n' )
         elif p.typ == Node.iter:
            ParserGen.codeGen.Indent( indent )
            p2 = p.sub
            ParserGen.codeGen.write( 'while ' )
            if p2.typ == Node.wt:
               s1 = Tab.Expected( p2.next, ParserGen.curSy )
               s2 = Tab.Expected( p.next, ParserGen.curSy )
               ParserGen.codeGen.write( 'self.WeakSeparator(' )
               ParserGen.PrintTermName( p2.sym )
               ParserGen.codeGen.write( ', ' + str(ParserGen.NewCondSet(s1)) + ', ' + str(ParserGen.NewCondSet(s2)) + ')' )
               s1 = set( )
               if p2.up or p2.next is None:
                  p2 = None
               else:
                  p2 = p2.next
            else:
               s1 = Tab.First( p2 )
               ParserGen.GenCond( s1, p2 )
            ParserGen.codeGen.write( ':\n' )
            ParserGen.GenCode( p2,indent+1, s1 )
            ParserGen.codeGen.write( '\n' )
         elif p.typ == Node.opt:
            s1 = Tab.First( p.sub )
            ParserGen.codeGen.Indent( indent )
            ParserGen.codeGen.write( 'if (' )
            ParserGen.GenCond( s1, p.sub )
            ParserGen.codeGen.write( '):\n' )
            ParserGen.GenCode( p.sub, indent+1, s1 )
         
         if p.typ != Node.eps and p.typ != Node.sem and p.typ != Node.sync:
            for val in xrange( 0, len(isChecked) ):
               isChecked.discard( val )
         
         if p.up:
            break
         
         p = p.next

   @staticmethod
   def GenTokens( withNames ):
      assert isinstance( withNames, bool )
      for sym in Symbol.terminals:
         if sym.name[0].isalpha( ):
            ParserGen.codeGen.write( '   _' + sym.name + ' = ' + str(sym.n) + '\n' )
      if withNames:
         ParserGen.codeGen.write( '   # terminals\n')
         for sym in Symbol.terminals:
            ParserGen.codeGen.write( '   ' + sym.symName + ' = ' + str(sym.n) + '\n' )
         ParserGen.codeGen.write( '   # pragmas\n' )
         for sym in Symbol.pragmas:
            ParserGen.codeGen.write( '   ' + sym.symName + ' = ' + str(sym.n) + '\n' )
         ParserGen.codeGen.write( '\n' )

   @staticmethod
   def GenPragmas( ):
      for sym in Symbol.pragmas:
         ParserGen.codeGen.write( '   _' + str(sym.name) + ' = ' + str(sym.n) + '\n' )

   @staticmethod
   def GenCodePragmas( ):
      for sym in Symbol.pragmas:
         ParserGen.codeGen.write( 'if self.la.kind == ' )
         ParserGen.PrintTermName( sym )
         ParserGen.codeGen.write( ':\n' )
         ParserGen.codeGen.CopySourcePart( sym.semPos, 4, True )

   @staticmethod
   def GenProductions( ):
      for sym in Symbol.nonterminals:
         ParserGen.curSy = sym
         
         # Generate the function header
         ParserGen.codeGen.write( '   def ' + sym.name + '( self' )
         if sym.attrPos is not None:
            ParserGen.codeGen.write( ', ' )
         ParserGen.codeGen.CopySourcePart( sym.attrPos, 0 )
         ParserGen.codeGen.write( ' ):\n' )
         
         # Generate the function body
         ParserGen.codeGen.CopySourcePart( sym.semPos, 2 )
         ParserGen.GenCode( sym.graph, 2, set( ) )
         
         # Generate the function close
         if sym.retVar is not None:
            ParserGen.codeGen.write( '      return ' + sym.retVar + '\n' )
         ParserGen.codeGen.write( '\n' )

   @staticmethod
   def InitSets( ):
      for i in xrange(0,len(ParserGen.symSet)):
         s = ParserGen.symSet[i]
         ParserGen.codeGen.write( '      [' )
         j = 0
         for sym in Symbol.terminals:
            if sym.n in s:
               ParserGen.codeGen.write( 'T,' )
            else:
               ParserGen.codeGen.write( 'x,' )
            j += 1
            if j%4 == 0:
               ParserGen.codeGen.write( ' ' )
         if i == (len(ParserGen.symSet) - 1):
            ParserGen.codeGen.write( 'x]\n' )
         else:
            ParserGen.codeGen.write( 'x],\n' )

   @staticmethod
   def Init( fn, dir ):
      assert isinstance( fn, str )
      assert isinstance( dir, str )
      ParserGen.srcName = fn
      ParserGen.srcDir  = dir
      ParserGen.errorNr = -1
      ParserGen.usingPos = None

   @staticmethod
   def WriteParser( withNames ):
      assert isinstance( withNames, bool )
      assert isinstance( Tab.allSyncSets, set )
      ParserGen.symSet.append( Tab.allSyncSets )
      
      ParserGen.codeGen.openFiles( 'Parser.frame', ParserGen.srcName,
            'Parser.py', True )
      
      if withNames: 
         Tab.AssignNames( ) 
      
      ParserGen.err = StringIO.StringIO( )
      for sym in Symbol.terminals:
         ParserGen.GenErrorMsg( ParserGen.tErr, sym )
      
      ParserGen.codeGen.CopyFramePart( '-->begin' )
      if ParserGen.usingPos != None:
         ParserGen.codeGen.write( '\n' )
         ParserGen.codeGen.CopySourcePart( ParserGen.usingPos, 0 )
      ParserGen.codeGen.CopyFramePart( '-->constants' )
      ParserGen.GenTokens( withNames )
      ParserGen.codeGen.write( '   maxT = ' + str(len(Symbol.terminals) - 1) + '\n')
      ParserGen.GenPragmas( )
      ParserGen.codeGen.CopyFramePart( '-->declarations' )
      ParserGen.codeGen.CopySourcePart( Tab.semDeclPos, 0 )
      ParserGen.codeGen.CopyFramePart( '-->pragmas' )
      ParserGen.GenCodePragmas( )
      ParserGen.codeGen.CopyFramePart( '-->productions' )
      ParserGen.GenProductions( )
      ParserGen.codeGen.CopyFramePart( '-->parseRoot' )
      ParserGen.codeGen.write( Tab.gramSy.name + '()\n' )
      ParserGen.codeGen.write( '      self.Expect(' )
      ParserGen.PrintTermName( Tab.eofSy )
      ParserGen.codeGen.write( ')\n' )
      ParserGen.codeGen.CopyFramePart( '-->initialization' )
      ParserGen.InitSets( )
      ParserGen.codeGen.CopyFramePart( '-->errors' )
      ParserGen.codeGen.write( str(ParserGen.err.getvalue( )) )
      ParserGen.codeGen.CopyFramePart( '$$$' )
      ParserGen.codeGen.close( )

   @staticmethod
   def WriteStatistics( ):
      Trace.WriteLine( )
      Trace.WriteLine( 'Statistics:' )
      Trace.WriteLine( '-----------' )
      Trace.WriteLine( )
      Trace.WriteLine( str(len( Symbol.terminals )) + ' terminals' )
      Trace.WriteLine( str(len( Symbol.terminals ) + len( Symbol.pragmas ) + len( Symbol.nonterminals )) + ' symbols' )
      Trace.WriteLine( str(len(Node.nodes)) + ' nodes' )
      Trace.WriteLine( str(len(ParserGen.symSet)) + ' sets' )
      Trace.WriteLine( )

   @staticmethod
   def PrintTermName( sym ):
      assert isinstance( sym, Symbol )
      assert isinstance( sym.symName, (str,unicode) ) or (sym.symName is None)
      if sym.symName is None:
         ParserGen.codeGen.write( str(sym.n) )
      else:
         ParserGen.codeGen.write( 'Scanner.' )
         ParserGen.codeGen.write( str(sym.symName) )
Beispiel #21
0
 def __init__(self, animation_name):
     self.code_gen = CodeGenerator(animation_name)
     self.animation_name = animation_name
     self.sheet = pil_image.new('RGBA', (1024, 1024))
     self.frame_index = 0
     self.frame_count = 20
Beispiel #22
0
 def __init__(self, error_writer, file_out):
     self.semantics = Semantics(error_writer=error_writer)
     self.code_generator = CodeGenerator(self.semantics, file_out=file_out)
Beispiel #23
0
from CodeGenerator import CodeGenerator
import telebot
bot = telebot.TeleBot("1310630322:AAHk7aNFpZc4g2u0h_OC5J34XznoeTFJY88")

CodeGen = CodeGenerator()


@bot.message_handler(commands=['start'])
def start_handler(message):
    print(message)
    bot.send_message(
        message.chat.id,
        'Привет, я пока умею просто проверять коды. Попробуешь? Введи свой код.'
    )


@bot.message_handler(content_types=["text"])
def text_handler(message):
    print(message)
    if CodeGen.code_use(message.text) is True:
        bot.send_message(message.chat.id, "Ты великолепен, твой код работает!")
    else:
        bot.send_message(message.chat.id,
                         "Упс, ошибочка, код использован или не существует")


bot.polling()
Beispiel #24
0
if args.visualize:
    if not path.exists(args.visualize):
        os.makedirs(args.visualize)
    graph(parse_tree_root, path.join(args.visualize, 'original_ast'))

if parse_tree_root:
    static_semantic_analyzer = SemanticAnalyzer(parse_tree_root)
    static_semantic_analyzer.analyze()
    if args.visualize:
        static_semantic_analyzer.symbol_table.to_graph(
            path.join(args.visualize, 'symb_tab.png'))
    SemanticLogger.info(
        None, "Find {} warnings and {} errors".format(SemanticLogger.n_warn,
                                                      SemanticLogger.n_error))
    if SemanticLogger.n_error == 0:
        SemanticLogger.info(None, 'producing three address code')
        code_generator = CodeGenerator(parse_tree_root,
                                       static_semantic_analyzer.symbol_table)
        code_generator.gen_three_address_code()
        code_generator.write_file(out_file)
        SemanticLogger.info(None, 'done')

end = time.clock()

SemanticLogger.info(None, 'Time elapsed: {}s'.format(end - start))
print("=" * 20)

if args.visualize:
    graph(parse_tree_root, path.join(args.visualize, 'final_ast'))
Beispiel #25
0
 def completely_random_guess(self):
     """ Returns a radom guess"""
     return CodeGenerator().generate_random_code()
Beispiel #26
0
 def __init__(self):
     self.guess_list = []
     self.combinations = CodeGenerator().generate_all_options()
Beispiel #27
0
                        "--output-node-names",
                        nargs='+',
                        help="Names of the output nodes")
    parser.add_argument("-t",
                        "--templates",
                        nargs='+',
                        help="List of paths for the Jinja2 templates")
    parser.add_argument(
        "-d",
        "--output-directories",
        nargs='+',
        help="Paths of the output directories for the generated files")
    args = parser.parse_args()

    for model_file in args.frozen_model_filenames:
        # Create a Graph object from the default
        graph = _load_graph(model_file)

        # Cut the graph to only include the nodes between the declared input and the output nodes
        ir = IRGraph(graph,
                     args.input_node_names,
                     args.output_node_names,
                     prefix=GRAPH_OP_PREFIX)

        generator = CodeGenerator(ir)
        generator.generate_template(LIB_CC_FILE_NAME, LIB_H_FILE_NAME,
                                    args.templates, args.output_directories)

    print "Code generated for %s in %s" % (args.frozen_model_filenames,
                                           args.output_directories)
Beispiel #28
0
def password_message(message):
    if message.text == "KQ3tn2qU11zZ9pm6GajE":
        Generator = CodeGenerator()
        bot.send_message(message.chat.id, Generator.code_add())