Example usage for org.antlr.v4.runtime.tree ParseTree getPayload

List of usage examples for org.antlr.v4.runtime.tree ParseTree getPayload

Introduction

In this page you can find the example usage for org.antlr.v4.runtime.tree ParseTree getPayload.

Prototype

Object getPayload();

Source Link

Document

This method returns whatever object represents the data at this note.

Usage

From source file:AST.java

License:Open Source License

private /*static*/ Object getPayload(ParseTree tree) {
    /*if (tree.getChildCount() == 0) {
    // A leaf node: return the tree's payload, which is a Token.
    return tree.getPayload();//from w  ww  . j  a v  a2  s .co  m
    }*/
    if (tree.getPayload() instanceof Token) {
        // A leaf node: return the tree's payload, which is a Token.
        return tree.getPayload();
    } else {
        // The name for parser rule `foo` will be `FooContext`. Strip `Context` and
        // lower case the first character.
        String ruleName = tree.getClass().getSimpleName().replace("Context", "");
        return Character.toLowerCase(ruleName.charAt(0)) + ruleName.substring(1);
    }
}

From source file:AST.java

License:Open Source License

private static boolean containsTokens(ParseTree node) {
    if (node.getPayload() instanceof Token) {
        return true;
    }/*from  w w w.ja v  a2s .  co m*/
    for (int i = 0; i < node.getChildCount(); i++) {
        ParseTree child = node.getChild(i);
        if (containsTokens(child)) {
            return true;
        }
    }
    return false;
}

From source file:annis.ql.parser.RawAqlListener.java

License:Apache License

private static void collectToken(ParseTree node, List<Token> token) {
    for (int i = 0; i < node.getChildCount(); i++) {
        ParseTree child = node.getChild(i);
        if (child.getPayload() instanceof Token) {
            token.add((Token) child.getPayload());
        } else {/*from  w  w  w .j  a  va 2 s .c o m*/
            collectToken(child, token);
        }
    }
}

From source file:com.khubla.jvmbasic.jvmbasicc.compiler.iterator.GenericContextIterator.java

License:Open Source License

@SuppressWarnings("unchecked")
public void interate(ParseTree parseTree, GenericContextIteratorCallback<T> genericContextIteratorCallback)
        throws Exception {
    try {// www .j  a  va  2 s. c o  m
        for (int i = 0; i < parseTree.getChildCount(); i++) {
            final ParseTree subTree = parseTree.getChild(i);
            if (null != subTree) {
                final Object o = subTree.getPayload();
                if (o.getClass() == clazz) {
                    genericContextIteratorCallback.context((T) o);
                } else {
                    /*
                     * recurse
                     */
                    interate(subTree, genericContextIteratorCallback);
                }
            }
        }
    } catch (final Exception e) {
        throw new Exception("Exception in processDATADeclarations", e);
    }
}

From source file:com.spotify.heroic.grammar.QueryListener.java

License:Apache License

@Override
public void exitString(StringContext ctx) {
    final ParseTree child = ctx.getChild(0);
    final CommonToken token = (CommonToken) child.getPayload();
    final Context c = context(ctx);

    if (token.getType() == HeroicQueryLexer.SimpleString || token.getType() == HeroicQueryLexer.Identifier) {
        push(new StringExpression(c, child.getText()));
        return;/*from  w  ww . j av  a 2 s .com*/
    }

    push(new StringExpression(c, parseQuotedString(c, child.getText())));
}

From source file:fr.inria.oak.paxquery.xparser.XQueryVisitorImplementation.java

License:Apache License

/**
 * eleConstInner//from   ww w.j a  v  a 2  s .c  o  m
 * Terminates the execution if an attribute is used in the input query as an XML value
 * i.e.: <item>@attrib</item> rather than <item attrib="@attrib"></item>
 * 
 * TODO: if a variable within an XML element stores an attribute, then we currently terminate the execution
 * (since that is illegal). What we really should do is including it in the element's XML tag as an attribute
 * e.g: <item>@attrib</item> --> <item attrib="@attrib"></item>
 */
