org.antlr.v4.runtime.RuleContext Java Examples

The following examples show how to use org.antlr.v4.runtime.RuleContext. 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: ErrorHandler.java    From presto with Apache License 2.0 6 votes vote down vote up
public Result process(ATNState currentState, int tokenIndex, RuleContext context)
{
    RuleStartState startState = atn.ruleToStartState[currentState.ruleIndex];

    if (isReachable(currentState, startState)) {
        // We've been dropped inside a rule in a state that's reachable via epsilon transitions. This is,
        // effectively, equivalent to starting at the beginning (or immediately outside) the rule.
        // In that case, backtrack to the beginning to be able to take advantage of logic that remaps
        // some rules to well-known names for reporting purposes
        currentState = startState;
    }

    Set<Integer> endTokens = process(new ParsingState(currentState, tokenIndex, false, parser), 0);
    Set<Integer> nextTokens = new HashSet<>();
    while (!endTokens.isEmpty() && context.invokingState != -1) {
        for (int endToken : endTokens) {
            ATNState nextState = ((RuleTransition) atn.states.get(context.invokingState).transition(0)).followState;
            nextTokens.addAll(process(new ParsingState(nextState, endToken, false, parser), 0));
        }
        context = context.parent;
        endTokens = nextTokens;
    }

    return new Result(furthestTokenIndex, candidates);
}
 
Example #2
Source File: CumulusFrrConfigurationBuilder.java    From batfish with Apache License 2.0 6 votes vote down vote up
@Override
public void exitRmm_community(Rmm_communityContext ctx) {
  ctx.names.forEach(
      name ->
          _c.referenceStructure(
              IP_COMMUNITY_LIST, name.getText(),
              ROUTE_MAP_MATCH_COMMUNITY_LIST, name.getStart().getLine()));

  _currentRouteMapEntry.setMatchCommunity(
      new RouteMapMatchCommunity(
          ImmutableList.<String>builder()
              // add old names
              .addAll(
                  Optional.ofNullable(_currentRouteMapEntry.getMatchCommunity())
                      .map(RouteMapMatchCommunity::getNames)
                      .orElse(ImmutableList.of()))
              // add new names
              .addAll(ctx.names.stream().map(RuleContext::getText).iterator())
              .build()));
}
 
Example #3
Source File: Pass3Listener.java    From trygve with GNU General Public License v2.0 6 votes vote down vote up
private <ExprType> Declaration findProperMethodScopeAround(final ExprType ctxExpr, final RuleContext ctxParent, final Token ctxGetStart) {
	Declaration retval = null;
	RuleContext executionContext = ctxParent;
	while ((executionContext instanceof ProgramContext) == false) {
		if (executionContext instanceof Method_declContext) {
			final Method_declContext mdeclContext = (Method_declContext)executionContext;
			final Method_decl_hookContext hookContext = mdeclContext.method_decl_hook();
			final Method_signatureContext signatureCtx = hookContext.method_signature();
			final String methodName = signatureCtx.method_name().getText();
			final MethodDeclaration methodDecl = currentScope_.lookupMethodDeclarationRecursive(methodName, null, true);
			retval = methodDecl;
			break;
		} else if (executionContext instanceof Role_bodyContext) {
			break;
		} else if (executionContext instanceof Role_declContext) {
			break;
		} else if (executionContext instanceof Class_bodyContext) {
			break;
		} else if (executionContext instanceof Type_declarationContext) {
			break;
		}
		executionContext = executionContext.parent;
	}
	return retval;
}
 
Example #4
Source File: JavaFilePage.java    From jd-gui with GNU General Public License v3.0 6 votes vote down vote up
public boolean isAField(JavaParser.ExpressionContext ctx) {
    RuleContext parent = ctx.parent;

    if (parent instanceof JavaParser.ExpressionContext) {
        int size = parent.getChildCount();

        if (parent.getChild(size - 1) != ctx) {
            for (int i=0; i<size; i++) {
                if (parent.getChild(i) == ctx) {
                    ParseTree next = parent.getChild(i+1);

                    if (next instanceof TerminalNode) {
                        switch (((TerminalNode)next).getSymbol().getType()) {
                            case JavaParser.DOT:
                            case JavaParser.LPAREN:
                                return false;
                        }
                    }
                }
            }
        }
    }

    return true;
}
 
