Search in sources :

Example 16 with RecognitionException

use of org.antlr.v4.runtime.RecognitionException in project compiler by boalang.

the class BoaCompiler method main.

public static void main(final String[] args) throws IOException {
    CommandLine cl = processCommandLineOptions(args);
    if (cl == null)
        return;
    final ArrayList<File> inputFiles = BoaCompiler.inputFiles;
    // get the name of the generated class
    final String className = getGeneratedClass(cl);
    // get the filename of the jar we will be writing
    final String jarName;
    if (cl.hasOption('o'))
        jarName = cl.getOptionValue('o');
    else
        jarName = className + ".jar";
    // make the output directory
    File outputRoot = null;
    if (cl.hasOption("cd")) {
        outputRoot = new File(cl.getOptionValue("cd"));
    } else {
        outputRoot = new File(new File(System.getProperty("java.io.tmpdir")), UUID.randomUUID().toString());
    }
    final File outputSrcDir = new File(outputRoot, "boa");
    if (!outputSrcDir.mkdirs())
        throw new IOException("unable to mkdir " + outputSrcDir);
    // find custom libs to load
    final List<URL> libs = new ArrayList<URL>();
    if (cl.hasOption('l'))
        for (final String lib : cl.getOptionValues('l')) libs.add(new File(lib).toURI().toURL());
    final File outputFile = new File(outputSrcDir, className + ".java");
    final BufferedOutputStream o = new BufferedOutputStream(new FileOutputStream(outputFile));
    try {
        final List<String> jobnames = new ArrayList<String>();
        final List<String> jobs = new ArrayList<String>();
        final List<Integer> seeds = new ArrayList<Integer>();
        boolean isSimple = true;
        final List<Program> visitorPrograms = new ArrayList<Program>();
        SymbolTable.initialize(libs);
        final int maxVisitors;
        if (cl.hasOption('v'))
            maxVisitors = Integer.parseInt(cl.getOptionValue('v'));
        else
            maxVisitors = Integer.MAX_VALUE;
        for (int i = 0; i < inputFiles.size(); i++) {
            final File f = inputFiles.get(i);
            try {
                final BoaLexer lexer = new BoaLexer(new ANTLRFileStream(f.getAbsolutePath()));
                // use the whole input string to seed the RNG
                seeds.add(lexer._input.getText(new Interval(0, lexer._input.size())).hashCode());
                lexer.removeErrorListeners();
                lexer.addErrorListener(new LexerErrorListener());
                final CommonTokenStream tokens = new CommonTokenStream(lexer);
                final BoaParser parser = new BoaParser(tokens);
                parser.removeErrorListeners();
                parser.addErrorListener(new BaseErrorListener() {

                    @Override
                    public void syntaxError(Recognizer<?, ?> recognizer, Object offendingSymbol, int line, int charPositionInLine, String msg, RecognitionException e) throws ParseCancellationException {
                        throw new ParseCancellationException(e);
                    }
                });
                final BoaErrorListener parserErrorListener = new ParserErrorListener();
                final Start p = parse(tokens, parser, parserErrorListener);
                if (cl.hasOption("ast"))
                    new ASTPrintingVisitor().start(p);
                final String jobName = "" + i;
                try {
                    if (!parserErrorListener.hasError) {
                        new TypeCheckingVisitor().start(p, new SymbolTable());
                        final TaskClassifyingVisitor simpleVisitor = new TaskClassifyingVisitor();
                        simpleVisitor.start(p);
                        LOG.info(f.getName() + ": task complexity: " + (!simpleVisitor.isComplex() ? "simple" : "complex"));
                        isSimple &= !simpleVisitor.isComplex();
                        new InheritedAttributeTransformer().start(p);
                        new LocalAggregationTransformer().start(p);
                        // also let jobs have own methods if visitor merging is disabled
                        if (!simpleVisitor.isComplex() || maxVisitors < 2 || inputFiles.size() == 1) {
                            new VisitorOptimizingTransformer().start(p);
                            if (cl.hasOption("pp"))
                                new PrettyPrintVisitor().start(p);
                            if (cl.hasOption("ast2"))
                                new ASTPrintingVisitor().start(p);
                            final CodeGeneratingVisitor cg = new CodeGeneratingVisitor(jobName);
                            cg.start(p);
                            jobs.add(cg.getCode());
                            jobnames.add(jobName);
                        } else // if a job has visitors, fuse them all together into a single program
                        {
                            p.getProgram().jobName = jobName;
                            visitorPrograms.add(p.getProgram());
                        }
                    }
                } catch (final TypeCheckException e) {
                    parserErrorListener.error("typecheck", lexer, null, e.n.beginLine, e.n.beginColumn, e.n2.endColumn - e.n.beginColumn + 1, e.getMessage(), e);
                }
            } catch (final Exception e) {
                System.err.print(f.getName() + ": compilation failed: ");
                e.printStackTrace();
            }
        }
        if (!visitorPrograms.isEmpty())
            try {
                for (final Program p : new VisitorMergingTransformer().mergePrograms(visitorPrograms, maxVisitors)) {
                    new VisitorOptimizingTransformer().start(p);
                    if (cl.hasOption("pp"))
                        new PrettyPrintVisitor().start(p);
                    if (cl.hasOption("ast2"))
                        new ASTPrintingVisitor().start(p);
                    final CodeGeneratingVisitor cg = new CodeGeneratingVisitor(p.jobName);
                    cg.start(p);
                    jobs.add(cg.getCode());
                    jobnames.add(p.jobName);
                }
            } catch (final Exception e) {
                System.err.println("error fusing visitors - falling back: " + e);
                e.printStackTrace();
                for (final Program p : visitorPrograms) {
                    new VisitorOptimizingTransformer().start(p);
                    if (cl.hasOption("pp"))
                        new PrettyPrintVisitor().start(p);
                    if (cl.hasOption("ast2"))
                        new ASTPrintingVisitor().start(p);
                    final CodeGeneratingVisitor cg = new CodeGeneratingVisitor(p.jobName);
                    cg.start(p);
                    jobs.add(cg.getCode());
                    jobnames.add(p.jobName);
                }
            }
        if (jobs.size() == 0)
            throw new RuntimeException("no files compiled without error");
        final ST st = AbstractCodeGeneratingVisitor.stg.getInstanceOf("Program");
        st.add("name", className);
        st.add("numreducers", inputFiles.size());
        st.add("jobs", jobs);
        st.add("jobnames", jobnames);
        st.add("combineTables", CodeGeneratingVisitor.combineAggregatorStrings);
        st.add("reduceTables", CodeGeneratingVisitor.reduceAggregatorStrings);
        st.add("splitsize", isSimple ? 64 * 1024 * 1024 : 10 * 1024 * 1024);
        st.add("seeds", seeds);
        if (DefaultProperties.localDataPath != null) {
            st.add("isLocal", true);
        }
        o.write(st.render().getBytes());
    } finally {
        o.close();
    }
    compileGeneratedSrc(cl, jarName, outputRoot, outputFile);
}
Also used : BoaParser(boa.parser.BoaParser) Start(boa.compiler.ast.Start) ArrayList(java.util.ArrayList) URL(java.net.URL) VisitorOptimizingTransformer(boa.compiler.transforms.VisitorOptimizingTransformer) BoaErrorListener(boa.compiler.listeners.BoaErrorListener) TypeCheckingVisitor(boa.compiler.visitors.TypeCheckingVisitor) BufferedOutputStream(java.io.BufferedOutputStream) BoaLexer(boa.parser.BoaLexer) PrettyPrintVisitor(boa.compiler.visitors.PrettyPrintVisitor) CommonTokenStream(org.antlr.v4.runtime.CommonTokenStream) ST(org.stringtemplate.v4.ST) Program(boa.compiler.ast.Program) LexerErrorListener(boa.compiler.listeners.LexerErrorListener) BaseErrorListener(org.antlr.v4.runtime.BaseErrorListener) InheritedAttributeTransformer(boa.compiler.transforms.InheritedAttributeTransformer) VisitorMergingTransformer(boa.compiler.transforms.VisitorMergingTransformer) LocalAggregationTransformer(boa.compiler.transforms.LocalAggregationTransformer) IOException(java.io.IOException) TaskClassifyingVisitor(boa.compiler.visitors.TaskClassifyingVisitor) FileNotFoundException(java.io.FileNotFoundException) ParseCancellationException(org.antlr.v4.runtime.misc.ParseCancellationException) IOException(java.io.IOException) RecognitionException(org.antlr.v4.runtime.RecognitionException) ParserErrorListener(boa.compiler.listeners.ParserErrorListener) CommandLine(org.apache.commons.cli.CommandLine) ANTLRFileStream(org.antlr.v4.runtime.ANTLRFileStream) ParseCancellationException(org.antlr.v4.runtime.misc.ParseCancellationException) FileOutputStream(java.io.FileOutputStream) AbstractCodeGeneratingVisitor(boa.compiler.visitors.AbstractCodeGeneratingVisitor) CodeGeneratingVisitor(boa.compiler.visitors.CodeGeneratingVisitor) ASTPrintingVisitor(boa.compiler.visitors.ASTPrintingVisitor) File(java.io.File) RecognitionException(org.antlr.v4.runtime.RecognitionException) Interval(org.antlr.v4.runtime.misc.Interval)

