Java Code Examples for org.antlr.v4.runtime.ParserRuleContext#getStart()

The following examples show how to use org.antlr.v4.runtime.ParserRuleContext#getStart() . 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: AbstractProtoParserListener.java    From protostuff-compiler with Apache License 2.0 6 votes vote down vote up
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 2
Source File: PyEvalDef.java    From bookish with MIT License 5 votes vote down vote up
public PyEvalDef(ParserRuleContext tree,
                 String inputFilename,
                 int index,
                 Map<String,String> attributes,
                 String code)
{
	super(tree, inputFilename, index, tree.getStart(), attributes, code);
}
 
Example 3
Source File: ZserioAstBuilder.java    From zserio with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
@Override
public Package visitPackageDeclaration(ZserioParser.PackageDeclarationContext ctx)
{
    // package
    final PackageName packageName = visitPackageNameDefinition(ctx.packageNameDefinition());
    final DocComment docComment = ctx.packageNameDefinition() != null ?
            docCommentManager.findDocComment(ctx.packageNameDefinition()) : null;

    // imports
    final List<Import> imports = new ArrayList<Import>();
    for (ZserioParser.ImportDeclarationContext importCtx : ctx.importDeclaration())
        imports.add(visitImportDeclaration(importCtx));

    // package instance
    final ParserRuleContext packageLocationCtx = ctx.packageNameDefinition() != null
            ? ctx.packageNameDefinition().id(0) : ctx;
    final AstLocation packageLocation = new AstLocation(packageLocationCtx.getStart());
    currentPackage = new Package(packageLocation, packageName, imports, docComment);
    if (packageNameMap.put(currentPackage.getPackageName(), currentPackage) != null)
    {
        // translation unit package already exists, this could happen only for default packages
        throw new ParserException(currentPackage, "Multiple default packages are not allowed!");
    }

    for (ZserioParser.LanguageDirectiveContext languageDirectiveCtx : ctx.languageDirective())
        visitLanguageDirective(languageDirectiveCtx);

    final Package unitPackage = currentPackage;
    currentPackage = null;

    return unitPackage;
}
 
Example 4
Source File: Rule.java    From gyro with Apache License 2.0 5 votes vote down vote up
public Rule(ParserRuleContext context) {
    if (context != null) {
        start = context.getStart();
        stop = context.getStop();

    } else {
        start = null;
        stop = null;
    }
}
 
Example 5
Source File: Location.java    From rockscript with Apache License 2.0 5 votes vote down vote up
public Location(ParserRuleContext parserRuleContext) {
  Token start = parserRuleContext.getStart();
  this.start = start.getStartIndex();
  Token stop = parserRuleContext.getStop();
  end = stop.getStopIndex();
  line = start.getLine();
}
 
Example 6
Source File: Trainer.java    From codebuff with BSD 2-Clause "Simplified" License 5 votes vote down vote up
/** Walk upwards from node while p.start == token; return immediate parent
 *  if there is no ancestor starting at token. This is the earliest
 *  left ancestor. E.g, for '{' of a block, return parent up the chain from
 *  block starting with '{'. For '}' of block, return just block as nothing
 *  starts with '}'. (block stops with it).
 */
public static ParserRuleContext earliestAncestorStartingWithToken(TerminalNode node) {
	Token token = node.getSymbol();
	ParserRuleContext p = (ParserRuleContext)node.getParent();
	ParserRuleContext prev = null;
	while (p!=null && p.getStart()==token) {
		prev = p;
		p = p.getParent();
	}
	if ( prev==null ) {
		return (ParserRuleContext)node.getParent();
	}
	return prev;
}
 
Example 7
Source File: HierarchyViewer.java    From intellij-plugin-v4 with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
private boolean inBounds(ParserRuleContext ctx, int offset) {
	Token start = ctx.getStart();
	Token stop = ctx.getStop();
	if ( start!=null && stop!=null ) {
		return start.getStartIndex()<=offset && stop.getStopIndex()>=offset;
	}
	return false;
}
 
Example 8
Source File: TomlPosition.java    From incubator-tuweni with Apache License 2.0 4 votes vote down vote up
TomlPosition(ParserRuleContext ctx, int offset) {
  Token token = ctx.getStart();
  this.line = token.getLine();
  this.column = token.getCharPositionInLine() + 1 + offset;
}
 
Example 9
Source File: TomlPosition.java    From cava with Apache License 2.0 4 votes vote down vote up
TomlPosition(ParserRuleContext ctx, int offset) {
  Token token = ctx.getStart();
  this.line = token.getLine();
  this.column = token.getCharPositionInLine() + 1 + offset;
}
 
Example 10
Source File: OffsetRangeHelper.java    From kalang with MIT License 4 votes vote down vote up
public static OffsetRange getOffsetRange(ParserRuleContext tree) {
    Token start = tree.getStart();
    Token stop = tree.getStop();
    if(start==null || stop==null) return OffsetRange.NONE;
    return getOffsetRange(start, stop);
}
 