Example #5
Source File: FWPolicyLexer.java    From development with Apache License 2.0 6 votes vote down vote up
@Override
public void action(RuleContext _localctx, int ruleIndex, int actionIndex) {
    switch (ruleIndex) {
    case 6:
        MINUS_action((RuleContext) _localctx, actionIndex);
        break;

    case 7:
        SLASH_action((RuleContext) _localctx, actionIndex);
        break;

    case 8:
        LPAR_action((RuleContext) _localctx, actionIndex);
        break;

    case 9:
        RPAR_action((RuleContext) _localctx, actionIndex);
        break;

    case 19:
        WS_action((RuleContext) _localctx, actionIndex);
        break;
    }
}
 
Example #6
Source File: Select_or_valuesGenerator.java    From antsdb with GNU Lesser General Public License v3.0 6 votes vote down vote up
private static RuleContext rewriteHaving(GeneratorContext ctx, Planner planner, Expr_functionContext rule) {
    String funcname = rule.function_name().getText().toLowerCase();
    if (_aggregates.contains(funcname)) {
        OutputField field = findExisting(ctx, planner, rule);
        if (field != null) {
            return createColumnName_(rule, field);
        }
        else {
            Operator expr = ExprGenerator.gen(ctx, planner, (ExprContext)rule.getParent());
            field = planner.addOutputField("*" + planner.getOutputFields().size(), expr);
            return createColumnName_(rule, field);
        }
    }
    else {
        return rule;
    }
}
 
Example #7
Source File: Select_or_valuesGenerator.java    From antsdb with GNU Lesser General Public License v3.0 6 votes vote down vote up
private static ExprContext rewriteHaving(GeneratorContext ctx, Planner planner, ExprContext expr) {
    ExprContext rewritten = new ExprContext(expr.getParent(), expr.invokingState);
    for (ParseTree i:expr.children) {
        if (i instanceof Expr_functionContext) {
            rewritten.addChild(rewriteHaving(ctx, planner, (Expr_functionContext)i));
        }
        else if (i instanceof ExprContext) {
            rewritten.addChild(rewriteHaving(ctx, planner, (ExprContext)i));
        }
        else if (i instanceof RuleContext) {
            rewritten.addChild((RuleContext)i);
        }
        else if (i instanceof TerminalNode) {
            rewritten.addChild((TerminalNode)i);
        }
        else {
            throw new CodingError();
        }
    }
    return rewritten;
}
 
Example #8
Source File: ProtoParserDefinition.java    From protobuf-jetbrains-plugin with Apache License 2.0 6 votes vote down vote up
@Override
public String formatMessage(SyntaxError error) {
    RecognitionException exception = error.getException();
    if (exception instanceof InputMismatchException) {
        InputMismatchException mismatchException = (InputMismatchException) exception;
        RuleContext ctx = mismatchException.getCtx();
        int ruleIndex = ctx.getRuleIndex();
        switch (ruleIndex) {
            case ProtoParser.RULE_ident:
                return ProtostuffBundle.message("error.expected.identifier");
            default:
                break;
        }
    }
    return super.formatMessage(error);
}
 
Example #9
Source File: Python3MethodParser.java    From Siamese with GNU General Public License v3.0 6 votes vote down vote up
/**
 * Recursive depth first traversal that updates the current class node and extracts methods.
 * @param ruleContext RuleContext
 * @param methods List of Method extracted
 * @param classNode Current TerminalNodeImpl with class name that is the class
 *                  containing all methods traversed onwards from current iteration
 */
