Java Code Examples for org.antlr.v4.runtime.tree.ParseTree#getChild()

The following examples show how to use org.antlr.v4.runtime.tree.ParseTree#getChild() . 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: DistkvNewSqlListener.java    From distkv with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
@Override
public void enterDictPut(DistkvNewSQLParser.DictPutContext ctx) {
  Preconditions.checkState(parsedResult == null);
  Preconditions.checkState(ctx.children.size() == 3);
  DictProtocol.DictPutRequest.Builder builder = DictProtocol.DictPutRequest.newBuilder();
  final ParseTree keyValuePairsParseTree = ctx.children.get(2);
  final int numKeyValuePairs = keyValuePairsParseTree.getChildCount();
  DictProtocol.DistKVDict.Builder distKVDictBuilder = DictProtocol.DistKVDict.newBuilder();
  for (int i = 0; i < numKeyValuePairs; ++i) {
    final ParseTree keyValuePairParseTree = keyValuePairsParseTree.getChild(i);
    Preconditions.checkState(keyValuePairParseTree.getChildCount() == 2);
    distKVDictBuilder.addKeys(keyValuePairParseTree.getChild(0).getText());
    distKVDictBuilder.addValues(keyValuePairParseTree.getChild(1).getText());
  }
  builder.setDict(distKVDictBuilder.build());
  DistkvRequest request = DistkvRequest.newBuilder()
      .setKey(ctx.children.get(1).getText())
      .setRequestType(DICT_PUT)
      .setRequest(Any.pack(builder.build()))
      .build();
  parsedResult = new DistkvParsedResult(DICT_PUT, request);
}
 
Example 2
Source File: Translator.java    From bookish with MIT License 6 votes vote down vote up
/** Find all x={...} attributes and translate those from bookish to appropriate
	 *  target output format.  Replace existing attribute value with translation.
	 *
	 *  Side effect: alters xml attribute map annotation of attrs rule nodes.
	 */
	public void translateXMLAttributes(DocInfo docInfo) {
		Collection<ParseTree> attrsNodes = XPath.findAll(docInfo.tree, "//attrs", docInfo.parser);
		for (ParseTree attrsNode : attrsNodes) {
			for (int i = 0; i<attrsNode.getChildCount(); i++) {
				ParseTree assignment = attrsNode.getChild(i);
				ParseTree key = assignment.getChild(0);
				ParseTree value = assignment.getChild(2);
				if ( key!=null && value!=null ) {
					String v = value.getText();
					if ( v.charAt(0)=='{' ) {
						v = stripQuotes(v);
						BookishParser.AttrsContext a = (BookishParser.AttrsContext) attrsNode;
						String location = docInfo.getSourceName()+" "+a.start.getLine()+":"+a.start.getCharPositionInLine();
						v = tool.translateString(docInfo, v, location);
						a.attributes.put(key.getText(), v);
//						System.out.println("ALTER "+key.getText()+" from "+value.getText()+" ->" + v);
					}
				}
			}
		}
	}
 
Example 3
Source File: StepWordRange.java    From yauaa with Apache License 2.0 6 votes vote down vote up
@Override
public WalkResult walk(ParseTree tree, String value) {
    String actualValue = getActualValue(tree, value);
    if (actualValue == null) {
        return null;
    }

    String filteredValue;
    if (tree !=null &&
        tree.getChildCount() == 1 &&
        (
          tree.getChild(0) instanceof SingleVersionContext ||
          tree.getChild(0) instanceof SingleVersionWithCommasContext)) {
        filteredValue = VersionSplitter.getInstance().getSplitRange(actualValue, firstWord, lastWord);
    } else {
        filteredValue = WordSplitter.getInstance().getSplitRange(actualValue, firstWord, lastWord);
    }
    if (filteredValue == null) {
        return null;
    }
    return walkNextStep(tree, filteredValue);
}
 
Example 4
Source File: StepNext.java    From yauaa with Apache License 2.0 6 votes vote down vote up
private ParseTree next(ParseTree tree) {
    ParseTree parent = up(tree);

    if (parent == null) {
        return null;
    }

    ParseTree child;
    boolean foundCurrent = false;
    for (int i = 0; i < parent.getChildCount(); i++) {
        child = parent.getChild(i);
        if (foundCurrent) {
            if (treeIsSeparator(child)) {
                continue;
            }
            return child;
        }

        if (child == tree) {
            foundCurrent = true;
        }
    }
    return null; // There is no next
}
 
