Search in sources :

Example 11 with DMLProgram

use of org.apache.sysml.parser.DMLProgram in project incubator-systemml by apache.

the class DataTypeChangeTest method runValidateTest.

private void runValidateTest(String fullTestName, boolean expectedException) {
    boolean raisedException = false;
    try {
        // Tell the superclass about the name of this test, so that the superclass can
        // create temporary directories.
        TestConfiguration testConfig = new TestConfiguration(TEST_CLASS_DIR, fullTestName, new String[] {});
        addTestConfiguration(fullTestName, testConfig);
        loadTestConfiguration(testConfig);
        DMLConfig conf = new DMLConfig(getCurConfigFile().getPath());
        ConfigurationManager.setLocalConfig(conf);
        String dmlScriptString = "";
        HashMap<String, String> argVals = new HashMap<String, String>();
        // read script
        try (BufferedReader in = new BufferedReader(new FileReader(fullTestName))) {
            String s1 = null;
            while ((s1 = in.readLine()) != null) dmlScriptString += s1 + "\n";
        }
        // parsing and dependency analysis
        ParserWrapper parser = ParserFactory.createParser(org.apache.sysml.api.mlcontext.ScriptType.DML);
        DMLProgram prog = parser.parse(DMLScript.DML_FILE_PATH_ANTLR_PARSER, dmlScriptString, argVals);
        DMLTranslator dmlt = new DMLTranslator(prog);
        dmlt.liveVariableAnalysis(prog);
        dmlt.validateParseTree(prog);
    } catch (LanguageException ex) {
        raisedException = true;
        if (raisedException != expectedException)
            ex.printStackTrace();
    } catch (Exception ex2) {
        ex2.printStackTrace();
        throw new RuntimeException(ex2);
    // Assert.fail( "Unexpected exception occured during test run." );
    }
    // check correctness
    Assert.assertEquals(expectedException, raisedException);
}
Also used : DMLConfig(org.apache.sysml.conf.DMLConfig) HashMap(java.util.HashMap) TestConfiguration(org.apache.sysml.test.integration.TestConfiguration) DMLTranslator(org.apache.sysml.parser.DMLTranslator) DMLException(org.apache.sysml.api.DMLException) LanguageException(org.apache.sysml.parser.LanguageException) LanguageException(org.apache.sysml.parser.LanguageException) BufferedReader(java.io.BufferedReader) DMLProgram(org.apache.sysml.parser.DMLProgram) FileReader(java.io.FileReader) ParserWrapper(org.apache.sysml.parser.ParserWrapper)

Example 12 with DMLProgram

use of org.apache.sysml.parser.DMLProgram in project incubator-systemml by apache.

the class DMLParserWrapper method doParse.

/**
 * This function is supposed to be called directly only from DmlSyntacticValidator when it encounters 'import'
 * @param fileName script file name
 * @param dmlScript script file contents
 * @param sourceNamespace namespace from source statement
 * @param argVals script arguments
 * @return dml program, or null if at least one error
 */
