Search in sources :

Example 21 with CharStream

use of org.antlr.v4.runtime.CharStream in project titan.EclipsePlug-ins by eclipse.

the class ExtensionAttributeAnalyzer method parse.

public void parse(final AttributeSpecification specification) {
    ExtensionAttributeLexer lexer;
    Location location = specification.getLocation();
    StringReader reader = new StringReader(specification.getSpecification());
    CharStream charStream = new UnbufferedCharStream(reader);
    lexer = new ExtensionAttributeLexer(charStream);
    lexer.setTokenFactory(new CommonTokenFactory(true));
    TitanListener lexerListener = new TitanListener();
    lexer.removeErrorListeners();
    lexer.addErrorListener(lexerListener);
    // 1. Previously it was UnbufferedTokenStream(lexer), but it was changed to BufferedTokenStream, because UnbufferedTokenStream seems to be unusable. It is an ANTLR 4 bug.
    // Read this: https://groups.google.com/forum/#!topic/antlr-discussion/gsAu-6d3pKU
    // pr_PatternChunk[StringBuilder builder, boolean[] uni]:
    // $builder.append($v.text); <-- exception is thrown here: java.lang.UnsupportedOperationException: interval 85..85 not in token buffer window: 86..341
    // 2. Changed from BufferedTokenStream to CommonTokenStream, otherwise tokens with "-> channel(HIDDEN)" are not filtered out in lexer.
    final CommonTokenStream tokenStream = new CommonTokenStream(lexer);
    ExtensionAttributeParser parser = new ExtensionAttributeParser(tokenStream);
    parser.setBuildParseTree(false);
    TitanListener parserListener = new TitanListener();
    parser.removeErrorListeners();
    parser.addErrorListener(parserListener);
    parser.setActualFile((IFile) location.getFile());
    parser.setLine(location.getLine());
    parser.setOffset(location.getOffset() + 1);
    MarkerHandler.markMarkersForRemoval(GeneralConstants.ONTHEFLY_SYNTACTIC_MARKER, location.getFile(), location.getOffset(), location.getEndOffset());
    attributes = null;
    attributes = parser.pr_ExtensionAttributeRoot().list;
    if (!lexerListener.getErrorsStored().isEmpty()) {
        String reportLevel = Platform.getPreferencesService().getString(ProductConstants.PRODUCT_ID_DESIGNER, PreferenceConstants.REPORTERRORSINEXTENSIONSYNTAX, GeneralConstants.WARNING, null);
        int errorLevel;
        if (GeneralConstants.ERROR.equals(reportLevel)) {
            errorLevel = IMarker.SEVERITY_ERROR;
        } else if (GeneralConstants.WARNING.equals(reportLevel)) {
            errorLevel = IMarker.SEVERITY_WARNING;
        } else {
            return;
        }
        for (int i = 0; i < lexerListener.getErrorsStored().size(); i++) {
            Location temp = new Location(location);
            temp.setOffset(temp.getOffset() + 1);
            ParserMarkerSupport.createOnTheFlyMixedMarker((IFile) location.getFile(), lexerListener.getErrorsStored().get(i), errorLevel, temp);
        }
    }
    if (!parserListener.getErrorsStored().isEmpty()) {
        String reportLevel = Platform.getPreferencesService().getString(ProductConstants.PRODUCT_ID_DESIGNER, PreferenceConstants.REPORTERRORSINEXTENSIONSYNTAX, GeneralConstants.WARNING, null);
        int errorLevel;
        if (GeneralConstants.ERROR.equals(reportLevel)) {
            errorLevel = IMarker.SEVERITY_ERROR;
        } else if (GeneralConstants.WARNING.equals(reportLevel)) {
            errorLevel = IMarker.SEVERITY_WARNING;
        } else {
            return;
        }
        for (int i = 0; i < parserListener.getErrorsStored().size(); i++) {
            Location temp = new Location(location);
            temp.setOffset(temp.getOffset() + 1);
            ParserMarkerSupport.createOnTheFlyMixedMarker((IFile) location.getFile(), parserListener.getErrorsStored().get(i), errorLevel, temp);
        }
    }
}
Also used : CommonTokenStream(org.antlr.v4.runtime.CommonTokenStream) CommonTokenFactory(org.antlr.v4.runtime.CommonTokenFactory) StringReader(java.io.StringReader) UnbufferedCharStream(org.antlr.v4.runtime.UnbufferedCharStream) CharStream(org.antlr.v4.runtime.CharStream) UnbufferedCharStream(org.antlr.v4.runtime.UnbufferedCharStream) TitanListener(org.eclipse.titan.common.parsers.TitanListener) Location(org.eclipse.titan.designer.AST.Location)

