Search in sources :

Example 66 with Start

use of de.be4.eventb.core.parser.node.Start in project probparsers by bendisposto.

the class BParser method fullParsing.

public int fullParsing(final File bfile, final ParsingBehaviour parsingBehaviour, final PrintStream out, final PrintStream err) {
    try {
        // Properties hashes = new Properties();
        // if (parsingBehaviour.getOutputFile() != null) {
        // if (hashesStillValid(parsingBehaviour.getOutputFile())){
        // return 0;
        // }
        // }
        final long start = System.currentTimeMillis();
        final Start tree = parseFile(bfile, parsingBehaviour.isVerbose());
        final long end = System.currentTimeMillis();
        if (parsingBehaviour.isPrintTime()) {
            out.println("Time for parsing: " + (end - start) + "ms");
        }
        if (parsingBehaviour.isPrintAST()) {
            ASTPrinter sw = new ASTPrinter(out);
            tree.apply(sw);
        }
        if (parsingBehaviour.isDisplayGraphically()) {
            tree.apply(new ASTDisplay());
        }
        final long start2 = System.currentTimeMillis();
        if (parsingBehaviour.isPrologOutput()) {
            printASTasProlog(out, this, bfile, tree, parsingBehaviour, contentProvider);
        }
        final long end2 = System.currentTimeMillis();
        if (parsingBehaviour.isPrintTime()) {
            out.println("Time for Prolog output: " + (end2 - start2) + "ms");
        }
        if (parsingBehaviour.isFastPrologOutput()) {
            try {
                String fp = getASTasFastProlog(this, bfile, tree, parsingBehaviour, contentProvider);
                out.println(fp);
            } catch (Exception e) {
                throw new RuntimeException(e);
            }
        }
    } catch (final IOException e) {
        if (parsingBehaviour.isPrologOutput()) {
            PrologExceptionPrinter.printException(err, e, bfile.getAbsolutePath());
        } else {
            err.println();
            err.println("Error reading input file: " + e.getLocalizedMessage());
        }
        return -2;
    } catch (final BCompoundException e) {
        if (parsingBehaviour.isPrologOutput()) {
            PrologExceptionPrinter.printException(err, e, parsingBehaviour.isUseIndention(), false);
        // PrologExceptionPrinter.printException(err, e);
        } else {
            err.println();
            err.println("Error parsing input file: " + e.getLocalizedMessage());
        }
        return -3;
    }
    return 0;
}
Also used : Start(de.be4.classicalb.core.parser.node.Start) ASTPrinter(de.be4.classicalb.core.parser.visualisation.ASTPrinter) ASTDisplay(de.be4.classicalb.core.parser.visualisation.ASTDisplay) IOException(java.io.IOException) LexerException(de.be4.classicalb.core.parser.lexer.LexerException) IOException(java.io.IOException) ParserException(de.be4.classicalb.core.parser.parser.ParserException)

Example 67 with Start

use of de.be4.eventb.core.parser.node.Start in project probparsers by bendisposto.

the class BParser method parse.

/**
 * Parses the input string.
 *
 * @param input
 *            The {@link String} to be parsed
 * @param debugOutput
 *            output debug messages on standard out?
 * @param contentProvider
 *            A {@link IFileContentProvider} that is able to load content of
 *            referenced files during the parsing process. The content
 *            provider is used for referenced definition files for example.
 * @return the root node of the AST
 * @throws BCompoundException
 *             The {@link BCompoundException} class stores all
 *             {@link BException}s occurred during the parsing process. The
 *             {@link BException} class stores the actual exception as
 *             delegate and forwards all method calls to it. So it is save
 *             for tools to just use this exception if they want to extract
 *             an error message. If the tools needs to extract additional
 *             information, such as a source code position or involved
 *             tokens respectively nodes, it needs to retrieve the delegate
 *             exception. The {@link BException} class offers a
 *             {@link BException#getCause()} method for this, which returns
 *             the delegate exception.
 *             <p>
 *             Internal exceptions:
 *             <ul>
 *             <li>{@link PreParseException}: This exception contains errors
 *             that occur during the preparsing. If possible it supplies a
 *             token, where the error occurred.</li>
 *             <li>{@link BLexerException}: If any error occurs in the
 *             generated or customized lexer a {@link LexerException} is
 *             thrown. Usually the lexer classes just throw a
 *             {@link LexerException}. But this class unfortunately does not
 *             contain any explicit information about the source code
 *             position where the error occurred. Using aspect-oriented
 *             programming we intercept the throwing of these exceptions to
 *             replace them by our own exception. In our own exception we
 *             provide the source code position of the last characters that
 *             were read from the input.</li>
 *             <li>{@link BParseException}: This exception is thrown in two
 *             situations. On the one hand if the parser throws a
 *             {@link ParserException} we convert it into a
 *             {@link BParseException}. On the other hand it can be thrown
 *             if any error is found during the AST transformations after
 *             the parser has finished.</li>
 *             <li>{@link CheckException}: If any problem occurs while
 *             performing semantic checks, a {@link CheckException} is
 *             thrown. We provide one or more nodes that are involved in the
 *             problem. For example, if we find duplicate machine clauses,
 *             we will list all occurrences in the exception.</li>
 *             </ul>
 */