public DMLProgram doParse(String fileName, String dmlScript, String sourceNamespace, Map<String, String> argVals) {
    DMLProgram dmlPgm = null;
    ANTLRInputStream in;
    try {
        if (dmlScript == null) {
            dmlScript = readDMLScript(fileName, LOG);
        }
        InputStream stream = new ByteArrayInputStream(dmlScript.getBytes());
        in = new ANTLRInputStream(stream);
    } catch (FileNotFoundException e) {
        throw new ParseException("Cannot find file/resource: " + fileName, e);
    } catch (IOException e) {
        throw new ParseException("Cannot open file: " + fileName, e);
    } catch (LanguageException e) {
        throw new ParseException(e.getMessage(), e);
    }
    ProgramrootContext ast = null;
    CustomErrorListener errorListener = new CustomErrorListener();
    try {
        DmlLexer lexer = new DmlLexer(in);
        CommonTokenStream tokens = new CommonTokenStream(lexer);
        DmlParser antlr4Parser = new DmlParser(tokens);
        // For now no optimization, since it is not able to parse integer value.
        boolean tryOptimizedParsing = false;
        if (tryOptimizedParsing) {
            // Try faster and simpler SLL
            antlr4Parser.getInterpreter().setPredictionMode(PredictionMode.SLL);
            antlr4Parser.removeErrorListeners();
            antlr4Parser.setErrorHandler(new BailErrorStrategy());
            try {
                ast = antlr4Parser.programroot();
            // If successful, no need to try out full LL(*) ... SLL was enough
            } catch (ParseCancellationException ex) {
                // Error occurred, so now try full LL(*) for better error messages
                tokens.reset();
                antlr4Parser.reset();
                if (fileName != null) {
                    errorListener.setCurrentFileName(fileName);
                } else {
                    errorListener.setCurrentFileName("MAIN_SCRIPT");
                }
                // Set our custom error listener
                antlr4Parser.addErrorListener(errorListener);
                antlr4Parser.setErrorHandler(new DefaultErrorStrategy());
                antlr4Parser.getInterpreter().setPredictionMode(PredictionMode.LL);
                ast = antlr4Parser.programroot();
            }
        } else {
            // Set our custom error listener
            antlr4Parser.removeErrorListeners();
            antlr4Parser.addErrorListener(errorListener);
            errorListener.setCurrentFileName(fileName);
            // Now do the parsing
            ast = antlr4Parser.programroot();
        }
    } catch (Exception e) {
        throw new ParseException("ERROR: Cannot parse the program:" + fileName, e);
    }
    // Now convert the parse tree into DMLProgram
    // Do syntactic validation while converting
    ParseTree tree = ast;
    // And also do syntactic validation
    ParseTreeWalker walker = new ParseTreeWalker();
    // Get list of function definitions which take precedence over built-in functions if same name
    DmlPreprocessor prep = new DmlPreprocessor(errorListener);
    walker.walk(prep, tree);
    // Syntactic validation
    DmlSyntacticValidator validator = new DmlSyntacticValidator(errorListener, argVals, sourceNamespace, prep.getFunctionDefs());
    walker.walk(validator, tree);
    errorListener.unsetCurrentFileName();
    this.parseIssues = errorListener.getParseIssues();
    this.atLeastOneWarning = errorListener.isAtLeastOneWarning();
    this.atLeastOneError = errorListener.isAtLeastOneError();
    if (atLeastOneError) {
        throw new ParseException(parseIssues, dmlScript);
    }
    if (atLeastOneWarning) {
        LOG.warn(CustomErrorListener.generateParseIssuesMessage(dmlScript, parseIssues));
    }
    dmlPgm = createDMLProgram(ast, sourceNamespace);
    return dmlPgm;
}
Also used : CommonTokenStream(org.antlr.v4.runtime.CommonTokenStream) CustomErrorListener(org.apache.sysml.parser.common.CustomErrorListener) ByteArrayInputStream(java.io.ByteArrayInputStream) ANTLRInputStream(org.antlr.v4.runtime.ANTLRInputStream) InputStream(java.io.InputStream) BailErrorStrategy(org.antlr.v4.runtime.BailErrorStrategy) FileNotFoundException(java.io.FileNotFoundException) ProgramrootContext(org.apache.sysml.parser.dml.DmlParser.ProgramrootContext) IOException(java.io.IOException) ParseCancellationException(org.antlr.v4.runtime.misc.ParseCancellationException) LanguageException(org.apache.sysml.parser.LanguageException) IOException(java.io.IOException) FileNotFoundException(java.io.FileNotFoundException) ParseException(org.apache.sysml.parser.ParseException) LanguageException(org.apache.sysml.parser.LanguageException) ByteArrayInputStream(java.io.ByteArrayInputStream) ParseCancellationException(org.antlr.v4.runtime.misc.ParseCancellationException) DefaultErrorStrategy(org.antlr.v4.runtime.DefaultErrorStrategy) DMLProgram(org.apache.sysml.parser.DMLProgram) ParseException(org.apache.sysml.parser.ParseException) ANTLRInputStream(org.antlr.v4.runtime.ANTLRInputStream) ParseTree(org.antlr.v4.runtime.tree.ParseTree) ParseTreeWalker(org.antlr.v4.runtime.tree.ParseTreeWalker)