Example 5
Source File: StepPrev.java    From yauaa with Apache License 2.0 6 votes vote down vote up
private ParseTree prev(ParseTree tree) {
    ParseTree parent = up(tree);

    if (parent == null) {
        return null;
    }

    ParseTree prevChild = null;
    ParseTree child = null;
    int i;
    for (i = 0; i < parent.getChildCount(); i++) {
        if (!treeIsSeparator(child)) {
            prevChild = child;
        }
        child = parent.getChild(i);
        if (child == tree) {
            break; // Found it
        }
    }
    return prevChild;
}
 
Example 6
Source File: BdsNode.java    From BigDataScript with Apache License 2.0 5 votes vote down vote up
/**
 * Show a parseTree node
 */
void printNode(ParseTree tree) {
	System.out.println(tree.getClass().getSimpleName());
	for (int i = 0; i < tree.getChildCount(); i++) {
		ParseTree node = tree.getChild(i);
		System.out.println("\tchild[" + i + "]\ttype: " + node.getClass().getSimpleName() + "\ttext: '" + node.getText() + "'");
	}
}
 
Example 7
Source File: GroovyNameBuilder.java    From beakerx with Apache License 2.0 5 votes vote down vote up
private ParseTree findChildrenByType(ParseTree parseTree, Class<?> classtype) {
  for (int i = 0; i < parseTree.getChildCount(); i++) {
    ParseTree chl = parseTree.getChild(i);
    if (chl.getClass().equals(classtype)) {
      return chl;
    }
  }
  return null;
}
 
Example 8
Source File: RefactorUtils.java    From intellij-plugin-v4 with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
public static int childIndexOf(ParseTree t, ParseTree child) {
	if ( t==null || child==null ) return -1;
	for (int i = 0; i < t.getChildCount(); i++) {
		if ( child==t.getChild(i) ) return i;
	}
	return -1;
}
 
Example 9
Source File: Trainer.java    From codebuff with BSD 2-Clause "Simplified" License 5 votes vote down vote up
public static int getChildIndex(ParseTree t) {
	if ( t==null ) return -1;
	ParseTree parent = t.getParent();
	if ( parent==null ) {
		return -1;
	}
	// Figure out which child index t is of parent
	for (int i = 0; i<parent.getChildCount(); i++) {
		if ( parent.getChild(i)==t ) {
			return i;
		}
	}
	return -1;
}
 
Example 10
Source File: ANTLRUtils.java    From proleap-vb6-parser with MIT License 5 votes vote down vote up
public static List<ParseTree> findChildren(final ParseTree ctx) {
	final List<ParseTree> result = new ArrayList<ParseTree>();
	final int n = ctx.getChildCount();

	for (int i = 0; i < n; i++) {
		final ParseTree currentChild = ctx.getChild(i);
		result.add(currentChild);
	}

	return result;
}
 
Example 11
Source File: BQLCompiler.java    From linden with Apache License 2.0 5 votes vote down vote up
private static TerminalNode getStartNode(ParseTree tree) {
  if (tree instanceof TerminalNode) {
    return (TerminalNode) tree;
  }

  Deque<ParseTree> workList = new ArrayDeque<ParseTree>();
  IntegerStack workIndexStack = new IntegerStack();
  workList.push(tree);
  workIndexStack.push(0);
  while (!workList.isEmpty()) {
    ParseTree currentTree = workList.peek();
    int currentIndex = workIndexStack.peek();
    if (currentIndex == currentTree.getChildCount()) {
      workList.pop();
      workIndexStack.pop();
      continue;
    }

    // move work list to next child
    workIndexStack.push(workIndexStack.pop() + 1);

    // process the current child
    ParseTree child = currentTree.getChild(currentIndex);
    if (child instanceof TerminalNode) {
      return (TerminalNode) child;
    }

    workList.push(child);
    workIndexStack.push(0);
  }

  return null;
}
 
Example 12
Source File: UserAgentTreeFlattener.java    From yauaa with Apache License 2.0 5 votes vote down vote up
private void enterProductVersion(ParseTree ctx) {
    ParseTree child = ctx.getChild(0);
    // Only for the SingleVersion edition we want to have splits of the version.
    if (child instanceof SingleVersionContext || child instanceof SingleVersionWithCommasContext) {
        return;
    }

    inform(ctx, VERSION);
}
 
Example 13
Source File: StepNextN.java    From yauaa with Apache License 2.0 5 votes vote down vote up
private ParseTree next(ParseTree tree) {
    ParseTree parent = up(tree);

    if (parent == null) {
        return null;
    }

    ParseTree child;
    boolean foundCurrent = false;
    int stepsToDo = steps;
    for (int i = 0; i < parent.getChildCount(); i++) {
        child = parent.getChild(i);
        if (foundCurrent) {
            if (treeIsSeparator(child)) {
                continue;
            }
            stepsToDo--;
            if (stepsToDo == 0) {
                return child;
            }
        }

        if (child == tree) {
            foundCurrent = true;
        }
    }
    return null; // There is no next
}
 