Example 17 with RecognitionException

use of org.antlr.v4.runtime.RecognitionException in project compiler by boalang.

the class BaseTest method lex.

protected CommonTokenStream lex(final String input, final int[] ids, final String[] strings, final String[] errors) throws IOException {
    final List<String> foundErr = new ArrayList<String>();
    final BoaLexer lexer = new BoaLexer(new ANTLRInputStream(new StringReader(input)));
    lexer.removeErrorListeners();
    lexer.addErrorListener(new BaseErrorListener() {

        @Override
        public void syntaxError(final Recognizer<?, ?> recognizer, final Object offendingSymbol, final int line, final int charPositionInLine, final String msg, final RecognitionException e) {
            foundErr.add(line + "," + charPositionInLine + ": " + msg);
        }
    });
    final CommonTokenStream tokens = new CommonTokenStream(lexer);
    tokens.fill();
    if (ids.length > 0 && strings.length > 0)
        assertEquals("ids != strings", ids.length, strings.length);
    if (ids.length > 0) {
        final List<Token> t = tokens.getTokens();
        if (DEBUG) {
            for (int i = 0; i < t.size(); i++) {
                final Token token = t.get(i);
                System.out.print(token.getType() + ", ");
            }
            System.out.println();
            for (int i = 0; i < t.size(); i++) {
                final Token token = t.get(i);
                System.out.print(token.getText() + ", ");
            }
            System.out.println();
            System.out.println();
        }
        assertEquals("wrong number of tokens", ids.length, t.size());
        for (int i = 0; i < t.size(); i++) assertEquals("wrong token type", ids[i], t.get(i).getType());
    }
    if (strings.length > 0) {
        final List<Token> t = tokens.getTokens();
        assertEquals("wrong number of tokens", strings.length, t.size());
        for (int i = 0; i < t.size(); i++) assertEquals("wrong token type", strings[i], t.get(i).getText());
    }
    assertEquals("wrong number of errors: " + input, errors.length, foundErr.size());
    for (int i = 0; i < foundErr.size(); i++) assertEquals("wrong error", errors[i], foundErr.get(i));
    return tokens;
}
Also used : CommonTokenStream(org.antlr.v4.runtime.CommonTokenStream) BaseErrorListener(org.antlr.v4.runtime.BaseErrorListener) ArrayList(java.util.ArrayList) Token(org.antlr.v4.runtime.Token) StringReader(java.io.StringReader) JavaFileObject(javax.tools.JavaFileObject) BoaLexer(boa.parser.BoaLexer) ANTLRInputStream(org.antlr.v4.runtime.ANTLRInputStream) RecognitionException(org.antlr.v4.runtime.RecognitionException)

