Example usage for org.antlr.v4.runtime ParserRuleContext getParent

List of usage examples for org.antlr.v4.runtime ParserRuleContext getParent

Introduction

In this page you can find the example usage for org.antlr.v4.runtime ParserRuleContext getParent.

Prototype

@Override
    
    public ParserRuleContext getParent() 

Source Link

Usage

From source file:PostParser.java

License:Open Source License

/**
 * {@inheritDoc}/*from   ww w  .j  av a  2s  .  c om*/
 *
 * <p>Parsing Span nodes is a complete mess. This method essentially reparses
 * node sequences of the form expr? (;; expr?)+.</p>
 */
public void rewriteSpan(ParserRuleContext ctx) {
    ArrayList<Integer> opIndex = new ArrayList<Integer>();
    ArrayList<Integer> spanExpressions = new ArrayList<Integer>();

    FoxySheepParser.SpanAContext span;

    int i, j, nextOp;

    //Identify locations of ";;".
    for (i = 0; i < ctx.children.size(); i++) {
        if (ctx.children.get(i).getText().equals(";;")) {
            opIndex.add(i);
        }
    }

    for (i = 0, nextOp = 0; i < ctx.children.size() && nextOp < opIndex.size(); i++, nextOp++) {
        //The index i always points to the first child in a Span expression,
        //and index j always points to the current child of the current span
        //expression.
        j = i; //We are at the beginning of a span expression.
        //We move j to the end of this span expression by looking for a second ";;".

        if (nextOp + 1 < opIndex.size() //There is a next ";;"
                && opIndex.get(nextOp + 1) + 1 < ctx.children.size() //There is a node after the next ";;"
                && ctx.children.get(opIndex.get(nextOp + 1) + 1) instanceof FoxySheepParser.ExprContext) {
            //There is a second ";;" followed by an expr. 
            i = opIndex.get(nextOp + 1) + 1;
            spanExpressions.add(i);
            nextOp++; //We want nextOp to end at the last ";;" of the current expression.
        } else {
            //There is no second ";;" belonging to this expression.
            if (opIndex.get(nextOp) + 1 < ctx.children.size() //There is a node after ";;"
                    && ctx.children.get(opIndex.get(nextOp) + 1) instanceof FoxySheepParser.ExprContext) {
                //This span expression ends in an expr.
                i = opIndex.get(nextOp) + 1;
                spanExpressions.add(i);
            } else {
                //This span expression ends in the current ";;".
                i = opIndex.get(nextOp);
                spanExpressions.add(i);
            }
        }
    } //end for

    //At this point spanExpressions holds the index of the last child of each span expression. It might be
    //that after all of this there is nothing to do.
    if (spanExpressions.size() == 1)
        return;
    //Otherwise there is more than one span expression, and we need to rewrite the tree replacing the 
    //Span?Context this method was invoked on with a TimesContext.
    FoxySheepParser.TimesContext timesctx = new FoxySheepParser.TimesContext((FoxySheepParser.ExprContext) ctx);
    //How much of the following is necessary?
    timesctx.children = new ArrayList<ParseTree>();
    timesctx.parent = ctx.parent;

    //Add each span expression as a child to timesctx.
    for (i = 0, j = 0; i < spanExpressions.size(); i++) {
        //i is the index of the current span expression in spanExpressions, 
        //and j is the index to the beginning of the new span expressions children in ctx.children.
        //We make new SpanAContext objects for each span expression.
        span = new FoxySheepParser.SpanAContext((FoxySheepParser.ExprContext) ctx);
        //How much of this is necessary?
        span.children = new ArrayList<ParseTree>();
        span.parent = timesctx;
        for (int n = j; n <= spanExpressions.get(i); n++) {
            span.children.add(ctx.children.get(n));
        }
        timesctx.children.add(span);
        //update j to be the beginning of the next expression.
        j = spanExpressions.get(i) + 1;
    }

    //Finally, detach the span this method was invoked on from its parent and replace with the TimesContext.
    if (ctx.getParent() != null) {
        List<ParseTree> parentsChildren = ctx.getParent().children;
        parentsChildren.add(parentsChildren.indexOf(ctx), timesctx);
        parentsChildren.remove(ctx);
    }
    ctx.parent = timesctx;
    //...I think that's it.
}

From source file:android.databinding.tool.store.LayoutFileParser.java