public Start parse(final String input, final boolean debugOutput, final IFileContentProvider contentProvider) throws BCompoundException {
    final Reader reader = new StringReader(input);
    try {
        // PreParsing
        final DefinitionTypes defTypes = preParsing(debugOutput, reader, contentProvider, directory);
        /*
			 * The definition types are used in the lexer in order to replace an
			 * identifier token by a definition call token. This is required if
			 * the definition is a predicate because an identifier can not be
			 * parsed as a predicate. For example "... SELECT def THEN ... "
			 * would yield to a parse error. The lexer will replace the
			 * identifier token "def" by a TDefLiteralPredicate which will be
			 * excepted by the parser
			 * 
			 */
        defTypes.addAll(definitions.getTypes());
        /*
			 * Main parser
			 */
        final BLexer lexer = new BLexer(new PushbackReader(reader, BLexer.PUSHBACK_BUFFER_SIZE), defTypes);
        lexer.setParseOptions(parseOptions);
        SabbleCCBParser parser = new SabbleCCBParser(lexer);
        final Start rootNode = parser.parse();
        final List<BException> bExceptionList = new ArrayList<>();
        /*
			 * Collect available definition declarations. Needs to be done now
			 * cause they are needed by the following transformations.
			 */
        final DefinitionCollector collector = new DefinitionCollector(defTypes, this.definitions);
        collector.collectDefinitions(rootNode);
        List<CheckException> definitionsCollectorExceptions = collector.getExceptions();
        for (CheckException checkException : definitionsCollectorExceptions) {
            bExceptionList.add(new BException(getFileName(), checkException));
        }
        // perfom AST transformations that can't be done by SableCC
        try {
            applyAstTransformations(rootNode);
        } catch (CheckException e) {
            throw new BCompoundException(new BException(getFileName(), e));
        }
        // perform some semantic checks which are not done in the parser
        List<CheckException> checkExceptions = performSemanticChecks(rootNode);
        for (CheckException checkException : checkExceptions) {
            bExceptionList.add(new BException(getFileName(), checkException));
        }
        if (!bExceptionList.isEmpty()) {
            throw new BCompoundException(bExceptionList);
        }
        return rootNode;
    } catch (final LexerException e) {
        throw new BCompoundException(new BException(getFileName(), e));
    } catch (final BParseException e) {
        throw new BCompoundException(new BException(getFileName(), e));
    } catch (final IOException e) {
        throw new BCompoundException(new BException(getFileName(), e));
    } catch (final PreParseException e) {
        throw new BCompoundException(new BException(getFileName(), e));
    } catch (final ParserException e) {
        final Token token = e.getToken();
        String msg = getImprovedErrorMessageBasedOnTheErrorToken(token);
        if (msg == null) {
            msg = e.getLocalizedMessage();
        }
        final String realMsg = e.getRealMsg();
        throw new BCompoundException(new BException(getFileName(), new BParseException(token, msg, realMsg, e)));
    } catch (BException e) {
        throw new BCompoundException(e);
    }
}
Also used : DefinitionCollector(de.be4.classicalb.core.parser.analysis.checking.DefinitionCollector) ParserException(de.be4.classicalb.core.parser.parser.ParserException) Start(de.be4.classicalb.core.parser.node.Start) ArrayList(java.util.ArrayList) Reader(java.io.Reader) StringReader(java.io.StringReader) PushbackReader(java.io.PushbackReader) Token(de.be4.classicalb.core.parser.node.Token) IOException(java.io.IOException) PushbackReader(java.io.PushbackReader) StringReader(java.io.StringReader) LexerException(de.be4.classicalb.core.parser.lexer.LexerException)

Example 68 with Start

use of de.be4.eventb.core.parser.node.Start in project probparsers by bendisposto.

the class BParser method performSemanticChecks.