Example 22 with CharStream

use of org.antlr.v4.runtime.CharStream in project LogHub by fbacchella.

the class TestParser method testType.

@Test
public void testType() throws IOException {
    CharStream cs = CharStreams.fromStream(getClass().getClassLoader().getResourceAsStream("types.conf"), CharsetUtil.UTF_8);
    RouteLexer lexer = new RouteLexer(cs);
    CommonTokenStream tokens = new CommonTokenStream(lexer);
    RouteParser parser = new RouteParser(tokens);
    parser.removeErrorListeners();
    ConfigErrorListener errListener = new ConfigErrorListener();
    parser.addErrorListener(errListener);
    // begin parsing at init rule
    loghub.RouteParser.ConfigurationContext tree = parser.configuration();
    ConfigListener conf = new ConfigListener();
    ParseTreeWalker walker = new ParseTreeWalker();
    walker.walk(conf, tree);
    Assert.assertEquals("stack not empty :" + conf.stack, 0, conf.stack.size());
    ConfigListener.PipenodesList main = conf.pipelines.get("main");
    ObjectDescription p = (ObjectDescription) main.processors.get(0);
    Assert.assertTrue(((ObjectWrapped) p.beans.get("string")).wrapped instanceof String);
    Assert.assertTrue(((ObjectWrapped) p.beans.get("boolean")).wrapped instanceof Boolean);
    Assert.assertTrue(((ObjectWrapped) p.beans.get("int")).wrapped instanceof Integer);
    Assert.assertTrue(((ObjectWrapped) p.beans.get("double")).wrapped instanceof Double);
    Assert.assertArrayEquals(new Object[] { "0", 1, 1.0, true }, (Object[]) ((ObjectWrapped) p.beans.get("array")).wrapped);
}
Also used : CommonTokenStream(org.antlr.v4.runtime.CommonTokenStream) RouteLexer(loghub.RouteLexer) RouteParser(loghub.RouteParser) ObjectWrapped(loghub.configuration.ConfigListener.ObjectWrapped) CharStream(org.antlr.v4.runtime.CharStream) ObjectDescription(loghub.configuration.ConfigListener.ObjectDescription) ParseTreeWalker(org.antlr.v4.runtime.tree.ParseTreeWalker) Test(org.junit.Test)

Example 23 with CharStream

use of org.antlr.v4.runtime.CharStream in project inmemantlr by julianthome.

the class GenericParser method parse.

/**
 * parse string and create a context
 *
 * @param toParse    string to parseFile
 * @param production production name to parseFile
 * @param cs         case sensitivity
 * @return context
 * @throws IllegalWorkflowException if compilation did not take place
 * @throws ParsingException         if an error occurs while parsing
 */