private void traverse(RuleContext ruleContext, ArrayList<Method> methods, TerminalNodeImpl classNode) {
    if (ruleContext.getRuleIndex() == Python3Parser.RULE_classdef) {
        classNode = getClassNode(ruleContext);
    }

    if (ruleContext.getRuleIndex() == Python3Parser.RULE_funcdef) {
        List<TerminalNodeImpl> terminalNodes = new ArrayList<>();
        // Add terminal nodes to list in place
        extract(ruleContext, methods, classNode, terminalNodes);
        Method method = createMethod(classNode, terminalNodes);
        methods.add(method);
    } else {
        for (int i = 0; i < ruleContext.getChildCount(); i++) {
            ParseTree parseTree = ruleContext.getChild(i);
            if (parseTree instanceof RuleContext) {
                traverse((RuleContext) parseTree, methods, classNode);
            }
        }
    }
}
 
Example #10
Source File: FeatureParser.java    From karate with MIT License 6 votes vote down vote up
private FeatureParser(Feature feature, InputStream is) {
    this.feature = feature;
    CharStream stream;
    try {
        stream = CharStreams.fromStream(is, StandardCharsets.UTF_8);
    } catch (IOException e) {
        throw new RuntimeException(e);
    }
    KarateLexer lexer = new KarateLexer(stream);
    CommonTokenStream tokens = new CommonTokenStream(lexer);
    KarateParser parser = new KarateParser(tokens);
    parser.addErrorListener(errorListener);
    RuleContext tree = parser.feature();
    if (logger.isTraceEnabled()) {
        logger.debug(tree.toStringTree(parser));
    }
    ParseTreeWalker walker = new ParseTreeWalker();
    walker.walk(this, tree);
    if (errorListener.isFail()) {
        String errorMessage = errorListener.getMessage();
        logger.error("not a valid feature file: {} - {}", feature.getResource().getRelativePath(), errorMessage);
        throw new RuntimeException(errorMessage);
    }
}
 
Example #11
Source File: ASTGenerator.java    From ASTGenerator with MIT License 6 votes vote down vote up
private static void generateAST(RuleContext ctx, boolean verbose, int indentation) {
       boolean toBeIgnored = !verbose && ctx.getChildCount() == 1 && ctx.getChild(0) instanceof ParserRuleContext;

       if (!toBeIgnored) {
           String ruleName = Java8Parser.ruleNames[ctx.getRuleIndex()];
    LineNum.add(Integer.toString(indentation));
           Type.add(ruleName);
           Content.add(ctx.getText());
}
       for (int i = 0; i < ctx.getChildCount(); i++) {
           ParseTree element = ctx.getChild(i);
           if (element instanceof RuleContext) {
               generateAST((RuleContext) element, verbose, indentation + (toBeIgnored ? 0 : 1));
           }
       }
   }
 
Example #12
Source File: ValueNode.java    From gyro with Apache License 2.0 6 votes vote down vote up
private String getContextText(RuleContext context) {
    if (context.getChildCount() == 0) {
        return "";
    }

    StringBuilder builder = new StringBuilder();
    for (int i = 0; i < context.getChildCount(); i++) {
        ParseTree child = context.getChild(i);

        if (child instanceof GyroParser.EscapeContext) {
            builder.append(getEscapeText((GyroParser.EscapeContext) child));

        } else {
            builder.append(child.getText());
        }
    }

    return builder.toString();
}
 
Example #13
Source File: CumulusInterfacesConfigurationBuilder.java    From batfish with Apache License 2.0 5 votes vote down vote up
@Override
public void exitI_bridge_ports(I_bridge_portsContext ctx) {
  List<Interface_nameContext> interfaceNameCtxs = ctx.interface_name();
  interfaceNameCtxs.forEach(
      ifaceNameCtx ->
          _config.referenceStructure(
              CumulusStructureType.ABSTRACT_INTERFACE,
              ifaceNameCtx.getText(),
              CumulusStructureUsage.BRIDGE_PORT,
              ifaceNameCtx.getStart().getLine()));
  _currentIface.setBridgePorts(
      interfaceNameCtxs.stream()
          .map(RuleContext::getText)
          .collect(ImmutableSet.toImmutableSet()));
}
 