Example 18 with RecognitionException

use of org.antlr.v4.runtime.RecognitionException in project compiler by boalang.

the class BaseTest method parse.

protected StartContext parse(final String input, final String[] errors) throws IOException {
    final CommonTokenStream tokens = lex(input);
    final BoaParser parser = new BoaParser(tokens);
    final List<String> foundErr = new ArrayList<String>();
    parser.removeErrorListeners();
    parser.addErrorListener(new BaseErrorListener() {

        @Override
        public void syntaxError(Recognizer<?, ?> recognizer, Object offendingSymbol, int line, int charPositionInLine, String msg, RecognitionException e) throws ParseCancellationException {
            throw new ParseCancellationException(e);
        }
    });
    parser.setBuildParseTree(false);
    parser.getInterpreter().setPredictionMode(PredictionMode.SLL);
    StartContext p;
    try {
        p = parser.start();
    } catch (final Exception e) {
        // fall-back to LL mode parsing if SLL fails
        tokens.reset();
        parser.reset();
        parser.removeErrorListeners();
        parser.addErrorListener(new BaseErrorListener() {

            @Override
            public void syntaxError(final Recognizer<?, ?> recognizer, final Object offendingSymbol, final int line, final int charPositionInLine, final String msg, final RecognitionException e) {
                foundErr.add(line + "," + charPositionInLine + ": " + msg);
            }
        });
        parser.getInterpreter().setPredictionMode(PredictionMode.LL);
        p = parser.start();
    }
    if (!DEBUG)
        assertEquals("wrong number of errors", errors.length, foundErr.size());
    for (int i = 0; i < foundErr.size(); i++) {
        if (DEBUG)
            System.out.println(foundErr.get(i));
        else
            assertEquals("wrong error", errors[i], foundErr.get(i));
    }
    return p;
}
Also used : BoaParser(boa.parser.BoaParser) CommonTokenStream(org.antlr.v4.runtime.CommonTokenStream) BaseErrorListener(org.antlr.v4.runtime.BaseErrorListener) ArrayList(java.util.ArrayList) ParseCancellationException(org.antlr.v4.runtime.misc.ParseCancellationException) IOException(java.io.IOException) RecognitionException(org.antlr.v4.runtime.RecognitionException) StartContext(boa.parser.BoaParser.StartContext) Recognizer(org.antlr.v4.runtime.Recognizer) ParseCancellationException(org.antlr.v4.runtime.misc.ParseCancellationException) JavaFileObject(javax.tools.JavaFileObject) RecognitionException(org.antlr.v4.runtime.RecognitionException)