Example 13 with DMLProgram

use of org.apache.sysml.parser.DMLProgram in project incubator-systemml by apache.

the class DmlSyntacticValidator method exitImportStatement.

// -----------------------------------------------------------------
// "src" statment
// -----------------------------------------------------------------
@Override
public void exitImportStatement(ImportStatementContext ctx) {
    // prepare import filepath
    String filePath = ctx.filePath.getText();
    String namespace = DMLProgram.DEFAULT_NAMESPACE;
    if (ctx.namespace != null && ctx.namespace.getText() != null && !ctx.namespace.getText().isEmpty()) {
        namespace = ctx.namespace.getText();
    }
    if ((filePath.startsWith("\"") && filePath.endsWith("\"")) || filePath.startsWith("'") && filePath.endsWith("'")) {
        filePath = filePath.substring(1, filePath.length() - 1);
    }
    File file = new File(filePath);
    if (!file.isAbsolute()) {
        // concatenate working directory to filepath
        filePath = _workingDir + File.separator + filePath;
    }
    validateNamespace(namespace, filePath, ctx);
    String scriptID = DMLProgram.constructFunctionKey(namespace, filePath);
    DMLProgram prog = null;
    if (!_scripts.get().containsKey(scriptID)) {
        _scripts.get().put(scriptID, namespace);
        try {
            prog = (new DMLParserWrapper()).doParse(filePath, null, getQualifiedNamespace(namespace), argVals);
        } catch (ParseException e) {
            notifyErrorListeners(e.getMessage(), ctx.start);
            return;
        }
        // Custom logic whether to proceed ahead or not. Better than the current exception handling mechanism
        if (prog == null) {
            notifyErrorListeners("One or more errors found during importing a program from file " + filePath, ctx.start);
            return;
        } else {
            ctx.info.namespaces = new HashMap<>();
            ctx.info.namespaces.put(getQualifiedNamespace(namespace), prog);
            ctx.info.stmt = new ImportStatement();
            ((ImportStatement) ctx.info.stmt).setCompletePath(filePath);
            ((ImportStatement) ctx.info.stmt).setFilePath(ctx.filePath.getText());
            ((ImportStatement) ctx.info.stmt).setNamespace(namespace);
        }
    } else {
        // Skip redundant parsing (to prevent potential infinite recursion) and
        // create empty program for this context to allow processing to continue.
        prog = new DMLProgram();
        ctx.info.namespaces = new HashMap<>();
        ctx.info.namespaces.put(getQualifiedNamespace(namespace), prog);
        ctx.info.stmt = new ImportStatement();
        ((ImportStatement) ctx.info.stmt).setCompletePath(filePath);
        ((ImportStatement) ctx.info.stmt).setFilePath(ctx.filePath.getText());
        ((ImportStatement) ctx.info.stmt).setNamespace(namespace);
    }
}
Also used : DMLProgram(org.apache.sysml.parser.DMLProgram) ParseException(org.apache.sysml.parser.ParseException) ImportStatement(org.apache.sysml.parser.ImportStatement) File(java.io.File)

Example 14 with DMLProgram

use of org.apache.sysml.parser.DMLProgram in project incubator-systemml by apache.

the class OptTreePlanChecker method checkProgramCorrectness.