Example #14
Source File: CumulusInterfacesConfigurationBuilder.java    From batfish with Apache License 2.0 5 votes vote down vote up
@Override
public void exitI_bond_slaves(I_bond_slavesContext ctx) {
  List<Interface_nameContext> interfaceNameCtxs = ctx.interface_name();
  interfaceNameCtxs.forEach(
      ifaceNameCtx ->
          _config.referenceStructure(
              CumulusStructureType.INTERFACE,
              ifaceNameCtx.getText(),
              CumulusStructureUsage.BOND_SLAVE,
              ifaceNameCtx.getStart().getLine()));
  _currentIface.setBondSlaves(
      interfaceNameCtxs.stream().map(RuleContext::getText).collect(Collectors.toSet()));
}
 
Example #15
Source File: VendorConfiguration.java    From batfish with Apache License 2.0 5 votes vote down vote up
/**
 * Mark the specified structure as defined on each line in the supplied context. This method
 * proceeds by examining every token in the given {@code context}, rather than just the start and
 * stop intervals. It uses the given {@code parser} to find the original (pre-flattening) line
 * number of each token.
 *
 * <p>For structures in non-flattened files, see {@link #defineStructure(StructureType, String,
 * ParserRuleContext)}.
 */
public void defineFlattenedStructure(
    StructureType type, String name, RuleContext ctx, BatfishCombinedParser<?, ?> parser) {
  /* Recursively process children to find all relevant definition lines for the specified context */
  for (int i = 0; i < ctx.getChildCount(); i++) {
    ParseTree child = ctx.getChild(i);
    if (child instanceof TerminalNode) {
      defineSingleLineStructure(type, name, parser.getLine(((TerminalNode) child).getSymbol()));
    } else if (child instanceof RuleContext) {
      defineFlattenedStructure(type, name, (RuleContext) child, parser);
    }
  }
}
 
Example #16
Source File: Pass2Listener.java    From trygve with GNU General Public License v2.0 5 votes vote down vote up
@Override protected void checkExprDeclarationLevel(RuleContext ctxParent, Token ctxGetStart) {
	// Certified Pass 2 version :-)
	RuleContext executionContext = ctxParent;
	while ((executionContext instanceof ProgramContext) == false) {
		if (executionContext instanceof Method_declContext) {
			break;
		} else if (executionContext instanceof Stageprop_bodyContext) {
			errorHook5p2(ErrorIncidenceType.Fatal, ctxGetStart, "Expression cannot just appear in stageprop scope: it must be in a method", "", "", "");
			break;
		} else if (executionContext instanceof Role_bodyContext) {
			errorHook5p2(ErrorIncidenceType.Fatal, ctxGetStart, "Expression cannot just appear in Role scope: it must be in a method", "", "", "");
			break;
		} else if (executionContext instanceof Stageprop_declContext) {
			errorHook5p2(ErrorIncidenceType.Fatal, ctxGetStart, "Expression cannot just appear in stageprop scope: it must be in a method", "", "", "");
			break;
		} else if (executionContext instanceof Role_declContext) {
			errorHook5p2(ErrorIncidenceType.Fatal, ctxGetStart, "Expression cannot just appear in Role scope: it must be in a method", "", "", "");
			break;
		} else if (executionContext instanceof Class_bodyContext) {
			errorHook5p2(ErrorIncidenceType.Fatal, ctxGetStart, "Expression cannot just appear in Class scope: it must be in a method", "", "", "");
			break;
		} else if (executionContext instanceof Type_declarationContext) {
			errorHook5p2(ErrorIncidenceType.Fatal, ctxGetStart, "Expression cannot just appear in a global program element scope: it must be in a method", "", "", "");
			break;
		}
		executionContext = executionContext.parent;
	}
}
 
