org.antlr.v4.runtime.ParserRuleContext Java Examples
The following examples show how to use
org.antlr.v4.runtime.ParserRuleContext.
You can vote up the ones you like or vote down the ones you don't like,
and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: Tool.java From bookish with MIT License | 6 votes |
/** Given any XML tag like <chapter> or <pyeval>, return value associated * with the attribute for key. */ public static String getAttr(ParseTree t, String key) { ParserRuleContext ctx = (ParserRuleContext)t; if ( ctx==null ) { return null; // no attributes } BookishParser.AttrsContext attrsCtx = null; if ( ctx instanceof BookishParser.AttrsContext ) { attrsCtx = (BookishParser.AttrsContext)ctx; } else { attrsCtx = ctx.getRuleContext(BookishParser.AttrsContext.class, 0); } if ( attrsCtx!=null ) { if ( attrsCtx.valid.contains(key) ) { return attrsCtx.attributes.get(key); } else { throw new IllegalArgumentException("No such valid attribute name: '"+key+"'"); } } return null; }
Example #2
Source File: DmlSyntacticValidator.java From systemds with Apache License 2.0 | 6 votes |
protected void exitDataIdExpressionHelper(ParserRuleContext ctx, ExpressionInfo me, ExpressionInfo dataInfo) { // inject builtin constant if (dataInfo.expr instanceof DataIdentifier) { DataIdentifier id = ((DataIdentifier) dataInfo.expr); if (BuiltinConstant.contains(id.getName())) { dataInfo.expr = new DoubleIdentifier(BuiltinConstant.valueOf(id.getName()).get(), dataInfo.expr); } } me.expr = dataInfo.expr; // If "The parameter $X either needs to be passed through commandline or initialized to default value" validation // error occurs, then dataInfo.expr is null which would cause a null pointer exception with the following code. // Therefore, check for null so that parsing can continue so all parsing issues can be determined. if (me.expr != null) { me.expr.setCtxValuesAndFilename(ctx, currentFile); } }
Example #3
Source File: PrefixElem.java From swift-js-transpiler with MIT License | 6 votes |
static private PrefixElem getTemplatedConstructor(ParserRuleContext rChild, Instance type, List<ParserRuleContext/*Expression_elementContext or Closure_expressionContext*/> functionCallParams, Visitor visitor) { SwiftParser.Generic_argument_clauseContext template = ((SwiftParser.Primary_expressionContext) rChild).generic_argument_clause(); String typeStr = visitor.visit(rChild.getChild(0)).trim(); if(typeStr.equals("Set")) { if(type == null) { type = new Instance("Set", rChild, visitor.cache); type.generics = new HashMap<String, Instance>(); type.generics.put("Value", new Instance(template.generic_argument_list().generic_argument(0).getText(), rChild, visitor.cache)); } return new PrefixElem(visitor.targetLanguage.equals("ts") ? "new Set()" : "new " + type.targetType(visitor.targetLanguage, true, false) + "()", false, type, null, null, null); } return null; }
Example #4
Source File: JetTemplateCodeVisitor.java From jetbrick-template-1x with Apache License 2.0 | 6 votes |
private void assert_inside_of_for_directive(ParserRuleContext ctx, String name) { // 还有一种方法,直接看 forStack 是否为空就可以了 ParserRuleContext p = ctx.getParent(); while (p != null) { if (p instanceof For_directiveContext) { return; } if (p instanceof Else_directiveContext) { // 跳过可能的 for-else 的情况, 继续向上查找 // 当然如果时候 if-else 的情况, 也可以跳过这个 #if,没有问题 p = p.getParent(); } p = p.getParent(); } throw reportError(name + " cannot be used outside of a #for directive", ctx); }
Example #5
Source File: TestChildIterable.java From yauaa with Apache License 2.0 | 6 votes |
@Test public void testEdgeFewChildrens(){ ChildIterable ci = new ChildIterable(true, 1, 5, x -> (true)); ParserRuleContext prc = new ParserRuleContext(); prc.children = new ArrayList<>(); prc.children.add(new ParserRuleContext()); prc.children.add(new ParserRuleContext()); prc.children.add(new ParserRuleContext()); prc.children.add(new ParserRuleContext()); Iterator<ParseTree> iterator = ci.iterator(prc); assertThrows(NoSuchElementException.class, () -> { int i = 0; while (i < 10) { i++; iterator.next(); } }); }
Example #6
Source File: AbstractProtoParserListener.java From protostuff-compiler with Apache License 2.0 | 6 votes |
protected void attachComments(ParserRuleContext ctx, AbstractElement element, boolean addTrailingComment) { List<String> comments = new ArrayList<>(); Token stop = ctx.getStop(); Token start = ctx.getStart(); List<Token> tokensBefore = tokens.getHiddenTokensToLeft(start.getTokenIndex(), HIDDEN); if (tokensBefore != null) { for (Token token : tokensBefore) { if (usedComments.get(token.getLine())) { continue; } if (token.getType() == LINE_COMMENT) { addCommentToList(token, comments); } } } if (addTrailingComment) { List<Token> tokensAfter = tokens.getHiddenTokensToRight(stop.getTokenIndex(), HIDDEN); findTrailingComment(tokensAfter) .ifPresent(token -> addCommentToList(token, comments)); } List<String> trimComments = trim(comments); for (String comment : trimComments) { element.addComment(comment); } }
Example #7
Source File: IdentifyOversizeLists.java From codebuff with BSD 2-Clause "Simplified" License | 6 votes |
public void visitNonSingletonWithSeparator(ParserRuleContext ctx, List<? extends ParserRuleContext> siblings, Token separator) { boolean oversize = isOversizeList(ctx, siblings, separator); Map<Token, Pair<Boolean, Integer>> tokenInfo = getInfoAboutListTokens(ctx, tokens, tokenToNodeMap, siblings, oversize); // copy sibling list info for associated tokens into overall list // but don't overwrite existing so that most general (largest construct) // list information is use/retained (i.e., not overwritten). for (Token t : tokenInfo.keySet()) { if ( !tokenToListInfo.containsKey(t) ) { tokenToListInfo.put(t, tokenInfo.get(t)); } } }
Example #8
Source File: ParseTreePrettyPrinterTest.java From batfish with Apache License 2.0 | 6 votes |
@Test public void testGetParseTreeSentencesLineNumbers() { String configText = readResource("org/batfish/grammar/line_numbers", UTF_8); RecoveryCombinedParser cp = new RecoveryCombinedParser(configText, SETTINGS); ParserRuleContext tree = cp.parse(); ParseTreeSentences ptSentencesLineNums = ParseTreePrettyPrinter.getParseTreeSentences(tree, cp, true); /* Confirm printed parse tree includes line numbers when that option is set */ assertThat(ptSentencesLineNums.getSentences().get(3), containsString("SIMPLE:'simple' line:1")); assertThat(ptSentencesLineNums.getSentences().get(9), containsString("BLOCK:'block' line:2")); assertThat(ptSentencesLineNums.getSentences().get(12), containsString("INNER:'inner' line:3")); assertThat( ptSentencesLineNums.getSentences().get(14), containsString("SIMPLE:'simple' line:3)")); assertThat(ptSentencesLineNums.getSentences().get(16), containsString("EOF:<EOF> line:5)")); }
Example #9
Source File: ContentUriChecker.java From kripton with Apache License 2.0 | 6 votes |
/** * Prepare path. * * @param input the input * @return the pair */ private Pair<ParserRuleContext, CommonTokenStream> preparePath(final String input) { UriLexer lexer = new UriLexer(CharStreams.fromString(input)); CommonTokenStream tokens = new CommonTokenStream(lexer); UriParser parser = new UriParser(tokens); parser.removeErrorListeners(); parser.addErrorListener(new ContentUriBaseErrorListener() { @Override public void syntaxError(Recognizer<?, ?> recognizer, Object offendingSymbol, int line, int charPositionInLine, String msg, RecognitionException e) { AssertKripton.assertTrue(false, "unespected char at pos %s of URI '%s'", charPositionInLine, input); } }); ParserRuleContext context = parser.path(); return new Pair<>(context, tokens); }
Example #10
Source File: AristaGrammarTest.java From batfish with Apache License 2.0 | 6 votes |
private static @Nonnull AristaConfiguration parseVendorConfig(String hostname) { String src = readResource(TESTCONFIGS_PREFIX + hostname, UTF_8); Settings settings = new Settings(); configureBatfishTestSettings(settings); AristaCombinedParser ciscoParser = new AristaCombinedParser(src, settings); AristaControlPlaneExtractor extractor = new AristaControlPlaneExtractor( src, ciscoParser, ConfigurationFormat.ARISTA, new Warnings()); ParserRuleContext tree = Batfish.parse( ciscoParser, new BatfishLogger(BatfishLogger.LEVELSTR_FATAL, false), settings); extractor.processParseTree(TEST_SNAPSHOT, tree); AristaConfiguration vendorConfiguration = (AristaConfiguration) extractor.getVendorConfiguration(); vendorConfiguration.setFilename(TESTCONFIGS_PREFIX + hostname); // crash if not serializable return SerializationUtils.clone(vendorConfiguration); }
Example #11
Source File: CumulusNcluConfigurationBuilder.java From batfish with Apache License 2.0 | 6 votes |
private void unrecognized(ParseWarning warning, @Nullable ParserRuleContext ctx) { // for testing if (_parser.getSettings().getDisableUnrecognized()) { try { String warningStr = BatfishObjectMapper.writePrettyString(warning); String parseTreeStr = ctx != null ? ParseTreePrettyPrinter.print( ctx, _parser, _parser.getSettings().getPrintParseTreeLineNums()) : ""; throw new BatfishException( String.format( "Forcing failure on unrecognized line: %s\n%s", warningStr, parseTreeStr)); } catch (JsonProcessingException e) { throw new BatfishException("Failure describing unrecognized line", e); } } _w.getParseWarnings().add(warning); _c.setUnrecognized(true); }
Example #12
Source File: BatfishANTLRErrorStrategy.java From batfish with Apache License 2.0 | 6 votes |
/** * Create an error node with the text of the current line and insert it into parse tree * * @param recognizer The recognizer with which to create the error node * @param separator The token that ends the unrecognized link. This is also used to determine the * index of the line to return in error messages. * @return The token contained in the error node */ private Token createErrorNode(Parser recognizer, ParserRuleContext ctx, Token separator) { if (_recoveredAtEof) { _recoveredAtEof = false; throw new BatfishRecognitionException(recognizer, recognizer.getInputStream(), ctx); } if (separator.getType() == Lexer.EOF) { _recoveredAtEof = true; } String lineText = _lines[separator.getLine() - 1] + separator.getText(); Token lineToken = new UnrecognizedLineToken(lineText, separator.getLine(), _parserStateAtRecovery); ErrorNode errorNode = recognizer.createErrorNode(ctx, lineToken); ctx.addErrorNode(errorNode); return lineToken; }
Example #13
Source File: CumulusNcluGrammarTest.java From batfish with Apache License 2.0 | 6 votes |
private @Nonnull CumulusNcluConfiguration parseVendorConfig(String hostname) { String src = readResource(TESTCONFIGS_PREFIX + hostname, UTF_8); Settings settings = new Settings(); settings.setDisableUnrecognized(true); settings.setThrowOnLexerError(true); settings.setThrowOnParserError(true); CumulusNcluCombinedParser parser = new CumulusNcluCombinedParser(src, settings); CumulusNcluControlPlaneExtractor extractor = new CumulusNcluControlPlaneExtractor(src, parser, new Warnings()); ParserRuleContext tree = Batfish.parse(parser, new BatfishLogger(BatfishLogger.LEVELSTR_FATAL, false), settings); extractor.processParseTree(TEST_SNAPSHOT, tree); assertThat( String.format("Ensure '%s' was successfully parsed", hostname), extractor.getVendorConfiguration(), notNullValue()); VendorConfiguration vc = extractor.getVendorConfiguration(); assertThat(vc, instanceOf(CumulusNcluConfiguration.class)); return SerializationUtils.clone((CumulusNcluConfiguration) vc); }
Example #14
Source File: ExecutableCodeDef.java From bookish with MIT License | 6 votes |
public ExecutableCodeDef(ParserRuleContext tree, String inputFilename, int index, BookishParser.AttrsContext attrsCtx, String code) { super(index, attrsCtx!=null ? attrsCtx.attributes : null); this.tree = tree; this.inputFilename = inputFilename; this.code = expandTabs(code, 4); if ( attrsCtx!=null ) { if ( attrsCtx.attributes.containsKey("hide") ) { isCodeVisible = !attrsCtx.attributes.get("hide").equals("true"); } if ( attrsCtx.attributes.containsKey("output") ) { displayExpr = attrsCtx.attributes.get("output"); } if ( attrsCtx.attributes.containsKey("disable") ) { isEnabled = !attrsCtx.attributes.get("disable").equals("true"); } } if ( label==null ) { label = DEFAULT_CODE_LABEL; } }
Example #15
Source File: NumberRangeVisitor.java From yauaa with Apache License 2.0 | 5 votes |
private static Integer getMaxRange(NumberRangeContext ctx) { ParserRuleContext parent = ctx.getParent(); String name = ((StepDownContext) parent).name.getText(); Integer maxRange = MAX_RANGE.get(name); if (maxRange == null) { return DEFAULT_MAX; } return maxRange; }
Example #16
Source File: DmlSyntacticValidator.java From systemds with Apache License 2.0 | 5 votes |
private void handleDMLBodiedBuiltinFunction(String functionName, String namespace, ParserRuleContext ctx) { if( Builtins.contains(functionName, true, false) ) { //load and add builtin DML-bodied functions String filePath = Builtins.getFilePath(functionName); DMLProgram prog = parseAndAddImportedFunctions(namespace, filePath, ctx); for( Entry<String,FunctionStatementBlock> f : prog.getNamedFunctionStatementBlocks().entrySet() ) builtinFuns.addFunctionStatementBlock(f.getKey(), f.getValue()); } }
Example #17
Source File: YangStatementStreamSource.java From yangtools with Eclipse Public License 1.0 | 5 votes |
/** * Create a {@link YangStatementStreamSource} for a {@link ASTSchemaSource}. * * @param source YangTextSchemaSource, must not be null * @return A new {@link YangStatementStreamSource} */ public static YangStatementStreamSource create(final ASTSchemaSource source) { final ParserRuleContext ast = source.getAST(); checkArgument(ast instanceof StatementContext, "Unsupported context class %s for source %s", ast.getClass(), source.getIdentifier()); return create(source.getIdentifier(), (StatementContext) ast, source.getSymbolicName().orElse(null)); }
Example #18
Source File: TreeExpressionEvaluator.java From yauaa with Apache License 2.0 | 5 votes |
public TreeExpressionEvaluator(ParserRuleContext requiredPattern, Matcher matcher, boolean verbose) { this.requiredPatternText = requiredPattern.getText(); this.matcher = matcher; this.verbose = verbose; this.fixedValue = calculateFixedValue(requiredPattern); walkList = new WalkList(requiredPattern, matcher.getLookups(), matcher.getLookupSets(), verbose); }
Example #19
Source File: Trainer.java From codebuff with BSD 2-Clause "Simplified" License | 5 votes |
public static TerminalNode getMatchingLeftSymbol(Corpus corpus, InputDocument doc, TerminalNode node) { ParserRuleContext parent = (ParserRuleContext)node.getParent(); int curTokensParentRuleIndex = parent.getRuleIndex(); Token curToken = node.getSymbol(); if (corpus.ruleToPairsBag != null) { String ruleName = doc.parser.getRuleNames()[curTokensParentRuleIndex]; RuleAltKey ruleAltKey = new RuleAltKey(ruleName, parent.getAltNumber()); List<Pair<Integer, Integer>> pairs = corpus.ruleToPairsBag.get(ruleAltKey); if ( pairs!=null ) { // Find appropriate pair given current token // If more than one pair (a,b) with b=current token pick first one // or if a common pair like ({,}), then give that one preference. // or if b is punctuation, prefer a that is punct List<Integer> viableMatchingLeftTokenTypes = viableLeftTokenTypes(parent, curToken, pairs); Vocabulary vocab = doc.parser.getVocabulary(); if ( !viableMatchingLeftTokenTypes.isEmpty() ) { int matchingLeftTokenType = CollectTokenPairs.getMatchingLeftTokenType(curToken, viableMatchingLeftTokenTypes, vocab); List<TerminalNode> matchingLeftNodes = parent.getTokens(matchingLeftTokenType); // get matching left node by getting last node to left of current token List<TerminalNode> nodesToLeftOfCurrentToken = filter(matchingLeftNodes, n -> n.getSymbol().getTokenIndex()<curToken.getTokenIndex()); TerminalNode matchingLeftNode = nodesToLeftOfCurrentToken.get(nodesToLeftOfCurrentToken.size()-1); if (matchingLeftNode == null) { System.err.println("can't find matching node for "+node.getSymbol()); } return matchingLeftNode; } } } return null; }
Example #20
Source File: JsonModelResolver.java From netbeans with Apache License 2.0 | 5 votes |
@NonNull private static OffsetRange createOffsetRange(@NonNull final ParserRuleContext parseTree) { int start = parseTree.start.getStartIndex(); int end = parseTree.stop.getStopIndex() +1; if (end <= start) { end = start + 1; LOG.log( Level.FINE, "ParseTree.start offset is bigger then end offset [{0}, {1}]", //NOI18N new Object[]{parseTree.start.getStartIndex(), parseTree.stop.getStopIndex()}); } return new OffsetRange( start, end); }
Example #21
Source File: NxosControlPlaneExtractor.java From batfish with Apache License 2.0 | 5 votes |
@Override public void processParseTree(NetworkSnapshot snapshot, ParserRuleContext tree) { ParseTreeWalker walker = new BatfishParseTreeWalker(_parser); // extract metadata and set defaults walker.walk(new CiscoNxosPreprocessor(_text, _parser, _w, _configuration), tree); // build the configuration walker.walk(new CiscoNxosControlPlaneExtractor(_text, _parser, _w, _configuration), tree); }
Example #22
Source File: OrderbyClauseParser.java From PoseidonX with Apache License 2.0 | 5 votes |
/** * {@inheritDoc} */ @Override public ParseContext parse(String cql) throws ParseException { LOG.info("start to parse cql : {}", cql); CQLErrorListener errorListener = new CQLErrorListener(); CQLLexer lexer = new CQLLexer(new ANTLRIgnoreCaseStringStream(cql)); lexer.removeErrorListeners(); lexer.addErrorListener(errorListener); CommonTokenStream tokens = new CommonTokenStream(lexer); CQLParser parser = new CQLParser(tokens); CQLErrorStrategy errorHandler = new CQLErrorStrategy(); parser.setErrorHandler(errorHandler); parser.removeErrorListeners(); parser.addErrorListener(errorListener); ParserRuleContext tree = parser.columnNameOrderList(); if (errorListener.getRecException() != null) { errorListener.getRecException().setCql(cql); throw errorListener.getRecException(); } LOG.info("Parse Completed"); OrderbyClauseVisitor visitor = new OrderbyClauseVisitor(); return visitor.visit(tree); }
Example #23
Source File: InlinePyEvalDef.java From bookish with MIT License | 5 votes |
public InlinePyEvalDef(ParserRuleContext tree, String inputFilename, int index, BookishParser.AttrsContext attrsCtx, String code) { super(tree, inputFilename, index, attrsCtx, code); this.isCodeVisible = false; displayExpr = code; this.code = null; }
Example #24
Source File: ParseUtil.java From datacollector with Apache License 2.0 | 5 votes |
public static ParserRuleContext getParserRuleContext( String queryString, int op ) throws UnparseableSQLException { plsqlLexer lexer = new plsqlLexer(new ANTLRInputStream(queryString)); CommonTokenStream tokenStream = new CommonTokenStream(lexer); plsqlParser parser = new plsqlParser(tokenStream); ParserRuleContext context = null; switch (op) { case OracleCDCOperationCode.UPDATE_CODE: case OracleCDCOperationCode.SELECT_FOR_UPDATE_CODE: context = parser.update_statement(); break; case OracleCDCOperationCode.INSERT_CODE: context = parser.insert_statement(); break; case OracleCDCOperationCode.DELETE_CODE: context = parser.delete_statement(); break; case OracleCDCOperationCode.DDL_CODE: case OracleCDCOperationCode.COMMIT_CODE: case OracleCDCOperationCode.ROLLBACK_CODE: break; default: throw new UnparseableSQLException(queryString); } return context; }
Example #25
Source File: Trainer.java From codebuff with BSD 2-Clause "Simplified" License | 5 votes |
/** Return the number of hops to get to ancestor from node or -1 if we * don't find ancestor on path to root. */ public static int getDeltaToAncestor(ParserRuleContext node, ParserRuleContext ancestor) { int n = 0; ParserRuleContext p = node; while ( p!=null && p!=ancestor ) { n++; p = p.getParent(); } if ( p==null ) return -1; return n; }
Example #26
Source File: ZoneOffsetVisitor.java From incubator-tuweni with Apache License 2.0 | 5 votes |
private static ZoneOffset toZoneOffset(int hours, int minutes, ParserRuleContext ctx, int offset) { try { return ZoneOffset.ofHoursMinutes(hours, (hours < 0) ? -minutes : minutes); } catch (DateTimeException e) { throw new TomlParseError("Invalid zone offset (valid range -18:00..+18:00)", new TomlPosition(ctx, offset), e); } }
Example #27
Source File: UserAgentGetChildrenVisitor.java From yauaa with Apache License 2.0 | 5 votes |
@Override public Iterator<? extends ParseTree> visitProductNameKeyValue(ProductNameKeyValueContext ctx) { switch (name) { case "key": return Collections.singletonList((ParserRuleContext) ctx.key).iterator(); case "value": List<? extends ParserRuleContext> children = ctx.multipleWords(); if (!children.isEmpty()) { return children.iterator(); } children = ctx.keyValueProductVersionName(); if (!children.isEmpty()) { return children.iterator(); } children = ctx.siteUrl(); if (!children.isEmpty()) { return children.iterator(); } children = ctx.emailAddress(); if (!children.isEmpty()) { return children.iterator(); } children = ctx.uuId(); return children.iterator(); default: return getChildrenByName(ctx); } }
Example #28
Source File: BuiltinFunctionExpression.java From systemds with Apache License 2.0 | 5 votes |
public BuiltinFunctionExpression(ParserRuleContext ctx, Builtins bifop, ArrayList<ParameterExpression> args, String fname) { _opcode = bifop; setCtxValuesAndFilename(ctx, fname); args = expandDnnArguments(args); _args = new Expression[args.size()]; for(int i=0; i < args.size(); i++) { _args[i] = args.get(i).getExpr(); } }
Example #29
Source File: AstBuilder.java From crate with Apache License 2.0 | 5 votes |
@Nullable private <T> T visitOptionalContext(@Nullable ParserRuleContext context, Class<T> clazz) { if (context != null) { return clazz.cast(visit(context)); } return null; }
Example #30
Source File: ContentUriChecker.java From kripton with Apache License 2.0 | 5 votes |
/** * Replace internal from uri. * * @param input the input * @param replace the replace * @param rewriterListener the rewriter listener * @return the string */ private String replaceInternalFromUri(String input, final List<Triple<Token, Token, String>> replace, UriBaseListener rewriterListener) { Pair<ParserRuleContext, CommonTokenStream> parser = prepareUri(input); pathSegmentIndex = -1; walker.walk(rewriterListener, parser.value0); TokenStreamRewriter rewriter = new TokenStreamRewriter(parser.value1); for (Triple<Token, Token, String> item : replace) { rewriter.replace(item.value0, item.value1, item.value2); } return rewriter.getText(); }