private List<CheckException> performSemanticChecks(final Start rootNode) {
    final List<CheckException> list = new ArrayList<>();
    final SemanticCheck[] checks = { new ClausesCheck(), new SemicolonCheck(), new IdentListCheck(), new DefinitionUsageCheck(getDefinitions()), new PrimedIdentifierCheck(), new ProverExpressionsCheck() };
    for (SemanticCheck check : checks) {
        check.setOptions(parseOptions);
        check.runChecks(rootNode);
        list.addAll(check.getCheckExceptions());
    }
    return list;
}
Also used : SemicolonCheck(de.be4.classicalb.core.parser.analysis.checking.SemicolonCheck) IdentListCheck(de.be4.classicalb.core.parser.analysis.checking.IdentListCheck) SemanticCheck(de.be4.classicalb.core.parser.analysis.checking.SemanticCheck) ArrayList(java.util.ArrayList) ProverExpressionsCheck(de.be4.classicalb.core.parser.analysis.checking.ProverExpressionsCheck) ClausesCheck(de.be4.classicalb.core.parser.analysis.checking.ClausesCheck) PrimedIdentifierCheck(de.be4.classicalb.core.parser.analysis.checking.PrimedIdentifierCheck) DefinitionUsageCheck(de.be4.classicalb.core.parser.analysis.checking.DefinitionUsageCheck)

Example 69 with Start

use of de.be4.eventb.core.parser.node.Start in project probparsers by bendisposto.

the class ClassicalBParser method parsePredicate.

@Override
public void parsePredicate(final IPrologTermOutput pto, final String predicate, final boolean wrap) throws ProBParseException {
    try {
        Start ast = new BParser().parsePredicate(predicate);
        printAst(pto, ast, wrap, WRAPPER_PRED);
    } catch (BCompoundException e) {
        throw new ProBParseException(e.getFirstException().getLocalizedMessage());
    }
}
Also used : Start(de.be4.classicalb.core.parser.node.Start) ProBParseException(de.prob.parserbase.ProBParseException) BCompoundException(de.be4.classicalb.core.parser.exceptions.BCompoundException)

Example 70 with Start

use of de.be4.eventb.core.parser.node.Start in project probparsers by bendisposto.

the class PreLexer method collectRhs.

private void collectRhs() throws LexerException, IOException {
    if (state.equals(State.DEFINITIONS_RHS) || (previousState != null && previousState.equals(State.DEFINITIONS_RHS))) {
        if (rhsToken == null) {
            // starting a new definition rhs
            rhsToken = new TRhsBody("", -1, -1);
            rhsBuffer = new StringBuilder();
        } else {
            final State nextState = getNextState();
            // end of rhs reached?
            if (nextState != null) {
                // push current token back into reader
                try {
                    unread(token);
                } catch (IOException e) {
                    throw new IOException("Pushback buffer overflow on Token: " + token.getText());
                }
                // prepare rhs_body token to be the current one
                ((Token) rhsToken).setText(rhsBuffer.toString());
                token = rhsToken;
                rhsToken = null;
                rhsBuffer = null;
                state = nextState;
            } else {
                // first token after "==" sets start position
                if (rhsToken.getLine() == -1) {
                    rhsToken.setLine(token.getLine());
                    rhsToken.setPos(token.getPos());
                }
                rhsBuffer.append(token.getText());
                token = null;
            }
        }
    }
}
Also used : TRhsBody(de.be4.classicalb.core.preparser.node.TRhsBody) Token(de.be4.classicalb.core.preparser.node.Token) IOException(java.io.IOException)

Aggregations

Start (de.be4.classicalb.core.parser.node.Start)104 Test (org.junit.Test)84 BParser (de.be4.classicalb.core.parser.BParser)43 Ast2String (util.Ast2String)32 File (java.io.File)20 Start (de.be4.eventbalg.core.parser.node.Start)19 BCompoundException (de.be4.classicalb.core.parser.exceptions.BCompoundException)18 Start (de.be4.eventb.core.parser.node.Start)18 AMachineParseUnit (de.be4.eventb.core.parser.node.AMachineParseUnit)14 AMachineParseUnit (de.be4.eventbalg.core.parser.node.AMachineParseUnit)14 IOException (java.io.IOException)12 RecursiveMachineLoader (de.be4.classicalb.core.parser.analysis.prolog.RecursiveMachineLoader)11 PushbackReader (java.io.PushbackReader)11 StringReader (java.io.StringReader)11 ASTProlog (de.be4.classicalb.core.parser.analysis.prolog.ASTProlog)8 AExpressionParseUnit (de.be4.classicalb.core.parser.node.AExpressionParseUnit)7 AbstractParseMachineTest (util.AbstractParseMachineTest)7 ParsingBehaviour (de.be4.classicalb.core.parser.ParsingBehaviour)6 ClassicalPositionPrinter (de.be4.classicalb.core.parser.analysis.prolog.ClassicalPositionPrinter)6 ASTPrinter (de.be4.classicalb.core.parser.visualisation.ASTPrinter)6