License:Apache License

private void parseExpressions(String newTag, final XMLParser.ElementContext rootView, final boolean isMerge,
        ResourceBundle.LayoutFileBundle bundle) {
    final List<XMLParser.ElementContext> bindingElements = new ArrayList<>();
    final List<XMLParser.ElementContext> otherElementsWithIds = new ArrayList<>();
    rootView.accept(new XMLParserBaseVisitor<Void>() {
        @Override//from   w  w w  .  jav a  2  s  .c  o  m
        public Void visitElement(@NotNull XMLParser.ElementContext ctx) {
            if (filter(ctx)) {
                bindingElements.add(ctx);
            } else {
                String name = ctx.elmName.getText();
                if (!"include".equals(name) && !"fragment".equals(name)
                        && attributeMap(ctx).containsKey("android:id")) {
                    otherElementsWithIds.add(ctx);
                }
            }
            visitChildren(ctx);
            return null;
        }

        private boolean filter(XMLParser.ElementContext ctx) {
            if (isMerge) {
                // account for XMLParser.ContentContext
                if (ctx.getParent().getParent() == rootView) {
                    return true;
                }
            } else if (ctx == rootView) {
                return true;
            }
            if (hasIncludeChild(ctx)) {
                return true;
            }
            if (XmlEditor.hasExpressionAttributes(ctx)) {
                return true;
            }
            return false;
        }

        private boolean hasIncludeChild(XMLParser.ElementContext ctx) {
            for (XMLParser.ElementContext child : XmlEditor.elements(ctx)) {
                if ("include".equals(child.elmName.getText())) {
                    return true;
                }
            }
            return false;
        }
    });

    final HashMap<XMLParser.ElementContext, String> nodeTagMap = new HashMap<XMLParser.ElementContext, String>();
    L.d("number of binding nodes %d", bindingElements.size());
    int tagNumber = 0;
    for (XMLParser.ElementContext parent : bindingElements) {
        final Map<String, String> attributes = attributeMap(parent);
        String nodeName = parent.elmName.getText();
        String viewName = null;
        String includedLayoutName = null;
        final String id = attributes.get("android:id");
        final String tag;
        final String originalTag = attributes.get("android:tag");
        if ("include".equals(nodeName)) {
            // get the layout attribute
            final String includeValue = attributes.get("layout");
            if (StringUtils.isEmpty(includeValue)) {
                L.e("%s must include a layout", parent);
            }
            if (!includeValue.startsWith(LAYOUT_PREFIX)) {
                L.e("included value (%s) must start with %s.", includeValue, LAYOUT_PREFIX);
            }
            // if user is binding something there, there MUST be a layout file to be
            // generated.
            String layoutName = includeValue.substring(LAYOUT_PREFIX.length());
            includedLayoutName = layoutName;
            final ParserRuleContext myParentContent = parent.getParent();
            Preconditions.check(myParentContent instanceof XMLParser.ContentContext,
                    "parent of an include tag must be a content context but it is %s",
                    myParentContent.getClass().getCanonicalName());
            final ParserRuleContext grandParent = myParentContent.getParent();
            Preconditions.check(grandParent instanceof XMLParser.ElementContext,
                    "grandparent of an include tag must be an element context but it is %s",
                    grandParent.getClass().getCanonicalName());
            //noinspection SuspiciousMethodCalls
            tag = nodeTagMap.get(grandParent);
        } else if ("fragment".equals(nodeName)) {
            L.e("fragments do not support data binding expressions.");
            continue;
        } else {
            viewName = getViewName(parent);
            // account for XMLParser.ContentContext
            if (rootView == parent || (isMerge && parent.getParent().getParent() == rootView)) {
                tag = newTag + "_" + tagNumber;
            } else {
                tag = "binding_" + tagNumber;
            }
            tagNumber++;
        }
        final ResourceBundle.BindingTargetBundle bindingTargetBundle = bundle.createBindingTarget(id, viewName,
                true, tag, originalTag, new Location(parent));
        nodeTagMap.put(parent, tag);
        bindingTargetBundle.setIncludedLayout(includedLayoutName);

        for (XMLParser.AttributeContext attr : XmlEditor.expressionAttributes(parent)) {
            String value = escapeQuotes(attr.attrValue.getText(), true);
            if (value.charAt(0) == '@' && value.charAt(1) == '{' && value.charAt(value.length() - 1) == '}') {
                final String strippedValue = value.substring(2, value.length() - 1);
                Location attrLocation = new Location(attr);
                Location valueLocation = new Location();
                // offset to 0 based
                valueLocation.startLine = attr.attrValue.getLine() - 1;
                valueLocation.startOffset = attr.attrValue.getCharPositionInLine()
                        + attr.attrValue.getText().indexOf(strippedValue);
                valueLocation.endLine = attrLocation.endLine;
                valueLocation.endOffset = attrLocation.endOffset - 2; // account for: "}
                bindingTargetBundle.addBinding(escapeQuotes(attr.attrName.getText(), false), strippedValue,
                        attrLocation, valueLocation);
            }
        }
    }

    for (XMLParser.ElementContext elm : otherElementsWithIds) {
        final String id = attributeMap(elm).get("android:id");
        final String className = getViewName(elm);
        bundle.createBindingTarget(id, className, true, null, null, new Location(elm));
    }
}