public static void checkProgramCorrectness(ProgramBlock pb, StatementBlock sb, Set<String> fnStack) {
    Program prog = pb.getProgram();
    DMLProgram dprog = sb.getDMLProg();
    if (pb instanceof FunctionProgramBlock && sb instanceof FunctionStatementBlock) {
        FunctionProgramBlock fpb = (FunctionProgramBlock) pb;
        FunctionStatementBlock fsb = (FunctionStatementBlock) sb;
        FunctionStatement fstmt = (FunctionStatement) fsb.getStatement(0);
        for (int i = 0; i < fpb.getChildBlocks().size(); i++) {
            ProgramBlock pbc = fpb.getChildBlocks().get(i);
            StatementBlock sbc = fstmt.getBody().get(i);
            checkProgramCorrectness(pbc, sbc, fnStack);
        }
    // checkLinksProgramStatementBlock(fpb, fsb);
    } else if (pb instanceof WhileProgramBlock && sb instanceof WhileStatementBlock) {
        WhileProgramBlock wpb = (WhileProgramBlock) pb;
        WhileStatementBlock wsb = (WhileStatementBlock) sb;
        WhileStatement wstmt = (WhileStatement) wsb.getStatement(0);
        checkHopDagCorrectness(prog, dprog, wsb.getPredicateHops(), wpb.getPredicate(), fnStack);
        for (int i = 0; i < wpb.getChildBlocks().size(); i++) {
            ProgramBlock pbc = wpb.getChildBlocks().get(i);
            StatementBlock sbc = wstmt.getBody().get(i);
            checkProgramCorrectness(pbc, sbc, fnStack);
        }
        checkLinksProgramStatementBlock(wpb, wsb);
    } else if (pb instanceof IfProgramBlock && sb instanceof IfStatementBlock) {
        IfProgramBlock ipb = (IfProgramBlock) pb;
        IfStatementBlock isb = (IfStatementBlock) sb;
        IfStatement istmt = (IfStatement) isb.getStatement(0);
        checkHopDagCorrectness(prog, dprog, isb.getPredicateHops(), ipb.getPredicate(), fnStack);
        for (int i = 0; i < ipb.getChildBlocksIfBody().size(); i++) {
            ProgramBlock pbc = ipb.getChildBlocksIfBody().get(i);
            StatementBlock sbc = istmt.getIfBody().get(i);
            checkProgramCorrectness(pbc, sbc, fnStack);
        }
        for (int i = 0; i < ipb.getChildBlocksElseBody().size(); i++) {
            ProgramBlock pbc = ipb.getChildBlocksElseBody().get(i);
            StatementBlock sbc = istmt.getElseBody().get(i);
            checkProgramCorrectness(pbc, sbc, fnStack);
        }
        checkLinksProgramStatementBlock(ipb, isb);
    } else if (// incl parfor
    pb instanceof ForProgramBlock && sb instanceof ForStatementBlock) {
        ForProgramBlock fpb = (ForProgramBlock) pb;
        ForStatementBlock fsb = (ForStatementBlock) sb;
        ForStatement fstmt = (ForStatement) sb.getStatement(0);
        checkHopDagCorrectness(prog, dprog, fsb.getFromHops(), fpb.getFromInstructions(), fnStack);
        checkHopDagCorrectness(prog, dprog, fsb.getToHops(), fpb.getToInstructions(), fnStack);
        checkHopDagCorrectness(prog, dprog, fsb.getIncrementHops(), fpb.getIncrementInstructions(), fnStack);
        for (int i = 0; i < fpb.getChildBlocks().size(); i++) {
            ProgramBlock pbc = fpb.getChildBlocks().get(i);
            StatementBlock sbc = fstmt.getBody().get(i);
            checkProgramCorrectness(pbc, sbc, fnStack);
        }
        checkLinksProgramStatementBlock(fpb, fsb);
    } else {
        checkHopDagCorrectness(prog, dprog, sb.getHops(), pb.getInstructions(), fnStack);
    // checkLinksProgramStatementBlock(pb, sb);
    }
}
Also used : FunctionProgramBlock(org.apache.sysml.runtime.controlprogram.FunctionProgramBlock) IfProgramBlock(org.apache.sysml.runtime.controlprogram.IfProgramBlock) ForStatementBlock(org.apache.sysml.parser.ForStatementBlock) FunctionStatementBlock(org.apache.sysml.parser.FunctionStatementBlock) DMLProgram(org.apache.sysml.parser.DMLProgram) Program(org.apache.sysml.runtime.controlprogram.Program) ForProgramBlock(org.apache.sysml.runtime.controlprogram.ForProgramBlock) WhileProgramBlock(org.apache.sysml.runtime.controlprogram.WhileProgramBlock) WhileStatement(org.apache.sysml.parser.WhileStatement) FunctionStatement(org.apache.sysml.parser.FunctionStatement) IfStatement(org.apache.sysml.parser.IfStatement) DMLProgram(org.apache.sysml.parser.DMLProgram) ForProgramBlock(org.apache.sysml.runtime.controlprogram.ForProgramBlock) IfProgramBlock(org.apache.sysml.runtime.controlprogram.IfProgramBlock) FunctionProgramBlock(org.apache.sysml.runtime.controlprogram.FunctionProgramBlock) ProgramBlock(org.apache.sysml.runtime.controlprogram.ProgramBlock) WhileProgramBlock(org.apache.sysml.runtime.controlprogram.WhileProgramBlock) ForStatement(org.apache.sysml.parser.ForStatement) FunctionStatementBlock(org.apache.sysml.parser.FunctionStatementBlock) IfStatementBlock(org.apache.sysml.parser.IfStatementBlock) WhileStatementBlock(org.apache.sysml.parser.WhileStatementBlock) ForStatementBlock(org.apache.sysml.parser.ForStatementBlock) StatementBlock(org.apache.sysml.parser.StatementBlock) WhileStatementBlock(org.apache.sysml.parser.WhileStatementBlock) IfStatementBlock(org.apache.sysml.parser.IfStatementBlock)

