Search in sources :

Example 1 with Parser

use of de.be4.classicalb.core.preparser.parser.Parser in project probparsers by bendisposto.

the class LtlConsoleParser method main.

public static void main(final String[] args) {
    ConsoleOptions options = new ConsoleOptions();
    options.addOption(CLI_LANG, "set language for atomic propositions, etc. (e.g. none, B)", 1);
    options.addOption(CLI_OUT, "set output file, use stdout if omitted", 1);
    options.addOption(CLI_LTL, "use LTL (default)");
    options.addOption(CLI_CTL, "use CTL instead of LTL");
    options.setIntro("usage: LtlConsoleParser [options] <LTL file>\n\n" + "If the file is omitted, stdin is used\n" + "Available options are:");
    options.addOption(CLI_HELP, "print this message");
    options.parseOptions(args);
    if (options.isOptionSet(CLI_HELP)) {
        options.printUsage(System.out);
        return;
    }
    String[] params = options.getRemainingOptions();
    if (params.length > 1) {
        options.printUsage(System.out);
        System.exit(-1);
        return;
    }
    if (options.isOptionSet(CLI_LTL) && options.isOptionSet(CLI_CTL)) {
        System.err.println("Incopatible options -ltl and -ctl given.");
        System.exit(-1);
        return;
    }
    final Mode mode = options.isOptionSet(CLI_CTL) ? Mode.CTL : Mode.LTL;
    // please note: createOutputStream might call System.exit()
    final OutputStream out = createOutputStream(options);
    final String lang = options.isOptionSet(CLI_LANG) ? options.getOptions(CLI_LANG)[0] : null;
    final ProBParserBase extParser = getExtensionParser(lang);
    final IPrologTermOutput pto = new PrologTermOutput(out, false);
    final String input = createInputStream(params, pto);
    if (input != null) {
        final String[] formulas = input.split("###");
        final TemporalLogicParser<?> parser = createParser(extParser, mode);
        pto.openList();
        for (final String formula : formulas) {
            try {
                final PrologTerm term = parser.generatePrologTerm(formula, null);
                pto.openTerm("ltl").printTerm(term).closeTerm();
            } catch (LtlParseException e) {
                pto.openTerm("syntax_error").printAtom(e.getLocalizedMessage()).closeTerm();
            }
        }
        pto.closeList();
    }
    pto.fullstop();
    pto.flush();
    if (options.isOptionSet(CLI_OUT)) {
        try {
            out.close();
        } catch (IOException e) {
        // ignore
        }
    }
}
Also used : PrologTermOutput(de.prob.prolog.output.PrologTermOutput) IPrologTermOutput(de.prob.prolog.output.IPrologTermOutput) OutputStream(java.io.OutputStream) FileOutputStream(java.io.FileOutputStream) IOException(java.io.IOException) ProBParserBase(de.prob.parserbase.ProBParserBase) PrologTerm(de.prob.prolog.term.PrologTerm) IPrologTermOutput(de.prob.prolog.output.IPrologTermOutput) LtlParseException(de.be4.ltl.core.parser.LtlParseException)

Example 2 with Parser

use of de.be4.classicalb.core.preparser.parser.Parser in project probparsers by bendisposto.

the class EventBParser method parse.

/**
 * Parses the input string.
 *
 * @param input
 *            the {@link String} to be parsed
 * @param debugOutput
 *            output debug messages on standard out?
 * @return the root node of the AST
 * @throws BException
 *             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 sourcecode 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 EventBLexerException}: 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 sourcecode
 *             position where the error occured. 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 sourcecode position of the last characters that
 *             were read from the input.</li>
 *             <li> {@link EventBParseException}: This exception is thrown in
 *             two situations. On the one hand if the parser throws a
 *             {@link ParserException} we convert it into a
 *             {@link EventBParseException}. On the other hand it can be
 *             thrown if any error is found during the AST transformations
 *             after the parser has finished. We try to provide a token if a
 *             single token is involved in the error. Otherwise a
 *             {@link SourcecodeRange} is provided, which can be used to
 *             retrieve detailed position information from the
 *             {@link SourcePositions} (s. {@link #getSourcePositions()}).</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 dublicate machine clauses,
 *             we will list all occurances in the exception.</li>
 *             </ul>
 */