public Void visitEleConstInner(XQueryParser.EleConstInnerContext ctx) {
    String varName;
    boolean isAggrExpr = false;
    Variable outerVarObject = null;
    for (int i = 0; i < ctx.children.size(); i++) {
        varName = null;
        ParseTree child = ctx.getChild(i);
        //decide whether we have aggrExpr or VAR
        isAggrExpr = (!(child instanceof TerminalNode)
                && child.getPayload().getClass() == XQueryParser.AggrExprContext.class) ? true : false;

        ////if VAR
        if (isAggrExpr)
            varName = ((XQueryParser.AggrExprContext) child).VAR().getText();
        else
            varName = child.getText();
        if (varName.startsWith("$") == false)
            continue;
        Variable var = varMap.getVariable(varName);
        int patternTreeIndex = XQueryUtils.findVarInPatternTree(scans, patternNodeMap, varName);

        if (subqueryLevel == -1) { //not in a subquery
            if (var != null && (patternTreeIndex != -1 || var.dataType == Variable.VariableDataType.Subquery
                    || var.dataType == Variable.VariableDataType.Aggregation)) {
                //for the case treePatternVisited.get(patternTreeIndex)==true the XMLScan associated to the returned variable is already in the algebraic tree, so we do nothing
                //for the case treePatternVisited.get(patternTreeIndex)==false the XMLScan associated to the returned variable has not been included in the algebraic tree, hence we plug the XMLScan to constructChild
                if (patternTreeIndex != -1 && treePatternVisited.get(patternTreeIndex) == false) {
                    if (constructChild == null)
                        constructChild = scans.get(patternTreeIndex);
                    else
                        constructChild = new CartesianProduct(constructChild, scans.get(patternTreeIndex));
                    treePatternVisited.set(patternTreeIndex, true);
                }
                //create the root ConstructionTreePatternNode and instantiate the ConstructionTreePattern
                int[] varpath = null;
                ConstructionTreePatternNode ctpNodeToAdd = null;
                if (var.dataType == Variable.VariableDataType.Subquery && var.nestedCTPRoot != null) {
                    ctpNodeToAdd = var.nestedCTPRoot;
                } else {
                    if (var.node != null && var.node.getNestingDepth() > 0) {
                        //we have a nested let
                        varpath = new int[2];
                        varpath[0] = varMap.getTemporaryPositionByName(varName);
                        varpath[1] = -1; //will be translated into a 0, which is the position of the nested tuples within this tuple. This is done to avoid confusions with the real 0-positioned variable, or to prevent crashes if no 0 position is found in varMap
                    } else //for or non-nested let
                        varpath = new int[] { varMap.getTemporaryPositionByName(varName) };
                    ctpNodeToAdd = new ConstructionTreePatternNode(constructionTreePattern,
                            ContentType.VARIABLE_PATH, varpath, false);

                    //check whether the varpath belongs to an attribute in the source document: in that case, make it hang from an new attribute node in the output
                    //if(var.node != null && var.node.isAttribute() == true)
                    //   artificialAttributeNodeName = var.node.getTag();
                }

                if (isAggrExpr) {
                    //varpath for the Aggregation operator
                    if (varpath == null) {
                        varpath = new int[2];
                        varpath[0] = varMap.getTemporaryPositionByName(varName);
                        varpath[1] = -1; //will be translated into a 0, which is the position of the nested tuples within this tuple. This is done to avoid confusions with the real 0-positioned variable, or to prevent crashes if no 0 position is found in varMap
                    }
                    //REDO: for the case of subqueries, we need to check if aggregationtype is COUNT. In that case, calculate the varpath and input it to the Aggregation operator. If not COUNT, then Exception("you can not SUM,MAX,AVG,etc XML nodes!)
                    //instantiate an Aggregation operator
                    AggregationType aggrType = XQueryUtils.StringToAggregationType(
                            ((XQueryParser.AggrExprContext) child).AGGR_FUNCT().getText());
                    Variable aggrVar = new Variable(XQueryUtils.getNextAuxVariableName(),
                            Variable.VariableDataType.Aggregation);
                    varMap.addNewVariable(aggrVar);
                    Aggregation aggregation = new Aggregation(constructChild, varpath, aggrType);
                    aggregation.setOuterVariable(aggrVar);
                    aggregation.setInnerVariable(var);
                    constructChild = aggregation;
                    //varpath for the CTPNode
                    varpath = new int[] { varMap.getTemporaryPositionByName(aggrVar.name) };
                    ctpNodeToAdd = new ConstructionTreePatternNode(constructionTreePattern,
                            ContentType.VARIABLE_PATH, varpath, false);
                }

                if (var.node != null && var.node.isAttribute() == true && isAggrExpr == false) { //create the artificial attribute node in the output
                    ConstructionTreePatternNode artificialAttributeNode = new ConstructionTreePatternNode(
                            constructionTreePattern, ContentType.ATTRIBUTE, var.node.getTag(), false);
                    //artificialAttributeNode.set
                    constructionTreePattern.addChild(lastConstructionTreePatternNode, artificialAttributeNode);
                    constructionTreePattern.addChild(artificialAttributeNode, ctpNodeToAdd);
                } else
                    constructionTreePattern.addDeepCopySubtreeDuplicateVarpaths(lastConstructionTreePatternNode,
                            ctpNodeToAdd);
            }
        } else { //inside a subquery. So far we assume there is only one inner TP (one TP being navigated in the subquery and nowhere else)
            ConstructionTreePatternNode ctpnode = null;
            if (subqueryWithWhere == true) {
                if (operatorsProcessedInSubquery == false) { //we need to process the operators in this subquery
                    //get the inner TP
                    NavigationTreePattern innerTP = null;
                    BaseLogicalOperator rightChild = null;
                    int tpIndex = -1;
                    if (navigationTreePatternsInsideSubquery.numCols(subqueryLevel) == 1) {
                        innerTP = navigationTreePatternsInsideSubquery.getElement(subqueryLevel, 0);
                        if (innerTP != null) {
                            logicalPlan.setLeaves(scans);
                            rightChild = logicalPlan.getTopFromLeaf(innerTP);
                            tpIndex = XQueryUtils.findTreePatternIndexInScans(scans, innerTP);
                            if (tpIndex != -1)
                                treePatternVisited.set(tpIndex, true);
                        }
                    } else
                        throw new PAXQueryExecutionException(
                                "Currently only one inner Tree Pattern is supported in Left Nested Outer Joins.");

                    //for the other trees: create CPs if needed
                    //if constructChild == null, do CP with all outer XMLScans 
                    ArrayList<BaseLogicalOperator> outerScans = new ArrayList<BaseLogicalOperator>();
                    if (constructChild == null) {// && scans.size() > 1) {
                        if (scans.size() > 1) {
                            for (int scan_index = 0; scan_index < scans.size(); scan_index++) {
                                if (logicalPlan.getTopFromLeaf(scans.get(scan_index)) != rightChild) {
                                    if (constructChild == null)
                                        constructChild = scans.get(scan_index);
                                    else
                                        constructChild = new CartesianProduct(constructChild,
                                                scans.get(scan_index));
                                    treePatternVisited.set(scan_index, true);
                                    outerScans.add(scans.get(scan_index));
                                }
                            }
                        } else {
                            constructChild = scans.get(0);
                            treePatternVisited.set(0, true);
                            outerScans.add(scans.get(0));
                        }
                    } else {
                        for (int scan_index = 0; scan_index < scans.size(); scan_index++) {
                            BaseLogicalOperator topFromLeaf = logicalPlan.getTopFromLeaf(scans.get(scan_index));
                            if (topFromLeaf != rightChild) {
                                if (constructChild != topFromLeaf) //if the i-th scan is not in the main logical tree then do a cartesian product between both trees
                                    constructChild = new CartesianProduct(constructChild, topFromLeaf);
                                treePatternVisited.set(scan_index, true);
                                outerScans.add(scans.get(scan_index));
                            }
                        }
                    }

                    //instantiate the outer variable
                    outerVarObject = new Variable(outerVarSubquery, Variable.VariableDataType.Subquery);
                    outerVarObject.setNestedCTP(subqueryConstructionTreePattern.getRoot());
                    varMap.addNewVariable(outerVarObject);

                    //process the predicate
                    BasePredicate predicate = predicateStack.pop();
                    if (predicate == null)
                        throw new PAXQueryExecutionException(
                                "The predicate for the Left Outer Nested Join does not exist.");

                    //instantiate the LeftOuterNestedJoin operator
                    constructChild = new LeftOuterNestedJoin(constructChild, rightChild, predicate, -1,
                            new int[0]);
                    //instantiate a LeftOuterNestedJoinInfo for later update of the GroupBy operator
                    subqueryInfoList.add(new LeftOuterNestedJoinInfo((LeftOuterNestedJoin) constructChild,
                            outerScans, rightChild, outerVarObject, varMap.getVariable(varName), varMap));

                    operatorsProcessedInSubquery = true;
                }

                ArrayList<Integer> list = new ArrayList<Integer>();
                list.add(varMap.getTemporaryPositionByName(varName));
                boolean nested = (var.dataType != Variable.VariableDataType.Aggregation)
                        && (var.node.getNestingDepth() > 0);
                if (nested == true)
                    list.add(-1);
                int[] varpath = XQueryUtils.IntegerListToIntArray(list);
                //create a CTPNode with a varpath for the innervariable of the outervariable
                ctpnode = new ConstructionTreePatternNode(subqueryConstructionTreePattern,
                        ContentType.VARIABLE_PATH, varpath, false);
                ctpnode.setOuterVariable(outerVarSubquery);

                if (var.node != null && var.node.isAttribute() == true && isAggrExpr == false) { //create the artificial attribute node in the output
                    ConstructionTreePatternNode artificialAttributeNode = new ConstructionTreePatternNode(
                            subqueryConstructionTreePattern, ContentType.ATTRIBUTE, var.node.getTag(), false);
                    //artificialAttributeNode.set
                    subqueryConstructionTreePattern.addChild(lastSubqueryConstructionTreePatternNode,
                            artificialAttributeNode);
                    subqueryConstructionTreePattern.addChild(artificialAttributeNode, ctpnode);
                } else
                    subqueryConstructionTreePattern.addChild(lastSubqueryConstructionTreePatternNode, ctpnode);
            } else { //subquery without a where, we build a chain of Cartesian Products with a GroupBy on top
                if (operatorsProcessedInSubquery == false) { //we need to process the operators in this subquery
                    ArrayList<BaseLogicalOperator> outerScans = new ArrayList<BaseLogicalOperator>();
                    //BaseOperator rightChild = inner tree
                    NavigationTreePattern innerTP = null;
                    BaseLogicalOperator rightChild = null;
                    int tpIndex = -1;
                    if (navigationTreePatternsInsideSubquery.numCols(subqueryLevel) > 0) {
                        innerTP = navigationTreePatternsInsideSubquery.getElement(subqueryLevel, 0);
                        if (innerTP != null) {
                            logicalPlan.setLeaves(scans);
                            rightChild = logicalPlan.getTopFromLeaf(innerTP);
                            tpIndex = XQueryUtils.findTreePatternIndexInScans(scans, innerTP);
                            if (tpIndex != -1)
                                treePatternVisited.set(tpIndex, true);
                        }
                    }
                    //for the other trees: create CPs if needed
                    //if constructChild == null, do CP with all outer XMLScans 
                    if (constructChild == null) {// && scans.size() > 1) {
                        if (scans.size() > 1) {
                            for (int scan_index = 0; scan_index < scans.size(); scan_index++) {
                                if (logicalPlan.getTopFromLeaf(scans.get(scan_index)) != rightChild) {
                                    if (constructChild == null)
                                        constructChild = scans.get(scan_index);
                                    else
                                        constructChild = new CartesianProduct(constructChild,
                                                scans.get(scan_index));
                                    treePatternVisited.set(scan_index, true);
                                    outerScans.add(scans.get(scan_index));
                                }
                            }
                        } else {
                            constructChild = scans.get(0);
                            treePatternVisited.set(0, true);
                            outerScans.add(scans.get(0));
                        }
                    } else {
                        for (int scan_index = 0; scan_index < scans.size(); scan_index++) {
                            BaseLogicalOperator topFromLeaf = logicalPlan.getTopFromLeaf(scans.get(scan_index));
                            if (topFromLeaf != rightChild) {
                                if (constructChild != topFromLeaf) //if the i-th scan is not in the main logical tree then do a cartesian product between both trees
                                    constructChild = new CartesianProduct(constructChild, topFromLeaf);
                                treePatternVisited.set(scan_index, true);
                                outerScans.add(scans.get(scan_index));
                            }
                        }
                    }
                    //instantiate CP between the outer and the inner scans
                    constructChild = new CartesianProduct(constructChild, rightChild);

                    //add the variable that contains the subquery
                    outerVarObject = new Variable(outerVarSubquery, Variable.VariableDataType.Subquery);
                    outerVarObject.setNestedCTP(subqueryConstructionTreePattern.getRoot());
                    varMap.addNewVariable(outerVarObject);
                    //outerVarObject.updateNestedCTPWithVarPosition(varMap.getTemporaryPositionByName(outerVarObject.name));

                    //instantiate a temporary empty GroupBy operator
                    constructChild = new GroupBy(constructChild, new int[0], new int[0], new int[0]);
                    //instantiate a XQueryGroupByInfo for later update of the GroupBy operator
                    subqueryInfoList.add(new GroupByInfo((GroupBy) constructChild, outerScans, rightChild,
                            outerVarObject, varMap.getVariable(varName), varMap));

                    operatorsProcessedInSubquery = true;
                }

                ArrayList<Integer> list = new ArrayList<Integer>();
                list.add(varMap.getTemporaryPositionByName(varName));
                boolean nested = (var.dataType != Variable.VariableDataType.Aggregation)
                        && (var.node.getNestingDepth() > 0);
                if (nested == true)
                    list.add(-1);
                int[] varpath = XQueryUtils.IntegerListToIntArray(list);
                //create a CTPNode with a varpath for the innervariable of the outervariable
                ctpnode = new ConstructionTreePatternNode(subqueryConstructionTreePattern,
                        ContentType.VARIABLE_PATH, varpath, false);
                ctpnode.setOuterVariable(outerVarSubquery);

                if (var.node != null && var.node.isAttribute() == true && isAggrExpr == false) { //create the artificial attribute node in the output
                    ConstructionTreePatternNode artificialAttributeNode = new ConstructionTreePatternNode(
                            subqueryConstructionTreePattern, ContentType.ATTRIBUTE, var.node.getTag(), false);
                    //artificialAttributeNode.set
                    subqueryConstructionTreePattern.addChild(lastSubqueryConstructionTreePatternNode,
                            artificialAttributeNode);
                    subqueryConstructionTreePattern.addChild(artificialAttributeNode, ctpnode);
                } else
                    subqueryConstructionTreePattern.addChild(lastSubqueryConstructionTreePatternNode, ctpnode);
            }
        }
    }

    return null;
}