Example 15 with DMLProgram

use of org.apache.sysml.parser.DMLProgram in project incubator-systemml by apache.

the class OptimizerRuleBased method rFindAndUnfoldRecursiveFunction.

protected void rFindAndUnfoldRecursiveFunction(OptNode n, ParForProgramBlock parfor, HashSet<ParForProgramBlock> recPBs, LocalVariableMap vars) {
    // unfold if found
    if (n.getNodeType() == NodeType.FUNCCALL && n.isRecursive()) {
        boolean exists = rContainsNode(n, parfor);
        if (exists) {
            String fnameKey = n.getParam(ParamType.OPSTRING);
            String[] names = fnameKey.split(Program.KEY_DELIM);
            String fnamespace = names[0];
            String fname = names[1];
            String fnameNew = FUNCTION_UNFOLD_NAMEPREFIX + fname;
            // unfold function
            FunctionOp fop = (FunctionOp) OptTreeConverter.getAbstractPlanMapping().getMappedHop(n.getID());
            Program prog = parfor.getProgram();
            DMLProgram dmlprog = parfor.getStatementBlock().getDMLProg();
            FunctionProgramBlock fpb = prog.getFunctionProgramBlock(fnamespace, fname);
            FunctionProgramBlock copyfpb = ProgramConverter.createDeepCopyFunctionProgramBlock(fpb, new HashSet<String>(), new HashSet<String>());
            prog.addFunctionProgramBlock(fnamespace, fnameNew, copyfpb);
            dmlprog.addFunctionStatementBlock(fnamespace, fnameNew, (FunctionStatementBlock) copyfpb.getStatementBlock());
            // replace function names in old subtree (link to new function)
            rReplaceFunctionNames(n, fname, fnameNew);
            // recreate sub opttree
            String fnameNewKey = fnamespace + Program.KEY_DELIM + fnameNew;
            OptNode nNew = new OptNode(NodeType.FUNCCALL);
            OptTreeConverter.getAbstractPlanMapping().putHopMapping(fop, nNew);
            nNew.setExecType(ExecType.CP);
            nNew.addParam(ParamType.OPSTRING, fnameNewKey);
            long parentID = OptTreeConverter.getAbstractPlanMapping().getMappedParentID(n.getID());
            OptTreeConverter.getAbstractPlanMapping().getOptNode(parentID).exchangeChild(n, nNew);
            HashSet<String> memo = new HashSet<>();
            // required if functionop not shared (because not replaced yet)
            memo.add(fnameKey);
            // requied if functionop shared (indirectly replaced)
            memo.add(fnameNewKey);
            for (int i = 0; i < copyfpb.getChildBlocks().size(); /*&& i<len*/
            i++) {
                ProgramBlock lpb = copyfpb.getChildBlocks().get(i);
                StatementBlock lsb = lpb.getStatementBlock();
                nNew.addChild(OptTreeConverter.rCreateAbstractOptNode(lsb, lpb, vars, false, memo));
            }
            // compute delta for recPB set (use for removing parfor)
            recPBs.removeAll(rGetAllParForPBs(n, new HashSet<ParForProgramBlock>()));
            recPBs.addAll(rGetAllParForPBs(nNew, new HashSet<ParForProgramBlock>()));
            // replace function names in new subtree (recursive link to new function)
            rReplaceFunctionNames(nNew, fname, fnameNew);
        }
        return;
    }
    // recursive invocation (only for non-recursive functions)
    if (!n.isLeaf())
        for (OptNode c : n.getChilds()) rFindAndUnfoldRecursiveFunction(c, parfor, recPBs, vars);
}
Also used : FunctionProgramBlock(org.apache.sysml.runtime.controlprogram.FunctionProgramBlock) DMLProgram(org.apache.sysml.parser.DMLProgram) Program(org.apache.sysml.runtime.controlprogram.Program) FunctionOp(org.apache.sysml.hops.FunctionOp) DMLProgram(org.apache.sysml.parser.DMLProgram) FunctionProgramBlock(org.apache.sysml.runtime.controlprogram.FunctionProgramBlock) ForProgramBlock(org.apache.sysml.runtime.controlprogram.ForProgramBlock) ProgramBlock(org.apache.sysml.runtime.controlprogram.ProgramBlock) ParForProgramBlock(org.apache.sysml.runtime.controlprogram.ParForProgramBlock) FunctionStatementBlock(org.apache.sysml.parser.FunctionStatementBlock) ParForStatementBlock(org.apache.sysml.parser.ParForStatementBlock) StatementBlock(org.apache.sysml.parser.StatementBlock) HashSet(java.util.HashSet)

