コード例 #1
0
def parse_from_str(language_def, debug=False):
    """
    Constructs parser and initializes the model that is put into the parser.

    Args:
        language_def (str): The language in applang.

    Returns:
        The parser with the initialized model.
    """

    if debug:
        print("*** APPLANG PARSER ***")

    # First create parser for TextX descriptions
    parser = ParserPython(model, comment_def=comment, debug=debug)

    PMDOTExporter().exportFile(parser.parser_model,
                               "applang_parse_tree_model.dot")
    # Parse language description with textX parser
    parse_tree = parser.parse(language_def)

    #Invoice semantic analyze
    lang_parser = parser.getASG()

    if debug:
        # Create dot file for debuging purposes
        PTDOTExporter().exportFile(parse_tree, "applang_parse_tree.dot")

    return parser
コード例 #2
0
ファイル: test_exporter.py プロジェクト: moreati/Arpeggio
def test_export_parse_tree(parser):
    """
    Testing parse tree export.
    """

    parse_tree = parser.parse("-(4-1)*5+(2+4.67)+5.89/(.2+7)")
    PTDOTExporter().exportFile(parse_tree, "test_exporter_parse_tree.dot")

    assert os.path.exists("test_exporter_parse_tree.dot")
コード例 #3
0
def main(debug=False):

    #declare the arpeggio parser
    parser = ParserPython(program, comment, debug=debug)

    #command line argument is stored in smurfCode
    smurfCode = ""

    #if a command line argument was provided, check if it is a file. If it is, then it will parse, and interpret correctly
    if (len(sys.argv) > 1):
        smurfCode = sys.argv[1]
        try:
            file_object = open(smurfCode, "r")
            smurfCode = file_object.read()
            parsing_tree = parser.parse(smurfCode)
            #this is used if you want to make the png of the tree
            PTDOTExporter().exportFile(parsing_tree, "parse_tree.dot")

            #this will store the AST in result
            result = visit_parse_tree(parsing_tree, SmurfVisitor(debug=False))

            #interprets the AST
            result.eval()
        except:
            try:
                #this block of code will allow the command line arguement to be printed to the console
                smurfCode = smurfCode.replace(" ", "")
                if ("#" in smurfCode):
                    smurfCode = smurfCode[:smurfCode.find("#")]
                smurfCode = "print(" + smurfCode + ")"
                parsing_tree = parser.parse(smurfCode)
                #this is used if you want to make the png of the tree
                PTDOTExporter().exportFile(parsing_tree, "parse_tree.dot")

                #this will store the AST in result
                result = visit_parse_tree(parsing_tree,
                                          SmurfVisitor(debug=False))

                #interprets the AST
                result.eval()
            except:
                print("File does not exist or the smurf syntax was incorrect")
コード例 #4
0
def test_semantic_action_results() -> None:

    global first_sar, third_sar

    peg_input = "4 3 3 3 a 3 3 b"

    parser = ParserPython(grammar, reduce_tree=False)
    result = parser.parse(peg_input)

    PTDOTExporter().exportFile(result, 'test_semantic_action_results_pt.dot')

    visit_parse_tree(result, Visitor(defaults=True))

    assert isinstance(first_sar, SemanticActionResults)
    assert len(first_sar.third) == 3
    assert third_sar.third_str[0] == '3'  # type: ignore