Example 19 with RecognitionException

use of org.antlr.v4.runtime.RecognitionException in project nikita-noark5-core by HiOA-ABI.

the class TestODataApp method main.

public static void main(String[] args) throws Exception {
    System.out.println("Starting OData parser test");
    System.out.println("Picks first line from odata_samples.txt in " + "resources folder.");
    try {
        AfterApplicationStartup afterApplicationStartup = new AfterApplicationStartup(null);
        afterApplicationStartup.populateTranslatedNames();
        TestODataApp app = new TestODataApp();
        ODataLexer lexer = new ODataLexer(CharStreams.fromStream(app.getInputStreamForParseFile("odata" + File.separator + "odata_samples.txt")));
        CommonTokenStream tokens = new CommonTokenStream(lexer);
        ODataParser parser = new ODataParser(tokens);
        ParseTree tree = parser.odataURL();
        ParseTreeWalker walker = new ParseTreeWalker();
        // Make the SQL Statement
        NikitaODataToSQLWalker sqlWalker = new NikitaODataToSQLWalker();
        walker.walk(sqlWalker, tree);
        System.out.println(sqlWalker.getSqlStatement());
    } catch (RecognitionException e) {
        throw new IllegalStateException("Recognition exception");
    }
}
Also used : ODataParser(nikita.webapp.odata.ODataParser) CommonTokenStream(org.antlr.v4.runtime.CommonTokenStream) ODataLexer(nikita.webapp.odata.ODataLexer) ParseTree(org.antlr.v4.runtime.tree.ParseTree) ParseTreeWalker(org.antlr.v4.runtime.tree.ParseTreeWalker) NikitaODataToSQLWalker(nikita.webapp.odata.NikitaODataToSQLWalker) RecognitionException(org.antlr.v4.runtime.RecognitionException)