Example #17
Source File: Pass3Listener.java    From trygve with GNU General Public License v2.0 5 votes vote down vote up
@Override protected <ExprType> Expression expressionFromReturnStatement(final ExprType ctxExpr, final RuleContext ctxParent, final Token ctxGetStart)
{
	Expression expressionReturned = null;
	if (null != ctxExpr) {
		expressionReturned = parsingData_.popExpression();
	}
	final MethodDeclaration methodDecl = (MethodDeclaration)findProperMethodScopeAround(ctxExpr, ctxParent, ctxGetStart);
	assert null == methodDecl || methodDecl instanceof MethodDeclaration;
	
	if (null == methodDecl) {
		expressionReturned = new ErrorExpression(null);
		ErrorLogger.error(ErrorIncidenceType.Fatal, ctxGetStart, "Return statement must be within a method scope ", "", "", "");
	} else {
		if (methodDecl.returnType() == null || methodDecl.returnType().name().equals("void")) {
			if (null == expressionReturned || expressionReturned.type().name().equals("void")) {
				;
			} else {
				ErrorLogger.error(ErrorIncidenceType.Fatal, ctxGetStart, "Return expression `", expressionReturned.getText(), "' of type ",
						expressionReturned.type().getText(), " is incompatible with method that returns no value.", "");
				expressionReturned = new ErrorExpression(null);
			}
		} else if (methodDecl.returnType().canBeConvertedFrom(expressionReturned.type())) {
			;
		} else {
			if (expressionReturned.isntError()) {
				ErrorLogger.error(ErrorIncidenceType.Fatal, ctxGetStart,
						"Return expression `" + expressionReturned.getText(),
						"`' of type `", expressionReturned.type().getText(),
						"' is not compatible with declared return type `",
						methodDecl.returnType().getText(), "'.");
				expressionReturned = new ErrorExpression(expressionReturned);
			}
		}
	}
	return expressionReturned;
}
 
Example #18
Source File: AnnotationProcessor.java    From depends with MIT License 5 votes vote down vote up
public void processAnnotationModifier(RuleContext ctx, @SuppressWarnings("rawtypes") Class rootClass,
	String toAnnotationPath,ContainerEntity container) {
	List<ContainerEntity> list  = new ArrayList<>() ;
	list.add(container);
	processAnnotationModifier(ctx, rootClass,
			toAnnotationPath, list);
}
 
Example #19
Source File: AnnotationProcessor.java    From depends with MIT License 5 votes vote down vote up
public void processAnnotationModifier(RuleContext ctx, @SuppressWarnings("rawtypes") Class rootClass,
		String toAnnotationPath, List<?> containers) {

	while (true) {
		if (ctx == null)
			break;
		if (ctx.getClass().equals(rootClass))
			break;
		ctx = ctx.parent;
	}
	if (ctx == null)
		return;


	try {
		Object r = ctx;
		String[] paths = toAnnotationPath.split("\\.");
		for (String path : paths) {
			r = invokeMethod(r, path);
			if (r == null)
				return;
		}
		Collection<AnnotationContext> contexts = new HashSet<>();
		mergeElements(contexts, r);
		for (Object item : contexts) {
			AnnotationContext annotation = (AnnotationContext) item;
			String name = QualitiedNameContextHelper.getName(annotation.qualifiedName());
			containers.stream().forEach(container->((ContainerEntity)container).addAnnotation(GenericName.build(name)));
		}
	} catch (Exception e) {
		return;
	}
}
 
Example #20
Source File: GDLLoader.java    From gdl with Apache License 2.0 5 votes vote down vote up
/**
 * Returns the element labels from a given header context.
 *
 * @param header header context
 * @return element labels or {@code null} if context was null
 */
private List<String> getLabels(GDLParser.HeaderContext header) {
  if (header != null && header.label() != null) {
    return header
      .label()
      .stream()
      .map(RuleContext::getText)
      .map(x -> x.substring(1))
      .collect(Collectors.toList());
  }
  return null;
}
 
Example #21
Source File: FWPolicyLexer.java    From development with Apache License 2.0 5 votes vote down vote up
private void MINUS_action(RuleContext _localctx, int actionIndex) {
    switch (actionIndex) {
    case 0:
        _channel = HIDDEN;
        break;
    }
}
 
Example #22
Source File: FWPolicyLexer.java    From development with Apache License 2.0 5 votes vote down vote up
private void LPAR_action(RuleContext _localctx, int actionIndex) {
    switch (actionIndex) {
    case 2:
        _channel = HIDDEN;
        break;
    }
}
 