コード例 #5
0
def doParsing(debug,
              interpreter_debug,
              showDotFile,
              UDO_FilePath,
              pathToGeneratePyFiles,
              customProjectName="",
              printMessages=True):
    """
    Function which reads the UDO file, does parsing and visits parse tree to properly create QW Modeller python script. 
    """
    if printMessages:
        print("UDO Interpreter\n\n")

    if UDO_FilePath:
        try:
            UDO_File = open(UDO_FilePath)

        except FileNotFoundError:
            if printMessages:
                print("Error -> Cannot find the file in given directory!\n\n")

        else:
            UDO_FileContent = UDO_File.read()

            projectName = customProjectName
            if not customProjectName:
                projectName = UDO_FilePath[UDO_FilePath.rfind("\\") +
                                           1:].split(".")[0]

            globalData = GlobalData(
                projectName=projectName,
                filePath=UDO_FilePath[:UDO_FilePath.rfind("\\") + 1],
                pathToGeneratePyFiles=
                pathToGeneratePyFiles[:pathToGeneratePyFiles.rfind("\\") + 1],
                printMessages=printMessages,
                udoFileContent=UDO_FileContent,
            )
            grammarRulesVistor = GrammarRulesVisitor(
                interpreter_debug=interpreter_debug, isNestedParsing=False)

            parser = ParserPython(program, debug=debug, reduce_tree=True)
            parse_tree = parser.parse(UDO_FileContent)

            if showDotFile:
                parseTreeVisualizationFileName = pathToGeneratePyFiles + globalData._singleton.projectName + "_ParseTreeVisualization.dot"
                PTDOTExporter().exportFile(parse_tree,
                                           parseTreeVisualizationFileName)
                s = Source.from_file(parseTreeVisualizationFileName)
                s.view()

            try:
                result = visit_parse_tree(parse_tree, grammarRulesVistor)

                if printMessages:
                    print("result = {result}\n\n".format(result=result))

                grammarRulesVistor.addLastLineToFilesIfRequired()
                if printMessages:
                    print(
                        "Parsing UDO file is completed!\nCheck .py generated files.\n\n"
                    )

            except NestedParsingFileNotFoundError as e:
                if printMessages:
                    print(
                        str(e) + "\n" +
                        ".py generated files contain errors!\n")

            globalData.closeAllModellerScripts()
            UDO_File.close()

            # For unit test purpose:
            del GlobalData._singleton
            GlobalData._singleton = None

    else:
        if printMessages:
            print("Error -> File Path is empty!\n\n")
コード例 #6
0
def doNestedParsing(nestedParameters,
                    UDO_FilePath,
                    debug=False,
                    interpreter_debug=False,
                    showDotFile=False,
                    printMessages=True):
    """
    Does nested parsing (when UDO command 'CALL' is executed). 
    """
    if printMessages:
        print("Nested UDO Interpreter -> {0}".format(UDO_FilePath))

    try:
        UDO_File = open(UDO_FilePath)

    except FileNotFoundError:
        raise NestedParsingFileNotFoundError(
            "Cannot find file for nested parsing in directory: " +
            UDO_FilePath + "!")

    else:
        UDO_FileContent = UDO_File.read()
        globalData = GlobalData()

        previousFileContent = globalData.udoFileContent
        globalData.udoFileContent = UDO_FileContent

        elementsInThisFileStorage = globalData.elementsInThisFile
        globalData.elementsInThisFile = {}

        variableStorage = globalData.variables
        globalData.variables = createStandardVariables()
        globalData.variables["x"] = ["", nestedParameters[-3]]
        globalData.variables["y"] = ["", nestedParameters[-2]]
        globalData.variables["z"] = ["", nestedParameters[-1]]

        grammarRulesVistor = GrammarRulesVisitor(
            interpreter_debug=interpreter_debug,
            isNestedParsing=True,
            nestedParameters=nestedParameters)

        parser = ParserPython(program, debug=debug, reduce_tree=True)
        parse_tree = parser.parse(UDO_FileContent)

        try:
            result = visit_parse_tree(parse_tree, grammarRulesVistor)
            if showDotFile:
                PTDOTExporter().exportFile(
                    parse_tree,
                    "UDO_InterpreterParseTree.dot")  # Nadpisuje pliki.dot !!!
                s = Source.from_file("UDO_InterpreterParseTree.dot")
                s.view()

            if printMessages:
                print("Nested parsing UDO file is completed!\n")

        except NestedParsingFileNotFoundError as e:
            raise NestedParsingFileNotFoundError(str(e))

        UDO_File.close()

        elementsInThisFileStorage.update(globalData.elementsInThisFile)
        globalData.elementsInThisFile = elementsInThisFileStorage
        globalData.udoFileContent = previousFileContent
        globalData.variables = variableStorage