Example 20 with RecognitionException

use of org.antlr.v4.runtime.RecognitionException in project elasticsearch by elastic.

the class ParserErrorStrategy method recover.

@Override
public void recover(final Parser recognizer, final RecognitionException re) {
    final Token token = re.getOffendingToken();
    String message;
    if (token == null) {
        message = "no parse token found.";
    } else if (re instanceof InputMismatchException) {
        message = "unexpected token [" + getTokenErrorDisplay(token) + "]" + " was expecting one of [" + re.getExpectedTokens().toString(recognizer.getVocabulary()) + "].";
    } else if (re instanceof NoViableAltException) {
        if (token.getType() == PainlessParser.EOF) {
            message = "unexpected end of script.";
        } else {
            message = "invalid sequence of tokens near [" + getTokenErrorDisplay(token) + "].";
        }
    } else {
        message = "unexpected token near [" + getTokenErrorDisplay(token) + "].";
    }
    Location location = new Location(sourceName, token == null ? -1 : token.getStartIndex());
    throw location.createError(new IllegalArgumentException(message, re));
}
Also used : NoViableAltException(org.antlr.v4.runtime.NoViableAltException) Token(org.antlr.v4.runtime.Token) InputMismatchException(org.antlr.v4.runtime.InputMismatchException) Location(org.elasticsearch.painless.Location)

Aggregations

RecognitionException (org.antlr.v4.runtime.RecognitionException)13 CommonTokenStream (org.antlr.v4.runtime.CommonTokenStream)10 ArrayList (java.util.ArrayList)8 BaseErrorListener (org.antlr.v4.runtime.BaseErrorListener)6 Token (org.antlr.v4.runtime.Token)6 ParseCancellationException (org.antlr.v4.runtime.misc.ParseCancellationException)6 ANTLRInputStream (org.antlr.v4.runtime.ANTLRInputStream)5 RecognitionException (org.antlr.runtime.RecognitionException)4 ParseTree (org.antlr.v4.runtime.tree.ParseTree)4 BoaLexer (boa.parser.BoaLexer)3 BoaParser (boa.parser.BoaParser)3 Expression (com.sri.ai.expresso.api.Expression)3 IOException (java.io.IOException)3 GrammarASTAdaptor (org.antlr.v4.parse.GrammarASTAdaptor)3 NoViableAltException (org.antlr.v4.runtime.NoViableAltException)3 ASPCore2Lexer (at.ac.tuwien.kr.alpha.antlr.ASPCore2Lexer)2 ASPCore2Parser (at.ac.tuwien.kr.alpha.antlr.ASPCore2Parser)2 ParsedProgram (at.ac.tuwien.kr.alpha.grounder.parser.ParsedProgram)2 ParsedTreeVisitor (at.ac.tuwien.kr.alpha.grounder.parser.ParsedTreeVisitor)2 Start (boa.compiler.ast.Start)2