Example #23
Source File: FWPolicyLexer.java    From development with Apache License 2.0 5 votes vote down vote up
private void SLASH_action(RuleContext _localctx, int actionIndex) {
    switch (actionIndex) {
    case 1:
        _channel = HIDDEN;
        break;
    }
}
 
Example #24
Source File: FWPolicyLexer.java    From development with Apache License 2.0 5 votes vote down vote up
private void WS_action(RuleContext _localctx, int actionIndex) {
    switch (actionIndex) {
    case 4:
        _channel = HIDDEN;
        break;
    }
}
 
Example #25
Source File: FWPolicyLexer.java    From development with Apache License 2.0 5 votes vote down vote up
private void RPAR_action(RuleContext _localctx, int actionIndex) {
    switch (actionIndex) {
    case 3:
        _channel = HIDDEN;
        break;
    }
}
 
Example #26
Source File: ExpressionUsage.java    From depends with MIT License 5 votes vote down vote up
private Expression findParentInStack(RuleContext ctx) {
	if (ctx==null) return null;
	if (ctx.parent==null) return null;
	if (context.lastContainer()==null) {
		return null;
	}
	if (context.lastContainer().expressions().containsKey(ctx.parent)) return context.lastContainer().expressions().get(ctx.parent);
	return findParentInStack(ctx.parent);
}
 
Example #27
Source File: IndexRQL.java    From indexr with Apache License 2.0 5 votes vote down vote up
private static <T> T assignRuleContext(ParseTree root, T ruleContainer) {
    InstanceTypeAssigner instanceTypeAssigner = new InstanceTypeAssigner(ruleContainer, RuleContext.class);
    parseTreeWalker(root, rule -> {
        instanceTypeAssigner.tryAssign(rule.getRuleContext());
    });
    return ruleContainer;
}
 
Example #28
Source File: Select_or_valuesGenerator.java    From antsdb with GNU Lesser General Public License v3.0 5 votes vote down vote up
private static RuleContext createColumnName_(Expr_functionContext rule, OutputField field) {
    Column_name_Context column_name_ = new Column_name_Context(rule.getParent(), rule.invokingState);
    Column_nameContext column_name = new Column_nameContext(column_name_.getParent(), rule.invokingState);
    IdentifierContext identifier = new IdentifierContext(column_name, rule.invokingState);
    CommonToken token = CommonTokenFactory.DEFAULT.create(
            MysqlParser.BACKTICK_QUOTED_IDENTIFIER, 
            '`' + field.name + '`' );
    TerminalNode term = new TerminalNodeImpl(token);
    identifier.addChild(term);
    column_name.addChild(identifier);
    column_name_.addChild(column_name);
    return column_name_;
}
 
Example #29
Source File: ExpressionUsage.java    From depends with MIT License 5 votes vote down vote up
private Expression findParentInStack(RuleContext ctx) {
	if (ctx==null) return null;
	if (ctx.parent==null) return null;
	if (context.lastContainer()==null) {
		return null;
	}
	if (context.lastContainer().expressions().containsKey(ctx.parent)) 
		return context.lastContainer().expressions().get(ctx.parent);
	return findParentInStack(ctx.parent);
}
 
Example #30
Source File: Python3MethodParser.java    From Siamese with GNU General Public License v3.0 5 votes vote down vote up
/**
 * Uses ANTLR4 generated Parser and Lexer to extract methods from Python3 source code file
 * @return ArrayList of methods extracted from FILE_PATH attribute
 */
@Override
public ArrayList<Method> parseMethods() {
    RuleContext ruleContext = parseFile(FILE_PATH);
    ArrayList<Method> methods = new ArrayList<>();
    if (MODE.equals(Settings.MethodParserType.METHOD)) {
        // Add methods to list in place
        traverse(ruleContext, methods, null);
    } else {
        // Use the entire file as a single method
        methods.add(createFileMethod(ruleContext));
    }
    return methods;
}