public ParserRuleContext parse(String toParse, String production, CaseSensitiveType cs) throws IllegalWorkflowException, ParsingException {
    if (!antrlObjectsAvailable()) {
        throw new IllegalWorkflowException("No antlr objects have been compiled or loaded");
    }
    switch(cs) {
        case NONE:
            break;
        case UPPER:
            toParse = toParse.toUpperCase();
            break;
        case LOWER:
            toParse = toParse.toLowerCase();
            break;
    }
    InmemantlrErrorListener el = new InmemantlrErrorListener();
    listener.reset();
    // CodePointCharStream input = CharStreams.fromString(toParse);
    CharStream input = provider.getCharStream(toParse);
    Objects.requireNonNull(input, "char stream must not be null");
    LOGGER.debug("load lexer {}", lexerName);
    Lexer lex = sc.instanciateLexer(input, lexerName, useCached);
    lex.addErrorListener(el);
    Objects.requireNonNull(lex, "lex must not be null");
    CommonTokenStream tokens = new CommonTokenStream(lex);
    tokens.fill();
    LOGGER.debug("load parser {}", parserName);
    Parser parser = sc.instanciateParser(tokens, parserName);
    Objects.requireNonNull(parser, "Parser must not be null");
    // make parser information available to listener
    listener.setParser(parser);
    parser.removeErrorListeners();
    parser.addErrorListener(el);
    parser.getInterpreter().setPredictionMode(PredictionMode.LL_EXACT_AMBIG_DETECTION);
    parser.setBuildParseTree(true);
    parser.setTokenStream(tokens);
    String[] rules = parser.getRuleNames();
    String entryPoint;
    if (production == null) {
        entryPoint = rules[0];
    } else {
        if (!Arrays.asList(rules).contains(production)) {
            throw new IllegalArgumentException("Rule " + production + " not found");
        }
        entryPoint = production;
    }
    ParserRuleContext data = null;
    try {
        Class<?> pc = parser.getClass();
        Method m = pc.getDeclaredMethod(entryPoint, (Class<?>[]) null);
        Objects.requireNonNull(m, "method should not be null");
        data = (ParserRuleContext) m.invoke(parser, (Object[]) null);
    } catch (NoSuchMethodException | SecurityException | IllegalAccessException | IllegalArgumentException | InvocationTargetException e) {
        // e.printStackTrace();
        return null;
    }
    Set<String> msgs = el.getLog().entrySet().stream().filter(e -> e.getKey() == InmemantlrErrorListener.Type.SYNTAX_ERROR).map(e -> e.getValue()).collect(Collectors.toSet());
    if (msgs.size() > 0) {
        String result = msgs.stream().collect(Collectors.joining());
        throw new ParsingException(result);
    }
    ParseTreeWalker walker = new ParseTreeWalker();
    walker.walk(listener, data);
    return data;
}
Also used : java.util(java.util) org.snt.inmemantlr.comp(org.snt.inmemantlr.comp) FileUtils(org.snt.inmemantlr.utils.FileUtils) LoggerFactory(org.slf4j.LoggerFactory) MemoryTuple(org.snt.inmemantlr.memobjects.MemoryTuple) DefaultStreamProvider(org.snt.inmemantlr.stream.DefaultStreamProvider) org.snt.inmemantlr.exceptions(org.snt.inmemantlr.exceptions) GenericParserSerialize(org.snt.inmemantlr.memobjects.GenericParserSerialize) InmemantlrTool(org.snt.inmemantlr.tool.InmemantlrTool) ToolCustomizer(org.snt.inmemantlr.tool.ToolCustomizer) GrammarRootAST(org.antlr.v4.tool.ast.GrammarRootAST) Method(java.lang.reflect.Method) Tuple(org.snt.inmemantlr.utils.Tuple) org.antlr.v4.runtime(org.antlr.v4.runtime) Logger(org.slf4j.Logger) StreamProvider(org.snt.inmemantlr.stream.StreamProvider) ParseTreeWalker(org.antlr.v4.runtime.tree.ParseTreeWalker) DefaultListener(org.snt.inmemantlr.listener.DefaultListener) IOUtils.closeQuietly(org.apache.commons.io.IOUtils.closeQuietly) PredictionMode(org.antlr.v4.runtime.atn.PredictionMode) Collectors(java.util.stream.Collectors) InmemantlrErrorListener(org.snt.inmemantlr.tool.InmemantlrErrorListener) InvocationTargetException(java.lang.reflect.InvocationTargetException) MemorySource(org.snt.inmemantlr.memobjects.MemorySource) MemoryTupleSet(org.snt.inmemantlr.memobjects.MemoryTupleSet) java.io(java.io) FileExistsException(org.apache.commons.io.FileExistsException) Paths(java.nio.file.Paths) ParseTreeListener(org.antlr.v4.runtime.tree.ParseTreeListener) FilenameUtils(org.apache.commons.io.FilenameUtils) InmemantlrErrorListener(org.snt.inmemantlr.tool.InmemantlrErrorListener) Method(java.lang.reflect.Method) InvocationTargetException(java.lang.reflect.InvocationTargetException) ParseTreeWalker(org.antlr.v4.runtime.tree.ParseTreeWalker)

