Java Code Examples for org.antlr.v4.runtime.ParserRuleContext#getParent()
The following examples show how to use
org.antlr.v4.runtime.ParserRuleContext#getParent() .
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: Trainer.java From codebuff with BSD 2-Clause "Simplified" License | 6 votes |
/** Walk upwards from node until we find a child of p at t's char position. * Don't see alignment with self, t, or element *after* us. * return null if there is no such ancestor p. */ public static Pair<ParserRuleContext,Integer> earliestAncestorWithChildStartingAtCharPos(ParserRuleContext node, Token t, int charpos) { ParserRuleContext p = node; while ( p!=null ) { // check all children of p to see if one of them starts at charpos for (int i = 0; i<p.getChildCount(); i++) { ParseTree child = p.getChild(i); Token start; if ( child instanceof ParserRuleContext ) { start = ((ParserRuleContext) child).getStart(); } else { // must be token start = ((TerminalNode)child).getSymbol(); } // check that we don't see alignment with self or element *after* us if ( start.getTokenIndex()<t.getTokenIndex() && start.getCharPositionInLine()==charpos ) { return new Pair<>(p,i); } } p = p.getParent(); } return null; }
Example 2
Source File: ParseTreeToAst.java From turin-programming-language with Apache License 2.0 | 6 votes |
private Expression toAst(TurinParser.PlaceholderUsageContext ctx) { ParserRuleContext parent = ctx.getParent(); String fieldName = null; while (parent != null && fieldName == null) { if (parent instanceof TurinParser.InTypePropertyDeclarationContext) { fieldName = idText(((TurinParser.InTypePropertyDeclarationContext)parent).name); } else { parent = parent.getParent(); } } if (fieldName == null) { return new SemanticError("A placeholder should be used only inside in-type property declarations", getPosition(ctx)); } else { Placeholder placeholder = new Placeholder(); getPositionFrom(placeholder, ctx); return placeholder; } }
Example 3
Source File: ParseTreeToAst.java From turin-programming-language with Apache License 2.0 | 6 votes |
private Expression toAst(TurinParser.PlaceholderNameUsageContext ctx) { ParserRuleContext parent = ctx.getParent(); String fieldName = null; while (parent != null && fieldName == null) { if (parent instanceof TurinParser.InTypePropertyDeclarationContext) { fieldName = idText(((TurinParser.InTypePropertyDeclarationContext)parent).name); } else { parent = parent.getParent(); } } if (fieldName == null) { return new SemanticError("A placeholder should be used only inside in-type property declarations", getPosition(ctx)); } else { StringLiteral stringLiteral = new StringLiteral(fieldName); getPositionFrom(stringLiteral, ctx); return stringLiteral; } }
Example 4
Source File: ParseTreePrettyPrinter.java From batfish with Apache License 2.0 | 6 votes |
@Override public void enterEveryRule(ParserRuleContext ctx) { if (ctx != _ctx) { _ptSentences.getSentences().add(""); } for (int i = 0; i < _indent; i++) { _ptSentences.appendToLastSentence(" "); } String ruleName = _ruleNames.get(ctx.getRuleIndex()); if (ctx.getParent() != null) { for (Field f : ctx.getParent().getClass().getFields()) { try { if (!f.getName().equals(ruleName) && f.get(ctx.getParent()) == ctx) { _ptSentences.appendToLastSentence(f.getName() + " = "); } } catch (Throwable t) { // Ignore the error and continue. } } } _ptSentences.appendToLastSentence("(" + ruleName); _indent++; }
Example 5
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 6
Source File: PomListener.java From depends with MIT License | 5 votes |
private String getParentElementName(ParserRuleContext node) { node = node.getParent(); if (node == null) return "project"; node = node.getParent(); if (!(node instanceof ElementContext)) return "project"; ElementContext p = (ElementContext) node; String name = p.Name().get(0).getText(); return name; }
Example 7
Source File: Trainer.java From codebuff with BSD 2-Clause "Simplified" License | 5 votes |
/** Return first ancestor of p that is not an only child including p. * So if p.getParent().getChildCount()>1, this returns p. If we * have found a chain rule at p's parent (p is its only child), then * move p to its parent and try again. */ public static ParserRuleContext getParentClosure(ParserRuleContext p) { if ( p==null ) return null; // if p not an only child, return p if ( p.getParent()==null || p.getParent().getChildCount()>1 ) return p; // we found a chain rule node return getParentClosure(p.getParent()); }
Example 8
Source File: Trainer.java From codebuff with BSD 2-Clause "Simplified" License | 5 votes |
/** Walk upwards from node while p.start == token; return immediate parent * if there is no ancestor starting at token. This is the earliest * left ancestor. E.g, for '{' of a block, return parent up the chain from * block starting with '{'. For '}' of block, return just block as nothing * starts with '}'. (block stops with it). */ public static ParserRuleContext earliestAncestorStartingWithToken(TerminalNode node) { Token token = node.getSymbol(); ParserRuleContext p = (ParserRuleContext)node.getParent(); ParserRuleContext prev = null; while (p!=null && p.getStart()==token) { prev = p; p = p.getParent(); } if ( prev==null ) { return (ParserRuleContext)node.getParent(); } return prev; }
Example 9
Source File: Trainer.java From codebuff with BSD 2-Clause "Simplified" License | 5 votes |
/** Walk upwards from node while p.stop == token; return immediate parent * if there is no ancestor stopping at token. This is the earliest * right ancestor. E.g, for '}' of a block, return parent up the chain from * block stopping with '}'. For '{' of block, return just block as nothing * stops with '{'. (block starts with it). */ public static ParserRuleContext earliestAncestorEndingWithToken(TerminalNode node) { Token token = node.getSymbol(); ParserRuleContext p = (ParserRuleContext)node.getParent(); ParserRuleContext prev = null; while (p!=null && p.getStop()==token) { prev = p; p = p.getParent(); } if ( prev==null ) { return (ParserRuleContext)node.getParent(); } return prev; }
Example 10
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 11
Source File: Trainer.java From codebuff with BSD 2-Clause "Simplified" License | 5 votes |
public static ParserRuleContext getAncestor(ParserRuleContext node, int delta) { int n = 0; ParserRuleContext p = node; while ( p!=null && n!=delta ) { n++; p = p.getParent(); } return p; }
Example 12
Source File: ParserUtils.java From cqengine with Apache License 2.0 | 5 votes |
/** * Examines the parent rule contexts of the given context, and returns the first parent context which is assignable * from (i.e. is a, or is a subclass of) one of the given context types. * @param currentContext The starting context whose parent contexts should be examined * @param parentContextTypes The types of parent context sought * @return The first parent context which is assignable from one of the given context types, * or null if there is no such parent in the tree */ public static ParserRuleContext getParentContextOfType(ParserRuleContext currentContext, Class<?>... parentContextTypes) { while (currentContext != null) { currentContext = currentContext.getParent(); if (currentContext != null) { for (Class<?> parentContextType : parentContextTypes) { if (parentContextType.isAssignableFrom(currentContext.getClass())) { return currentContext; } } } } return null; }
Example 13
Source File: QueryExprListener.java From ameba with MIT License | 5 votes |
/** * <p>getParentSourceElement.</p> * * @param node a {@link org.antlr.v4.runtime.ParserRuleContext} object. * @return a {@link org.antlr.v4.runtime.ParserRuleContext} object. */ protected ParserRuleContext getParentSourceElement(ParserRuleContext node) { if (node == null) return null; ParserRuleContext parent = node.getParent(); if (parent instanceof QueryParser.SourceElementContext) { return parent; } return getParentSourceElement(parent); }
Example 14
Source File: ExpressionUsage.java From depends with MIT License | 4 votes |
public void foundExpression(ParserRuleContext ctx) { if (!isStartOfContainerRule(ctx)) { return ; } if (context.lastContainer().containsExpression(ctx)) return; if (ctx.getParent() instanceof TrailerContext) return; Expression parent = findParentInStack(ctx); Expression expression = parent; if (ctx.getParent().getChildCount()==1 && parent!=null) { //如果就是自己,则无需创建新的Expression }else { /* create expression and link it with parent*/ expression = new Expression(idGenerator.generateId()); expression.setText(ctx.getText()); context.lastContainer().addExpression(ctx,expression); expression.setParent(parent); } if (ctx instanceof Expr_stmtContext) { Expr_stmtContext exprAssign = (Expr_stmtContext)ctx; if (exprAssign.assign_part()!=null) { expression.setSet(true); expression.setIdentifier(exprAssign.testlist_star_expr().getText()); if (isValidIdentifier(expression.getIdentifier())) { makeSureVarExist(expression.getIdentifier()); } deduceVarTypeInCaseOfAssignment((Expr_stmtContext)ctx,expression); } } if (ctx instanceof Raise_stmtContext) { expression.setThrow (true); } if (ctx instanceof Return_stmtContext) { deduceReturnTypeInCaseOfReturn((Return_stmtContext)ctx,expression); } if (ctx instanceof ExprContext) { processExprContext((ExprContext)ctx, expression); } }
Example 15
Source File: Trainer.java From codebuff with BSD 2-Clause "Simplified" License | 4 votes |
/** Get the token type and tree ancestor features. These are computed * the same for both training and formatting. */ public static int[] getContextFeatures(Corpus corpus, Map<Token, TerminalNode> tokenToNodeMap, InputDocument doc, int i) { int[] features = new int[NUM_FEATURES]; CodeBuffTokenStream tokens = doc.tokens; TerminalNode node = tokenToNodeMap.get(tokens.get(i)); if ( node==null ) { System.err.println("### No node associated with token "+tokens.get(i)); return features; } Token curToken = node.getSymbol(); // Get context information for previous token Token prevToken = tokens.getPreviousRealToken(i); TerminalNode prevNode = tokenToNodeMap.get(prevToken); ParserRuleContext prevEarliestRightAncestor = earliestAncestorEndingWithToken(prevNode); int prevEarliestAncestorRuleIndex = prevEarliestRightAncestor.getRuleIndex(); int prevEarliestAncestorRuleAltNum = prevEarliestRightAncestor.getAltNumber(); // Get context information for current token ParserRuleContext earliestLeftAncestor = earliestAncestorStartingWithToken(node); ParserRuleContext earliestLeftAncestorParent = earliestLeftAncestor!=null ? earliestLeftAncestor.getParent() : null; ParserRuleContext earliestLeftAncestorParent2 = earliestLeftAncestorParent!=null ? earliestLeftAncestorParent.getParent() : null; ParserRuleContext earliestLeftAncestorParent3 = earliestLeftAncestorParent2!=null ? earliestLeftAncestorParent2.getParent() : null; ParserRuleContext earliestLeftAncestorParent4 = earliestLeftAncestorParent3!=null ? earliestLeftAncestorParent3.getParent() : null; ParserRuleContext earliestLeftAncestorParent5 = earliestLeftAncestorParent4!=null ? earliestLeftAncestorParent4.getParent() : null; features[INDEX_PREV_TYPE] = prevToken.getType(); features[INDEX_PREV_EARLIEST_RIGHT_ANCESTOR] = rulealt(prevEarliestAncestorRuleIndex,prevEarliestAncestorRuleAltNum); features[INDEX_CUR_TOKEN_TYPE] = curToken.getType(); features[INDEX_CUR_TOKEN_CHILD_INDEX] = getChildIndexOrListMembership(node); features[INDEX_EARLIEST_LEFT_ANCESTOR] = rulealt(earliestLeftAncestor); features[INDEX_ANCESTORS_CHILD_INDEX] = getChildIndexOrListMembership(earliestLeftAncestor); features[INDEX_ANCESTORS_PARENT_RULE] = earliestLeftAncestorParent!=null ? rulealt(earliestLeftAncestorParent) : -1; features[INDEX_ANCESTORS_PARENT_CHILD_INDEX] = getChildIndexOrListMembership(earliestLeftAncestorParent); features[INDEX_ANCESTORS_PARENT2_RULE] = earliestLeftAncestorParent2!=null ? rulealt(earliestLeftAncestorParent2) : -1; features[INDEX_ANCESTORS_PARENT2_CHILD_INDEX] = getChildIndexOrListMembership(earliestLeftAncestorParent2); features[INDEX_ANCESTORS_PARENT3_RULE] = earliestLeftAncestorParent3!=null ? rulealt(earliestLeftAncestorParent3) : -1; features[INDEX_ANCESTORS_PARENT3_CHILD_INDEX] = getChildIndexOrListMembership(earliestLeftAncestorParent3); features[INDEX_ANCESTORS_PARENT4_RULE] = earliestLeftAncestorParent4!=null ? rulealt(earliestLeftAncestorParent4) : -1; features[INDEX_ANCESTORS_PARENT4_CHILD_INDEX] = getChildIndexOrListMembership(earliestLeftAncestorParent4); features[INDEX_ANCESTORS_PARENT5_RULE] = earliestLeftAncestorParent5!=null ? rulealt(earliestLeftAncestorParent5) : -1; features[INDEX_ANCESTORS_PARENT5_CHILD_INDEX] = getChildIndexOrListMembership(earliestLeftAncestorParent5); features[INDEX_MATCHING_TOKEN_STARTS_LINE] = getMatchingSymbolStartsLine(corpus, doc, node); features[INDEX_MATCHING_TOKEN_ENDS_LINE] = getMatchingSymbolEndsLine(corpus, doc, node); features[INDEX_INFO_FILE] = 0; // dummy; _toString() dumps filename w/o this value; placeholder for col in printout features[INDEX_INFO_LINE] = curToken.getLine(); features[INDEX_INFO_CHARPOS] = curToken.getCharPositionInLine(); return features; }
Example 16
Source File: GroovydocManager.java From groovy with Apache License 2.0 | 4 votes |
private String findDocCommentByNode(ParserRuleContext node) { if (!asBoolean(node)) { return null; } if (node instanceof GroovyParser.ClassBodyContext) { return null; } ParserRuleContext parentContext = node.getParent(); if (!asBoolean(parentContext)) { return null; } String docCommentNodeText = null; boolean sameTypeNodeBefore = false; for (ParseTree child : parentContext.children) { if (node == child) { // if no doc comment node found and no siblings of same type before the node, // try to find doc comment node of its parent if (!asBoolean((Object) docCommentNodeText) && !sameTypeNodeBefore) { return findDocCommentByNode(parentContext); } return docCommentNodeText; } if (node.getClass() == child.getClass()) { // e.g. ClassBodyDeclarationContext == ClassBodyDeclarationContext docCommentNodeText = null; sameTypeNodeBefore = true; continue; } if (!(child instanceof GroovyParser.NlsContext || child instanceof GroovyParser.SepContext)) { continue; } // doc comments are treated as NL List<? extends TerminalNode> nlList = child instanceof GroovyParser.NlsContext ? ((GroovyParser.NlsContext) child).NL() : ((GroovyParser.SepContext) child).NL(); int nlListSize = nlList.size(); if (0 == nlListSize) { continue; } for (int i = nlListSize - 1; i >= 0; i--) { String text = nlList.get(i).getText(); if (matches(text, SPACES_PATTERN)) { continue; } if (text.startsWith(GROOVYDOC_PREFIX)) { docCommentNodeText = text; } else { docCommentNodeText = null; } break; } } throw new GroovyBugError("node can not be found: " + node.getText()); // The exception should never be thrown! }