Exemple #1
0
def main(filename):
    # get the root of the parse tree of the input file
    parseTreeRoot = parseFile(filename)

    # the errorHandler which will group all of the errors
    errorHandler = ErrorHandler(filename)

    try:
        # create an AST an attach it to a listener so the listener can fill in the tree
        abstractSyntaxTree = buildAST(parseTreeRoot)

        firstPassDecoration(abstractSyntaxTree)

        # create a symbol table and symbol table filler, fill in the table and check if everything is declared before it is used in the c file
        symbolTable = SymbolTable()
        scopeCheck(abstractSyntaxTree, errorHandler, symbolTable)

        # do the type checking
        typeCheck(abstractSyntaxTree, errorHandler)

        output(str(abstractSyntaxTree))
        output(str(symbolTable))

        # generate code
        if not errorHandler.errorCount():
            generateCode(abstractSyntaxTree, symbolTable)

    except Exception as e:
        ex_type, ex, tb = sys.exc_info()
        traceback.print_exception(ex_type, ex, tb)

    if errorHandler.errorCount() or errorHandler.warningCount():
        print(str(errorHandler.errorCount()) + " error" + ("s" if errorHandler.errorCount() != 1 else ""))
        print(str(errorHandler.warningCount()) + " warning" + ("s" if errorHandler.warningCount() != 1 else ""))
        errorHandler.printErrors()
Exemple #2
0
    def parseFile(self, filename):
        input_file = FileStream(filename)
        lexer = CLexer(input_file)
        stream = CommonTokenStream(lexer)
        parser = CParser(stream)
        programContext = parser.program()

        if parser._syntaxErrors > 0:
            raise Exception("error parsing file " + filename)

        walker = ParseTreeWalker()
        abstractSyntaxTree = AbstractSyntaxTree();
        self.errorHandler = ErrorHandler(filename)
        listener = Listener(abstractSyntaxTree)
        walker.walk(listener, programContext)

        decorator = VisitorDecorator()
        decorator.visitProgramNode(abstractSyntaxTree.root)

        symbolTable = SymbolTable()
        functionFiller = VisitorSymbolTableFiller(symbolTable, self.errorHandler)
        functionFiller.visitProgramNode(abstractSyntaxTree.root)

        tableFiller = VisitorDeclarationProcessor(symbolTable, self.errorHandler)
        tableFiller.visitProgramNode(abstractSyntaxTree.root)

        typeCheck = VisitorTypeChecker(self.errorHandler)
        typeCheck.visitProgramNode(abstractSyntaxTree.root)

        if self.errorHandler.errorCount() == 0:
            pFilename = os.path.splitext(filename)[0] + ".p"
            codeGenerator = VisitorCodeGenerator(symbolTable, pFilename)
            codeGenerator.visitProgramNode(abstractSyntaxTree.root)
def logException():
    out = cStringIO.StringIO()
    ErrorHandler.logError(out)
    
    errorTags = [frame.executable.dt._error_tag
                 for frame in Component.componentStack
                 if isinstance(frame.executable, Executables.STMLExecutable)
                 if hasattr(frame.executable.dt, '_error_tag')]
    if errorTags:
        out.write('Tag traceback (most recent tag last):\n')
        for tag in errorTags:
            if tag:
                out.write('  File "%s", line %s\n' % (tag._name, tag._lineno))
                out.write('    %s\n' % tag.tag)
            else:
                out.write('  File ??, line??\n')

    x = out.getvalue()
    Logs.ERROR(x)
    return x
Exemple #4
0
def open_file():
    print("\nPlease select the XML file containing your class data.\n")

    gradebook_list = os.listdir(save_path)
    for gradebook in gradebook_list:
        if gradebook.__contains__('.xml'):
            print('\t>', gradebook.replace('.xml', ''), '\n')
        
    FILE_NAME = os.path.join(save_path, str(input("> ")) + '.xml')

    if ErrorHandler.is_file_type('xml', FILE_NAME):
        global FILE_NAME
        main_menu()
    else:
        print("\nInvalid file type. Please choose another.")
        open_file()
Exemple #5
0
def view_menu():
    end_prompt = "Press any key to continue"
    print("\nYou are using the file {!s}\n".format(FILE_NAME))

    print("Choose an option by typing the number and pressing RETURN")
    print("\t[1] View class report.")
    print("\t[2] View student report.")
    print("\t[3] View class statistics.")
    print("\t[4] Back to main menu.")

    choice = input("> ")

    if choice == '1':
        ParseXML.print_all_grades(FILE_NAME)
        input(end_prompt)
        view_menu()

    elif choice == '2':
        print("List of students:\n")
        ParseXML.list_students(FILE_NAME)
        print("\nEnter the name of a student, then press RETURN.")
        name = input("> \n")

        if ErrorHandler.is_a_student(name, FILE_NAME):
            ParseXML.one_student_grades(FILE_NAME, name)
            input(end_prompt)
            view_menu()
        else:
            print("{!s} is not a student. Press RETURN to go back to"
                  " menu.".format(name))
            input("")
            view_menu()

    elif choice == '3':
        pass
        # TODO (CREATE STATISTICS)

    elif choice == '4':
        main_menu()
    else:
        print("Invalid selection.")
        view_menu()
        # 
        # config - pointer to current configuration object
        # yes, no, true, false - various boolean values
        ns_dict['config'] = self

        for y in ( 'yes', 'true', 'YES', 'TRUE', 'Yes', 'True' ):
            ns_dict[y] = 1 
        for n in ( 'no', 'false', 'NO', 'FALSE', 'No', 'False' ):
            ns_dict[n] = 0

        ns = ns_dict.copy()

        try:
            exec code in ns
        except:
            trace = ErrorHandler.readError()

            raise SkunkStandardError, 'cannot parse config file %s :\n%s' % \
                                      ( realfile, trace )
        for k, v in ns.items():
            if type(v) not in (types.ModuleType, types.FunctionType) and \
               k not in [ '__builtins__' ] + ns_dict.keys() and k[0] != '_':
                # Check that it's not set on the command line
                if self.has_key(k) and self._dict[k].isSetCmdLine():
                    continue

                self[k] = v
                
        # Get rid of the _dir in path if we added it there
        if chdir and _dir:
            del sys.path[sys.path.index(_dir)]