From source file:codemate.Fortran.FortranDepend.java

License:Open Source License

private boolean isDependMacro(ParserRuleContext ctx) {
    if (ctx.getParent() instanceof CppDirectiveContext) {
        ParserRuleContext mark = ctx.getParent();
        ParserRuleContext parent = mark.getParent();
        if (parent instanceof UseStatementsContext) {
            if (parent.children.get(parent.children.size() - 1) != mark)
                return true;
            else/* w ww . j a  va 2  s. com*/
                return false;
        }
    }
    return false;
}

From source file:codemate.Fortran.FortranTemplater.java

License:Open Source License

@SuppressWarnings("unused")
private Stack<ParserRuleContext> findRoute(ParserRuleContext startNode, int endNodeRuleIndex) {
    Stack<ParserRuleContext> route = new Stack<ParserRuleContext>();
    ParserRuleContext node = startNode;
    boolean isFound = false;
    while (!isFound && node != null) {
        route.push(node);//ww  w. j a  va2 s .  c  o  m
        if (node.getRuleIndex() == endNodeRuleIndex)
            isFound = true;
        else
            for (ParseTree child : node.children)
                if (child instanceof ParserRuleContext) {
                    if (((ParserRuleContext) child).getRuleIndex() == endNodeRuleIndex) {
                        route.pop(); // throw the useless parent node away
                        route.push((ParserRuleContext) child);
                        // I push a null into the stack to indicate that
                        // the end node is a sibling node.
                        route.push(null);
                        isFound = true;
                        break;
                    }
                }
        if (!isFound)
            node = node.getParent();
    }
    if (false) {
        if (route.lastElement() != null)
            System.out.println("Route (local):");
        else
            System.out.println("Route (non-local):");
        for (ParserRuleContext node_ : route)
            if (node_ != null)
                System.out.println("* " + FortranParser.ruleNames[node_.getRuleIndex()]);
    }
    return route;
}

From source file:com.espertech.esper.epl.parse.ASTUtil.java

License:Open Source License

public static boolean isRecursiveParentRule(ParserRuleContext ctx, Set<Integer> rulesIds) {
    ParserRuleContext parent = ctx.getParent();
    if (parent == null) {
        return false;
    }/*from   w  w  w  .  j av  a2  s  . co  m*/
    return rulesIds.contains(parent.getRuleIndex()) || isRecursiveParentRule(parent, rulesIds);
}

From source file:com.googlecode.cqengine.query.parser.common.ParserUtils.java

License:Apache License

/**
 * 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
 */// w w  w.j  a v a  2s . c  o  m
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;
}

From source file:com.googlecode.cqengine.query.parser.cqnative.support.NativeQueryAntlrListener.java

License:Apache License

/**
 * 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
 *//*from  www  .j a  v  a2  s.co m*/
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;
}

From source file:com.satisfyingstructures.J2S.J2SConverter.java

License:Open Source License