Example 24 with CharStream

use of org.antlr.v4.runtime.CharStream in project redsnake by Taken0711.

the class Redsnake method buildAST.

public Statement buildAST(CharStream inputStream) {
    RedsnakeLexer redsnakeLexer = new RedsnakeLexer(inputStream);
    TokenStream commonTokenStream = new CommonTokenStream(redsnakeLexer);
    RedsnakeParser parser = new RedsnakeParser(commonTokenStream);
    ParseTree t = parser.statement();
    return (Statement) astBuilder.visit(t);
}
Also used : CommonTokenStream(org.antlr.v4.runtime.CommonTokenStream) TokenStream(org.antlr.v4.runtime.TokenStream) CommonTokenStream(org.antlr.v4.runtime.CommonTokenStream) RedsnakeLexer(net.taken.redsnake.parser.RedsnakeLexer) RedsnakeParser(net.taken.redsnake.parser.RedsnakeParser) Statement(net.taken.redsnake.tree.statements.Statement) ParseTree(org.antlr.v4.runtime.tree.ParseTree)

Example 25 with CharStream

use of org.antlr.v4.runtime.CharStream in project redsnake by Taken0711.

the class TestUtils method parseProgram.

public static Program parseProgram(@NotNull String... s) {
    StringBuilder str = new StringBuilder();
    Arrays.stream(s).forEach(st -> str.append(st).append(System.lineSeparator()));
    CharStream inputStream = CharStreams.fromString(str.toString());
    RedsnakeLexer redsnakeLexer = new RedsnakeLexer(inputStream);
    TokenStream commonTokenStream = new CommonTokenStream(redsnakeLexer);
    RedsnakeParser parser = new RedsnakeParser(commonTokenStream);
    ParseTree t = parser.program();
    return (Program) new ASTBuilder().visit(t);
}
Also used : RedsnakeLexer(net.taken.redsnake.parser.RedsnakeLexer) RedsnakeParser(net.taken.redsnake.parser.RedsnakeParser) ASTBuilder(net.taken.redsnake.parser.visitors.ASTBuilder) ParseTree(org.antlr.v4.runtime.tree.ParseTree)

Aggregations

CharStream (org.antlr.v4.runtime.CharStream)187 Test (org.junit.Test)93 CommonTokenStream (org.antlr.v4.runtime.CommonTokenStream)85 UnbufferedCharStream (org.antlr.v4.runtime.UnbufferedCharStream)46 ParseTree (org.antlr.v4.runtime.tree.ParseTree)38 ParseTreeWalker (org.antlr.v4.runtime.tree.ParseTreeWalker)30 IOException (java.io.IOException)28 InputStream (java.io.InputStream)23 ANTLRInputStream (org.antlr.v4.runtime.ANTLRInputStream)23 LexerInterpreter (org.antlr.v4.runtime.LexerInterpreter)22 File (java.io.File)21 TokenStream (org.antlr.v4.runtime.TokenStream)21 StringReader (java.io.StringReader)20 CancellationException (java.util.concurrent.CancellationException)20 ConsoleErrorListener (org.antlr.v4.runtime.ConsoleErrorListener)20 CommonTokenFactory (org.antlr.v4.runtime.CommonTokenFactory)18 Token (org.antlr.v4.runtime.Token)18 LexerGrammar (org.antlr.v4.tool.LexerGrammar)18 Utils.toCharStream (clawfc.Utils.toCharStream)15 Path (java.nio.file.Path)14