public Start parse(final String input, final boolean debugOutput) throws BException {
    final Reader reader = new StringReader(input);
    try {
        /*
			 * Main parser
			 */
        final EventBLexer lexer = new EventBLexer(new PushbackReader(reader, 99));
        lexer.setDebugOutput(debugOutput);
        Parser parser = new Parser(lexer);
        final Start rootNode = parser.parse();
        final List<IToken> tokenList = ((ITokenListContainer) lexer).getTokenList();
        /*
			 * Retrieving sourcecode positions which were found by ParserAspect
			 */
        final Map<PositionedNode, SourcecodeRange> positions = ((IParser) parser).getMapping();
        sourcePositions = new SourcePositions(tokenList, positions);
        parser = null;
        return rootNode;
    } catch (final LexerException e) {
        /*
			 * Actually it's supposed to be a EventBLexerException because the
			 * aspect 'LexerAspect' replaces any LexerException to provide
			 * sourcecode position information in the BLexerException.
			 */
        throw new BException(e);
    } catch (final ParserException e) {
        throw new BException(createEventBParseException(e));
    } catch (final EventBParseException e) {
        throw new BException(e);
    } catch (final IOException e) {
        // shouldn't happen and if, we cannot handle it
        throw new BException(e);
    }
}
Also used : ParserException(de.be4.eventb.core.parser.parser.ParserException) Start(de.be4.eventb.core.parser.node.Start) SourcePositions(de.hhu.stups.sablecc.patch.SourcePositions) Reader(java.io.Reader) InputStreamReader(java.io.InputStreamReader) StringReader(java.io.StringReader) PushbackReader(java.io.PushbackReader) PositionedNode(de.hhu.stups.sablecc.patch.PositionedNode) IOException(java.io.IOException) PushbackReader(java.io.PushbackReader) IParser(de.hhu.stups.sablecc.patch.IParser) Parser(de.be4.eventb.core.parser.parser.Parser) IToken(de.hhu.stups.sablecc.patch.IToken) StringReader(java.io.StringReader) ITokenListContainer(de.hhu.stups.sablecc.patch.ITokenListContainer) SourcecodeRange(de.hhu.stups.sablecc.patch.SourcecodeRange) LexerException(de.be4.eventb.core.parser.lexer.LexerException) IParser(de.hhu.stups.sablecc.patch.IParser)

Example 3 with Parser

use of de.be4.classicalb.core.preparser.parser.Parser in project probparsers by bendisposto.

the class AbstractTest method parseInput.

protected Start parseInput(final String input, final boolean debugOutput) throws BException {
    if (debugOutput) {
        System.out.println();
        System.out.println();
    }
    final EventBParser parser = new EventBParser();
    final Start rootNode = parser.parse(input, debugOutput);
    return rootNode;
}
Also used : Start(de.be4.eventb.core.parser.node.Start) EventBParser(de.be4.eventb.core.parser.EventBParser)

Example 4 with Parser

use of de.be4.classicalb.core.preparser.parser.Parser in project probparsers by bendisposto.

the class LTLFormulaVisitor method parseBPredicate.

private de.be4.classicalb.core.parser.node.Start parseBPredicate(String text) {
    String bPredicate = "#PREDICATE " + text;
    BParser parser = new BParser("Testing");
    de.be4.classicalb.core.parser.node.Start start = null;
    try {
        start = parser.parse(bPredicate, false);
    } catch (BCompoundException e) {
        throw new LTLParseException(e.getMessage());
    }
    return start;
}
Also used : LTLParseException(de.prob.typechecker.exceptions.LTLParseException) BParser(de.be4.classicalb.core.parser.BParser) BCompoundException(de.be4.classicalb.core.parser.exceptions.BCompoundException)

Example 5 with Parser

use of de.be4.classicalb.core.preparser.parser.Parser in project probparsers by bendisposto.

the class RulesMachineChecker method caseADefinitionExpression.

