Java Code Examples for org.antlr.v4.runtime.ParserRuleContext

The following examples show how to use org.antlr.v4.runtime.ParserRuleContext. These examples are extracted from open source projects. 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 Project: batfish   Source File: CumulusNcluConfigurationBuilder.java    License: Apache License 2.0 6 votes vote down vote up
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 2
Source Project: kripton   Source File: ContentUriChecker.java    License: Apache License 2.0 6 votes vote down vote up
/**
 * 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 3
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 4
Source Project: yauaa   Source File: TestChildIterable.java    License: Apache License 2.0 6 votes vote down vote up
@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 5
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 6
Source Project: batfish   Source File: ParseTreePrettyPrinterTest.java    License: Apache License 2.0 6 votes vote down vote up
@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 7
Source Project: bookish   Source File: ExecutableCodeDef.java    License: MIT License 6 votes vote down vote up
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 8
Source Project: batfish   Source File: CumulusNcluGrammarTest.java    License: Apache License 2.0 6 votes vote down vote up
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 9
Source Project: bookish   Source File: Tool.java    License: MIT License 6 votes vote down vote up
/** 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 10
Source Project: batfish   Source File: BatfishANTLRErrorStrategy.java    License: Apache License 2.0 6 votes vote down vote up
/**
 * 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 11
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 12
Source Project: swift-js-transpiler   Source File: PrefixElem.java    License: MIT License 6 votes vote down vote up
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 13
Source Project: systemds   Source File: DmlSyntacticValidator.java    License: Apache License 2.0 6 votes vote down vote up
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 14
Source Project: batfish   Source File: AristaGrammarTest.java    License: Apache License 2.0 6 votes vote down vote up
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 15
Source Project: incubator-tuweni   Source File: ZoneOffsetVisitor.java    License: Apache License 2.0 5 votes vote down vote up
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 16
Source Project: codebuff   Source File: Trainer.java    License: BSD 2-Clause "Simplified" License 5 votes vote down vote up
/** Return the index 0..n-1 of t as child of t.parent.
 *  If t is index 0, always return 0.
 *  If t is a repeated subtree root and index within
 *  sibling list > 0, return CHILD_INDEX_LIST_ELEMENT.
 *  In all other cases, return the actual index of t. That means for a
 *  sibling list starting at child index 5, the first sibling will return
 *  5 but 2nd and beyond in list will return CHILD_INDEX_LIST_ELEMENT.
 */
public static int getChildIndexOrListMembership(ParseTree t) {
	if ( t==null ) return -1;
	ParseTree parent = t.getParent();
	if ( parent==null ) {
		return -1;
	}
	// we know we have a parent now
	// check to see if we are 2nd or beyond element in a sibling list
	if ( t instanceof ParserRuleContext ) {
		List<ParserRuleContext> siblings =
			((ParserRuleContext)parent).getRuleContexts(((ParserRuleContext)t).getClass());
		if ( siblings.size()>1 && siblings.indexOf(t)>0 ) {
			return CHILD_INDEX_REPEATED_ELEMENT;
		}
	}
	// check to see if we are 2nd or beyond repeated token
	if ( t instanceof TerminalNode ) {
		List<TerminalNode> repeatedTokens =
			((ParserRuleContext) parent).getTokens(((TerminalNode) t).getSymbol().getType());
		if ( repeatedTokens.size()>1 && repeatedTokens.indexOf(t)>0 ) {
			return CHILD_INDEX_REPEATED_ELEMENT;
		}
	}

	return getChildIndex(t);
}
 
Example 17
Source Project: codebuff   Source File: Trainer.java    License: BSD 2-Clause "Simplified" License 5 votes vote down vote up
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 18
Source Project: batfish   Source File: CumulusNcluConfigurationBuilder.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * Returns a newly-created {@link Vxlan} with given {@code name}, or {@code null} if {@code name}
 * is invalid.
 */