Example 14
Source File: StepPrevN.java    From yauaa with Apache License 2.0 5 votes vote down vote up
private ParseTree prev(ParseTree tree) {
    ParseTree parent = up(tree);

    if (parent == null) {
        return null;
    }

    if (children== null) {
        children = new ParseTree[SIZE];
    }

    int lastChildIndex = -1;
    ParseTree child = null;
    int i;
    for (i = 0; i < parent.getChildCount(); i++) {
        if (!treeIsSeparator(child)) {
            lastChildIndex++;
            children[lastChildIndex] = child;
        }
        child = parent.getChild(i);
        if (child == tree) {
            if (lastChildIndex < steps) {
                break; // There is no previous
            }
            return children[lastChildIndex - steps + 1];
        }
    }
    return null; // There is no previous
}
 
Example 15
Source File: QuantileAnalysisImpl.java    From incubator-pinot with Apache License 2.0 5 votes vote down vote up
@NotNull int parseQuery() {
  LOGGER.debug("Parsing query: {}", _queryString);
  PQL2Parser.OptionalClauseContext optionalClauseContext = null;
  PQL2Parser.WhereClauseContext whereClauseContext = null;
  if (_queryString == null) {
    return 0;
  }
  try {
    PQL2Lexer lexer = new PQL2Lexer(new ANTLRInputStream(_queryString));
    PQL2Parser parser = new PQL2Parser(new CommonTokenStream(lexer));
    ParseTree selectStatement = parser.root().statement().selectStatement();
    LOGGER.debug("selectStatement: {}", selectStatement.getText());

    for (int i = 0; i < selectStatement.getChildCount(); i++) {
      if (selectStatement.getChild(i) instanceof PQL2Parser.OptionalClauseContext) {
        optionalClauseContext = (PQL2Parser.OptionalClauseContext) selectStatement.getChild(i);
        LOGGER.debug("optionalClauseContext: {}", optionalClauseContext.getText());
        if (optionalClauseContext.getChild(0) instanceof PQL2Parser.WhereClauseContext) {
          whereClauseContext = (PQL2Parser.WhereClauseContext) optionalClauseContext.getChild(0);
          break;
        }
      }
    }
  } catch (Exception e) {
    return 0;
  }
  if (whereClauseContext == null) {
    return 0;
  }
  LOGGER.debug("whereClauseContext: {}", whereClauseContext.getText());

  return parsePredicateList(whereClauseContext.predicateList());
}
 
Example 16
Source File: StatementInclude.java    From BigDataScript with Apache License 2.0 5 votes vote down vote up
@Override
protected void parse(ParseTree tree) {
	setNeedsScope(false);

	// File name & parent file name: this is merely informational
	File parentFile = getParent().getFile();
	parentFileName = (parentFile != null ? parentFile.toString() : null);
	fileName = includeFileName(tree.getChild(0).getChild(1).getText());

	// Resolve file and read program text
	File includedFile = StatementInclude.includeFile(fileName, parentFile);
	setFile(includedFile);

	super.parse(tree.getChild(0)); // Block parses statement
}
 
Example 17
Source File: BdsNode.java    From BigDataScript with Apache License 2.0 4 votes vote down vote up
/**
 * Create a BigDataScriptNode
 */
final public BdsNode factory(ParseTree tree, int childNum) {
	ParseTree child = childNum >= 0 ? tree.getChild(childNum) : tree;
	return BdsNodeFactory.get().factory(this, child);
}
 
Example 18
Source File: FieldDeclaration.java    From BigDataScript with Apache License 2.0 4 votes vote down vote up
@Override
protected void parse(ParseTree tree) {
	super.parse(tree.getChild(0));
}
 
Example 19
Source File: MethodDeclaration.java    From BigDataScript with Apache License 2.0 4 votes vote down vote up
@Override
protected void parse(ParseTree tree) {
	super.parse(tree.getChild(0));
}
 
Example 20
Source File: PathExpressionParser.java    From yangtools with Eclipse Public License 1.0 4 votes vote down vote up
private static <T> T getChild(final ParseTree parent, final int offset, final Class<T> clazz) {
    final ParseTree child = parent.getChild(offset);
    verify(clazz.isInstance(child), "Unexpected child %s at offset %s of %s when expecting %s", child, offset,
        parent, clazz);
    return clazz.cast(child);
}