@Override
public void caseADefinitionExpression(ADefinitionExpression node) {
    node.getDefLiteral().apply(this);
    final String defName = node.getDefLiteral().getText();
    if ("READ_XML_FROM_STRING".equals(defName)) {
        if (node.getParameters().size() != 1) {
            errorList.add(new CheckException("The external function 'READ_XML_FROM_STRING' requires exactly one argrument.", node));
            return;
        }
        PExpression pExpression = node.getParameters().get(0);
        if (pExpression instanceof AStringExpression) {
            AStringExpression aStringExpr = (AStringExpression) pExpression;
            TStringLiteral content = aStringExpr.getContent();
            String text = content.getText();
            int xmlStartIndex = text.indexOf("<?");
            if (xmlStartIndex == -1) {
                return;
            }
            String testString = text.substring(0, xmlStartIndex);
            int numberOfNewLines = testString.length() - testString.replace("\n", "").length();
            try {
                InputSource inputSource = new InputSource(new StringReader(text.trim()));
                SAXParserFactory factory = SAXParserFactory.newInstance();
                SAXParser saxParser = factory.newSAXParser();
                Locale newLocale = new Locale("en", "GB");
                // Surprisingly, we need both of the following two lines in
                // order to obtain all error messages in English.
                java.util.Locale.setDefault(newLocale);
                saxParser.setProperty("http://apache.org/xml/properties/locale", newLocale);
                saxParser.parse(inputSource, new DefaultHandler());
            } catch (SAXParseException e) {
                final int line = content.getLine() + numberOfNewLines + e.getLineNumber() - 1;
                final int column = (numberOfNewLines == 0 && e.getLineNumber() == 1) ? content.getPos() + e.getColumnNumber() : e.getColumnNumber();
                TStringLiteral dummy = new TStringLiteral("", line, column);
                String message = e.getMessage();
                errorList.add(new CheckException(message, dummy, e));
            } catch (SAXException e) {
                String message = e.getMessage();
                errorList.add(new CheckException(message, aStringExpr, e));
            } catch (ParserConfigurationException | IOException e) {
            /*
					 * We do nothing. The error is not handled by the parser but
					 * will be handled by the ProB prolog kernel.
					 */
            }
        }
    }
    super.caseADefinitionExpression(node);
}
Also used : Locale(java.util.Locale) InputSource(org.xml.sax.InputSource) CheckException(de.be4.classicalb.core.parser.exceptions.CheckException) AStringExpression(de.be4.classicalb.core.parser.node.AStringExpression) IOException(java.io.IOException) PExpression(de.be4.classicalb.core.parser.node.PExpression) DefaultHandler(org.xml.sax.helpers.DefaultHandler) SAXException(org.xml.sax.SAXException) SAXParseException(org.xml.sax.SAXParseException) StringReader(java.io.StringReader) SAXParser(javax.xml.parsers.SAXParser) TStringLiteral(de.be4.classicalb.core.parser.node.TStringLiteral) ParserConfigurationException(javax.xml.parsers.ParserConfigurationException) SAXParserFactory(javax.xml.parsers.SAXParserFactory)

Aggregations

Start (de.be4.classicalb.core.parser.node.Start)51 BParser (de.be4.classicalb.core.parser.BParser)41 Test (org.junit.Test)31 Ast2String (util.Ast2String)20 File (java.io.File)15 IOException (java.io.IOException)13 BCompoundException (de.be4.classicalb.core.parser.exceptions.BCompoundException)10 StringReader (java.io.StringReader)9 PushbackReader (java.io.PushbackReader)8 AbstractParseMachineTest (util.AbstractParseMachineTest)7 PrintStream (java.io.PrintStream)6 LexerException (de.be4.classicalb.core.parser.lexer.LexerException)5 ParsingBehaviour (de.be4.classicalb.core.parser.ParsingBehaviour)4 PreParseException (de.be4.classicalb.core.parser.exceptions.PreParseException)4 Reader (java.io.Reader)4 ArrayList (java.util.ArrayList)4 IDefinitions (de.be4.classicalb.core.parser.IDefinitions)3 NodeIdAssignment (de.be4.classicalb.core.parser.analysis.prolog.NodeIdAssignment)3 Start (de.be4.eventbalg.core.parser.node.Start)3 LtlParseException (de.be4.ltl.core.parser.LtlParseException)3