From source file:nanoverse.compiler.pipeline.interpret.visitors.AbstractNanoNodeVisitor.java

License:Open Source License

protected void verifyPayload(ParseTree child, Class expected) {
    if (child.getPayload() == null) {
        throw new IllegalStateException("Internal error: empty payload");
    }//from  w  w  w  .  j a va2  s.  c om

    Object payload = child.getPayload();

    if (!expected.isInstance(payload)) {
        throw new IllegalStateException("Internal error: expected " + "payload " + expected.getSimpleName()
                + " but got " + payload.getClass().getSimpleName() + ".");
    }
}

From source file:nanoverse.compiler.pipeline.interpret.visitors.AbstractNanoNodeVisitor.java

License:Open Source License

protected void verifyPayload(ParseTree child, Class[] legalChildClasses) {

    if (child.getPayload() == null) {
        throw new IllegalStateException("Internal error: empty payload");
    }//from w  ww  . j  a va 2s  .  com

    Object payload = child.getPayload();

    for (Class clazz : legalChildClasses) {
        if (clazz.isInstance(payload)) {
            return;
        }
    }

    throw new IllegalStateException(
            "Unexpected payload class: " + child.getPayload().getClass().getSimpleName());
}

From source file:org.acmsl.javacss.css.SelectorMatchVisitor.java