Exemple #7
0
class ASTTest():
    def setUp(self):
        self.errorHandler = None

    def parseFile(self, filename):
        input_file = FileStream(filename)
        lexer = CLexer(input_file)
        stream = CommonTokenStream(lexer)
        parser = CParser(stream)
        programContext = parser.program()

        if parser._syntaxErrors > 0:
            raise Exception("error parsing file " + filename)

        walker = ParseTreeWalker()
        abstractSyntaxTree = AbstractSyntaxTree();
        self.errorHandler = ErrorHandler(filename)
        listener = Listener(abstractSyntaxTree)
        walker.walk(listener, programContext)

        decorator = VisitorDecorator()
        decorator.visitProgramNode(abstractSyntaxTree.root)

        symbolTable = SymbolTable()
        functionFiller = VisitorSymbolTableFiller(symbolTable, self.errorHandler)
        functionFiller.visitProgramNode(abstractSyntaxTree.root)

        tableFiller = VisitorDeclarationProcessor(symbolTable, self.errorHandler)
        tableFiller.visitProgramNode(abstractSyntaxTree.root)

        typeCheck = VisitorTypeChecker(self.errorHandler)
        typeCheck.visitProgramNode(abstractSyntaxTree.root)

        if self.errorHandler.errorCount() == 0:
            pFilename = os.path.splitext(filename)[0] + ".p"
            codeGenerator = VisitorCodeGenerator(symbolTable, pFilename)
            codeGenerator.visitProgramNode(abstractSyntaxTree.root)

    def generateErrorsAndCompare(self, filename):
        self.parseFile(filename + ".c")
        self.assertTrue(self.errorHandler.errorCount() or self.errorHandler.warningCount())

        # if there is error output generated, compare with txt file
        try:
            with open(filename + ".txt", "r") as myfile:
                correctOutputOriginal = myfile.read()
        except:
            with open(filename + ".txt", "w") as myfile:
                correctOutputOriginal = ""

        errorMessage = self.errorHandler.errorsToString()
        errorMessageWithWhitespace = copy.copy(errorMessage)

        # remove all whitespace
        errorMessage  = re.sub("[ \t\n\r]", "", errorMessage)
        correctOutput = re.sub("[ \t\n\r]", "", correctOutputOriginal)

        # expectedOutputFound = errorMessage.find(correctOutput) != -1
        expectedOutputFound = errorMessage == correctOutput

        if setTxtFiles and not expectedOutputFound:
            f = open(filename + ".txt", "w")
            f.write(errorMessageWithWhitespace)
            f.close()

        if not expectedOutputFound:
            print("\nEXPECTED:\n" + correctOutputOriginal + "\nGOT:\n" + errorMessageWithWhitespace + "\n\n\n\n")

        self.assertTrue(expectedOutputFound)

    def generateNoError(self, filename):
        self.parseFile(filename + ".c")
        self.assertTrue(self.errorHandler.errorCount() == 0)

        # open the newly generated p code file
        try:
            with open(filename + ".p", "r") as myfile:
                pCodeGeneratedOriginal = myfile.read()
        except:
            with open(filename + ".p", "w") as myfile:
                pCodeGeneratedOriginal = ""

        # open the file with the correct p code
        try:
            with open(filename + ".p_correct", "r") as myfile:
                pCodeCorrectOriginal = myfile.read()
        except:
            with open(filename + ".p_correct", "w") as myfile:
                pCodeCorrectOriginal = ""

        # remove all whitespace
        pCodeGenerated  = re.sub("[ \t\n\r]", "", pCodeGeneratedOriginal)
        pCodeCorrect    = re.sub("[ \t\n\r]", "", pCodeCorrectOriginal)

        # expectedOutputFound = errorMessage.find(correctOutput) != -1
        expectedCodeFound = pCodeGenerated == pCodeCorrect

        if setPCode and not expectedCodeFound:
            f = open(filename + ".p_correct", "w")
            f.write(pCodeGeneratedOriginal)
            f.close()

        if not expectedCodeFound:
            print("\nEXPECTED:\n" + pCodeGeneratedOriginal + "\nGOT:\n" + pCodeCorrectOriginal + "\n\n\n\n")

        # os.system("gcc -std=c99 " + filename + ".c -w -o " + filename + ".testbin")

        self.assertTrue(expectedCodeFound)