Aggregations

DMLProgram (org.apache.sysml.parser.DMLProgram)19 LanguageException (org.apache.sysml.parser.LanguageException)8 FunctionStatementBlock (org.apache.sysml.parser.FunctionStatementBlock)7 DMLConfig (org.apache.sysml.conf.DMLConfig)5 DMLTranslator (org.apache.sysml.parser.DMLTranslator)5 ParseException (org.apache.sysml.parser.ParseException)5 ParserWrapper (org.apache.sysml.parser.ParserWrapper)5 FunctionStatement (org.apache.sysml.parser.FunctionStatement)4 ImportStatement (org.apache.sysml.parser.ImportStatement)4 StatementBlock (org.apache.sysml.parser.StatementBlock)4 ForProgramBlock (org.apache.sysml.runtime.controlprogram.ForProgramBlock)4 FunctionProgramBlock (org.apache.sysml.runtime.controlprogram.FunctionProgramBlock)4 ProgramBlock (org.apache.sysml.runtime.controlprogram.ProgramBlock)4 BufferedReader (java.io.BufferedReader)3 FileReader (java.io.FileReader)3 IOException (java.io.IOException)3 InputStream (java.io.InputStream)3 ArrayList (java.util.ArrayList)3 HashMap (java.util.HashMap)3 HashSet (java.util.HashSet)3