@Override
public void exitExplicitConstructorInvocation(Java8Parser.ExplicitConstructorInvocationContext ctx) {
    TerminalNode tn;//w  ww . j  a va 2  s.  co m
    if (null != (tn = ctx.getToken(Java8Parser.THIS, 0))) {
        //  'this' within explicit constructor invocation is calling sideways to another constructor, which implies we are a convenience constructor
        rewriter.replace(tn, "self.init");
        // put 'convenience' before type name in our constructor declarator
        ParserRuleContext context;
        if (null != (context = ctx.getParent())) // constructorBody
            if (null != (context = context.getParent())) // constructorDeclaration
                if (null != (context = context.getChild(Java8Parser.ConstructorDeclaratorContext.class, 0)))
                    if (null != (context = context.getChild(Java8Parser.SimpleTypeNameContext.class, 0)))
                        rewriter.insertBefore(context, "convenience ");
    } else if (null != (tn = ctx.getToken(Java8Parser.SUPER, 0))) {
        rewriter.replace(tn, "super.init");
    }
}

From source file:com.satisfyingstructures.J2S.J2SConverter.java

License:Open Source License

private void addBracesAroundStatementIfNecessary(ParserRuleContext ctx) {
    // Ensure the statement(s) with if(else), for, while and do is always wrapped in braces.
    // At the same time, remove the parentheses around the test/control part for the statement
    int statementRule = ctx.getRuleIndex();
    if (statementRule != Java8Parser.RULE_statement && statementRule != Java8Parser.RULE_statementNoShortIf)
        return; // not our expected parameter type
    ParserRuleContext parent = ctx.getParent();
    int parentRule = parent.getRuleIndex();
    switch (parentRule) {
    case Java8Parser.RULE_ifThenElseStatement:
    case Java8Parser.RULE_ifThenElseStatementNoShortIf: {
        // if this statement is an ifThen or an ifThenElse sitting within an ifThenElse, then 
        // check if it follows the else, because we don't wrap the trailing 'if' part of 'else if'
        int statementSubRule = ctx.getChild(ParserRuleContext.class, 0).getRuleIndex();
        if (statementSubRule == Java8Parser.RULE_ifThenStatement
                || statementSubRule == Java8Parser.RULE_ifThenElseStatement
                || statementSubRule == Java8Parser.RULE_ifThenElseStatementNoShortIf) {
            // the statement after else is the last child
            if (parent.getChild(parent.getChildCount() - 1) == ctx)
                break;
        }/*w  w w.  ja  v  a 2 s  .  co  m*/
    }
    // fallthru
    case Java8Parser.RULE_ifThenStatement:
    case Java8Parser.RULE_basicForStatement:
    case Java8Parser.RULE_basicForStatementNoShortIf:
    case Java8Parser.RULE_enhancedForStatement:
    case Java8Parser.RULE_enhancedForStatementNoShortIf:
    case Java8Parser.RULE_whileStatement:
    case Java8Parser.RULE_whileStatementNoShortIf:
    case Java8Parser.RULE_doStatement:
        if (ctx.start.getType() != Java8Parser.LBRACE) {
            rewriter.insertBefore(ctx.start, "{ ");
            // rewriter.insertAfter( ctx.stop, " }" );
            // ...we don't insert, because it binds to the following token and we may need to change/modify it
            // higher up the stack. Instead, we replace the current content of the stop token. This is necessary
            // because the stop can be the end of more than one statement, e.g. last semicolon in...
            //  for(;;i++)
            //      if (i%7)
            //          break;
            // ...gets wrapped twice to give
            //  for(;;i++)
            //      { if (i%7)
            //          { break; } }
            String current = rewriter.getText(ctx.stop);
            rewriter.replace(ctx.stop, current + " }");
        }
        break;
    default:
        return;
    }

    // Remove the parentheses around the test/control part for the statement
    removeParenthesesAroundExpression(parent);
}

From source file:com.sqatntu.metrics.listener.DepthOfConditionNestingListener.java

License:Open Source License

@Override
public void enterStatement(JavaParser.StatementContext ctx) {
    ctx.getChildCount();/*from  w w  w. j  a va 2  s . c  o m*/
    String text = ctx.getStart().getText();
    if (!text.equals("if") && !text.equals("while") && !text.equals("for") && !text.equals("do")) {
        return;
    }

    int depth = 1;
    ParserRuleContext tempContext = ctx.getParent();
    while (!(tempContext instanceof JavaParser.MethodDeclarationContext)) {
        if (tempContext instanceof JavaParser.StatementContext) {
            text = tempContext.getStart().getText();
            if (text.equals("if") || text.equals("while") || text.equals("for") || text.equals("do")) {
                depth++;
            }
        }
        tempContext = tempContext.getParent();
    }
    report.setDepthOfConditionNesting(depth);
}