License:Open Source License

protected boolean matches(final ParseTree node, final String currentSelector) {
    boolean result = false;

    if (currentSelector.startsWith(".")) {
        // class selector
        String className = node.getPayload().getClass().getSimpleName();

        // remove any container class, if it's anonymous
        if (className.contains("$")) {
            className = className.substring(className.lastIndexOf("$"));
        }//from   w ww  . j  av  a2  s.  com
        // uncapitalize the first letter
        if (className.length() > 1) {
            className = className.substring(0, 1).toLowerCase(Locale.getDefault()) + className.substring(1);
        }
        // remove the trailing "Context".
        className = className.substring(0, className.lastIndexOf("Context"));

        result = currentSelector.equals("." + className);
    } else if (currentSelector.startsWith("\"")) {
        Object payload = node.getPayload();

        if (payload instanceof CommonToken) {
            String value = ((CommonToken) payload).getText();

            String selectorPart = currentSelector.substring(1);
            selectorPart = selectorPart.substring(0, selectorPart.indexOf("\""));

            result = value.equals(selectorPart);
        }
    }

    return result;
}

From source file:sdd.vtlParser.components.AST.java

License:Open Source License

private Object getPayload(ParseTree tree) {
    if (tree.getChildCount() == 0) {
        // A leaf node: return the tree's payload, which is a Token.
        return tree.getPayload();
    } else {/*from   w  w w .jav  a 2 s .co m*/
        // The name for parser rule `foo` will be `FooContext`. Strip
        // `Context` and
        // lower case the first character.
        String ruleName = tree.getClass().getSimpleName().replace("Context", "");
        return Character.toLowerCase(ruleName.charAt(0)) + ruleName.substring(1);
    }
}