private @Nullable Vxlan createVxlan(String name, ParserRuleContext ctx) {
  if (name.equals(LOOPBACK_INTERFACE_NAME)
      || PHYSICAL_INTERFACE_PATTERN.matcher(name).matches()
      || SUBINTERFACE_PATTERN.matcher(name).matches()
      || VLAN_INTERFACE_PATTERN.matcher(name).matches()) {
    _w.redFlag(String.format("Invalid name '%s' for vxlan in: %s", name, getFullText(ctx)));
    return null;
  }
  if (_c.getBonds().containsKey(name)) {
    _w.redFlag(
        String.format(
            "Invalid name '%s' for vxlan clashes with existing bond interface in: %s",
            name, getFullText(ctx)));
    return null;
  }
  if (_c.getInterfaces().containsKey(name)) {
    _w.redFlag(
        String.format(
            "Invalid name '%s' for vxlan clashes with existing interface in: %s",
            name, getFullText(ctx)));
    return null;
  }
  if (_c.getVrfs().containsKey(name)) {
    _w.redFlag(
        String.format(
            "Invalid name '%s' for vxlan clashes with existing vrf in: %s",
            name, getFullText(ctx)));
    return null;
  }
  return new Vxlan(name);
}
 
Example 19
Source Project: yauaa   Source File: NumberRangeVisitor.java    License: Apache License 2.0 5 votes vote down vote up
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 20
/**
 * 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 21
Source Project: swift-js-transpiler   Source File: CacheVisitor.java    License: MIT License 5 votes vote down vote up
private void visitClassOrStructDeclaration(ParserRuleContext ctx) {
    String className =
            ctx instanceof SwiftParser.Class_declarationContext ? ((SwiftParser.Class_declarationContext)ctx).class_name().getText() :
            ((SwiftParser.Struct_declarationContext)ctx).struct_name().getText();

    Cache.CacheBlockAndObject superClass = null;
    SwiftParser.Type_inheritance_clauseContext typeInheritanceClauseCtx =
            ctx instanceof SwiftParser.Class_declarationContext ? ((SwiftParser.Class_declarationContext)ctx).type_inheritance_clause() :
            ((SwiftParser.Struct_declarationContext)ctx).type_inheritance_clause();
    if(typeInheritanceClauseCtx != null) {
        String superClassName = typeInheritanceClauseCtx.type_inheritance_list().type_identifier().getText();
        superClass = this.cache.find(superClassName, ctx);
    }

    ClassDefinition classDefinition = new ClassDefinition(className, superClass, new LinkedHashMap<String, Instance>(), new ArrayList<String>());
    if(ctx instanceof SwiftParser.Struct_declarationContext) {
        classDefinition.cloneOnAssignmentReplacement = new HashMap<String, Boolean>();
        classDefinition.cloneOnAssignmentReplacement.put("ts", true);
        classDefinition.cloneOnAssignmentReplacement.put("java", true);
    }
    cache.cacheOne(className, classDefinition, ctx);

    visit(ctx instanceof SwiftParser.Class_declarationContext ? ((SwiftParser.Class_declarationContext)ctx).class_body() : ((SwiftParser.Struct_declarationContext)ctx).struct_body());

    if(ctx instanceof SwiftParser.Struct_declarationContext) Initializer.addMemberwiseInitializer(classDefinition, ctx, this);
    Initializer.addDefaultInitializer(classDefinition, ctx, this);
}
 
Example 22
Source Project: datacollector   Source File: ParseUtil.java    License: Apache License 2.0 5 votes vote down vote up
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 23
Source Project: codebuff   Source File: Trainer.java    License: BSD 2-Clause "Simplified" License 5 votes vote down vote up
/** 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 24
Source Project: yauaa   Source File: UserAgentGetChildrenVisitor.java    License: Apache License 2.0 5 votes vote down vote up
@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 25
Source Project: systemds   Source File: BuiltinFunctionExpression.java    License: Apache License 2.0 5 votes vote down vote up
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 26
Source Project: bookish   Source File: InlinePyEvalDef.java    License: MIT License 5 votes vote down vote up
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 27
Source Project: PoseidonX   Source File: OrderbyClauseParser.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * {@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 28
Source Project: crate   Source File: AstBuilder.java    License: Apache License 2.0 5 votes vote down vote up
@Nullable
private <T> T visitOptionalContext(@Nullable ParserRuleContext context, Class<T> clazz) {
    if (context != null) {
        return clazz.cast(visit(context));
    }
    return null;
}
 
Example 29
Source Project: kripton   Source File: ContentUriChecker.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * 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();
}
 
Example 30
Source Project: netbeans   Source File: JsonModelResolver.java    License: Apache License 2.0 5 votes vote down vote up
@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);
}