Example 11
Source File: BNFListener.java    From openCypher with Apache License 2.0 4 votes vote down vote up
private String findHiddenTextBefore(ParserRuleContext ctx, boolean forHeader)
{
    Token startCtx = ctx.getStart();
    int i = startCtx.getTokenIndex();
    List<Token> normalTextChannel =
                tokens.getHiddenTokensToLeft(i, BNFLexer.HIDDEN);
    if (normalTextChannel != null) {
        // find where the blank lines are
        // when called for a rule, is the quasi-comment part of the content of the previous rule or
        // the description of this one. Immaterial for grammar header
        
        List<Token> lineTokens = normalTextChannel.stream().collect(Collectors.toList());

        int precedingBlankLines = startCtx.getLine() - lineTokens.get(lineTokens.size()-1).getLine() - 1;
        if (precedingBlankLines > 0) {
            if (forHeader) {
                // this will preserve the linefeeds
                return lineTokens.stream().map(tk -> tk.getText().replaceFirst("// ?", ""))
                        .collect(Collectors.joining("\n"));
            }  // it wasn't a description (just a stray comment ?)
        } else {
            if (forHeader) {
                // no blank line, so this is a description to the first 
                return "";
            }
            // description - go back and find any gap showing a last blank line
            int lastGoodLine = startCtx.getLine() - 1;        
            int currentIndex = lineTokens.size() - 1;
            while (currentIndex >= 0 && lineTokens.get(currentIndex).getLine() == lastGoodLine) {
                currentIndex--;
                lastGoodLine--;
            }
            List<String> content = new ArrayList<>();
            for (int j = currentIndex + 1; j <lineTokens.size(); j++) {
                content.add(lineTokens.get(j).getText().replaceFirst("// ?", ""));
            }
            return content.stream().collect(Collectors.joining("\n"));
        }
    }
    return "";
}
 
Example 12
Source File: BatfishLexerErrorListener.java    From batfish with Apache License 2.0 4 votes vote down vote up
@Override
public void syntaxError(
    Recognizer<?, ?> recognizer,
    Object offendingSymbol,
    int line,
    int charPositionInLine,
    String msg,
    RecognitionException e) {
  if (!_settings.getDisableUnrecognized() && _combinedParser.getRecovery()) {
    // recovery should have added error node for parse tree listener, so we can stop here
    return;
  }
  BatfishParser parser = _combinedParser.getParser();
  BatfishLexer lexer = _combinedParser.getLexer();
  List<String> ruleNames = Arrays.asList(parser.getRuleNames());
  ParserRuleContext ctx = parser.getContext();
  String ruleStack = ctx.toString(ruleNames);
  String[] lines = _combinedParser.getInputLines();
  int errorLineIndex = line - 1;
  if (!_settings.getDisableUnrecognized()) {
    // no recovery, so have to store error node for parse tree listener to process later
    parser
        .getContext()
        .addErrorNode(
            parser.createErrorNode(
                parser.getContext(),
                new UnrecognizedLineToken(lines[errorLineIndex], line, ruleStack)));
    return;
  }
  StringBuilder sb = new StringBuilder();
  sb.append(
      "lexer: " + _grammarName + ": line " + line + ":" + charPositionInLine + ": " + msg + "\n");
  sb.append("Current rule stack: '" + ruleStack + "'.\n");
  if (ctx.getStart() != null) {
    sb.append(
        "Current rule starts at: line: "
            + ctx.getStart().getLine()
            + ", col "
            + ctx.getStart().getCharPositionInLine()
            + "\n");
  }
  sb.append("Parse tree for current rule:\n");
  sb.append(
      ParseTreePrettyPrinter.print(ctx, _combinedParser, _settings.getPrintParseTreeLineNums()));
  sb.append("\n");
  sb.append("Lexer mode: " + lexer.getMode() + "\n");
  sb.append("Lexer state variables:\n");
  sb.append(lexer.printStateVariables());

  // collect context from text
  int errorContextStartLine = Math.max(errorLineIndex - _settings.getMaxParserContextLines(), 0);
  int errorContextEndLine =
      Math.min(errorLineIndex + _settings.getMaxParserContextLines(), lines.length);
  sb.append("Error context lines:\n");
  for (int i = errorContextStartLine; i < errorLineIndex; i++) {
    sb.append(String.format("%-11s%s\n", "   " + (i + 1) + ":", lines[i]));
  }
  sb.append(
      String.format("%-11s%s\n", ">>>" + (errorLineIndex + 1) + ":", lines[errorLineIndex]));
  for (int i = errorLineIndex + 1; i <= errorContextEndLine && i < lines.length; i++) {
    sb.append(String.format("%-11s%s\n", "   " + (i + 1) + ":", lines[i]));
  }

  String error = sb.toString();
  if (_settings.getThrowOnLexerError()) {
    throw new DebugBatfishException("\n" + error);
  } else {
    _combinedParser.getErrors().add(error);
  }
}
 
Example 13
Source File: Antlr4BasedCodeLocation.java    From openemm with GNU Affero General Public License v3.0 2 votes vote down vote up
/**
 * Create code location from given {@link ParserRuleContext}.
 * 
 * @param ctxt ParserRuleContext providing location information
 * 
 * @return CodeLocation from {@link ParserRuleContext}
 */
public static Antlr4BasedCodeLocation fromParserRuleContext(ParserRuleContext ctxt) {
	Token start = ctxt.getStart();
	
	return new Antlr4BasedCodeLocation(start.getLine(), start.getCharPositionInLine());
}