Example usage for org.antlr.v4.runtime ParserRuleContext getStart

List of usage examples for org.antlr.v4.runtime ParserRuleContext getStart

Introduction

In this page you can find the example usage for org.antlr.v4.runtime ParserRuleContext getStart.

Prototype

public Token getStart() 

Source Link

Document

Get the initial token in this context.

Usage

From source file:org.ballerinalang.langserver.completions.TreeVisitor.java

License:Open Source License

/**
 * Check whether the cursor resides within the given node type's parameter context.
 * Node name is used to identify the correct node
 * //from w  w  w .j av  a 2 s . com
 * @param nodeName              Name of the node
 * @param nodeType              Node type (Function, Resource, Action or Connector)
 * @return {@link Boolean}      Whether the cursor is within the parameter context
 */
private boolean isWithinParameterContext(String nodeName, String nodeType, SymbolEnv env) {
    ParserRuleContext parserRuleContext = lsContext.get(CompletionKeys.PARSER_RULE_CONTEXT_KEY);
    TokenStream tokenStream = lsContext.get(CompletionKeys.TOKEN_STREAM_KEY);
    String terminalToken = "";

    // If the parser rule context is not parameter context or parameter list context, we skipp the calculation
    if (!(parserRuleContext instanceof BallerinaParser.ParameterContext
            || parserRuleContext instanceof BallerinaParser.ParameterListContext)) {
        return false;
    }

    int startTokenIndex = parserRuleContext.getStart().getTokenIndex();
    ArrayList<String> terminalKeywords = new ArrayList<>(
            Arrays.asList(UtilSymbolKeys.ACTION_KEYWORD_KEY, UtilSymbolKeys.CONNECTOR_KEYWORD_KEY,
                    UtilSymbolKeys.FUNCTION_KEYWORD_KEY, UtilSymbolKeys.RESOURCE_KEYWORD_KEY));
    ArrayList<Token> filteredTokens = new ArrayList<>();
    Token openBracket = null;
    boolean isWithinParams = false;

    // Find the index of the closing bracket
    while (true) {
        if (startTokenIndex > tokenStream.size()) {
            // In the ideal case, should not reach this point
            startTokenIndex = -1;
            break;
        }
        Token token = tokenStream.get(startTokenIndex);
        String tokenString = token.getText();
        if (tokenString.equals(")")) {
            break;
        }
        startTokenIndex++;
    }

    // Backtrack the token stream to find a terminal token
    while (true) {
        if (startTokenIndex < 0) {
            break;
        }
        Token token = tokenStream.get(startTokenIndex);
        String tokenString = token.getText();
        if (terminalKeywords.contains(tokenString)) {
            terminalToken = tokenString;
            break;
        }
        if (token.getChannel() == Token.DEFAULT_CHANNEL) {
            filteredTokens.add(token);
        }
        startTokenIndex--;
    }

    Collections.reverse(filteredTokens);

    /*
    This particular logic identifies a matching pair of closing and opening bracket and then check whether the
    cursor is within those bracket pair
     */
    if (nodeName.equals(filteredTokens.get(0).getText()) && terminalToken.equals(nodeType)) {
        String tokenText;
        for (Token token : filteredTokens) {
            tokenText = token.getText();
            if (tokenText.equals("(")) {
                openBracket = token;
            } else if (tokenText.equals(")") && openBracket != null) {
                Position cursorPos = lsContext.get(DocumentServiceKeys.POSITION_KEY).getPosition();
                int openBLine = openBracket.getLine() - 1;
                int openBCol = openBracket.getCharPositionInLine();
                int closeBLine = token.getLine() - 1;
                int closeBCol = token.getCharPositionInLine();
                int cursorLine = cursorPos.getLine();
                int cursorCol = cursorPos.getCharacter();

                isWithinParams = (cursorLine > openBLine && cursorLine < closeBLine)
                        || (cursorLine == openBLine && cursorCol > openBCol && cursorLine < closeBLine)
                        || (cursorLine > openBLine && cursorCol < closeBCol && cursorLine == closeBLine)
                        || (cursorLine == openBLine && cursorLine == closeBLine && cursorCol >= openBCol
                                && cursorCol <= closeBCol);
                if (isWithinParams) {
                    break;
                } else {
                    openBracket = null;
                }
            }
        }
    }

    if (isWithinParams) {
        this.populateSymbols(this.resolveAllVisibleSymbols(env), env);
        forceTerminateVisitor();
    }

    return isWithinParams;
}

From source file:org.ballerinalang.langserver.completions.util.CompletionVisitorUtil.java

License:Open Source License

/**
 * Check whether the cursor resides within the given node type's parameter context.
 * Node name is used to identify the correct node
 *
 * @param nodeName              Name of the node
 * @param nodeType              Node type (Function, Resource, Action or Connector)
 * @param env                   Symbol Environment
 * @param lsContext             Language Server Operation Context
 * @param treeVisitor           Completion tree visitor instance
 * @return {@link Boolean}      Whether the cursor is within the parameter context
 *///from w  w  w  .  java2 s  .  co m
public static boolean isWithinParameterContext(String nodeName, String nodeType, SymbolEnv env,
        LSContext lsContext, TreeVisitor treeVisitor) {
    ParserRuleContext parserRuleContext = lsContext.get(CompletionKeys.PARSER_RULE_CONTEXT_KEY);
    TokenStream tokenStream = lsContext.get(CompletionKeys.TOKEN_STREAM_KEY);
    String terminalToken = "";

    // If the parser rule context is not parameter context or parameter list context, we skipp the calculation
    if (!(parserRuleContext instanceof BallerinaParser.ParameterContext
            || parserRuleContext instanceof BallerinaParser.ParameterListContext)) {
        return false;
    }

    int startTokenIndex = parserRuleContext.getStart().getTokenIndex();
    ArrayList<String> terminalKeywords = new ArrayList<>(
            Arrays.asList(UtilSymbolKeys.ACTION_KEYWORD_KEY, UtilSymbolKeys.CONNECTOR_KEYWORD_KEY,
                    UtilSymbolKeys.FUNCTION_KEYWORD_KEY, UtilSymbolKeys.RESOURCE_KEYWORD_KEY));
    ArrayList<Token> filteredTokens = new ArrayList<>();
    Token openBracket = null;
    boolean isWithinParams = false;

    // Find the index of the closing bracket
    while (true) {
        if (startTokenIndex > tokenStream.size()) {
            // In the ideal case, should not reach this point
            startTokenIndex = -1;
            break;
        }
        Token token = tokenStream.get(startTokenIndex);
        String tokenString = token.getText();
        if (tokenString.equals(")")) {
            break;
        }
        startTokenIndex++;
    }

    // Backtrack the token stream to find a terminal token
    while (true) {
        if (startTokenIndex < 0) {
            break;
        }
        Token token = tokenStream.get(startTokenIndex);
        String tokenString = token.getText();
        if (terminalKeywords.contains(tokenString)) {
            terminalToken = tokenString;
            break;
        }
        if (token.getChannel() == Token.DEFAULT_CHANNEL) {
            filteredTokens.add(token);
        }
        startTokenIndex--;
    }

    Collections.reverse(filteredTokens);

    /*
    This particular logic identifies a matching pair of closing and opening bracket and then check whether the
    cursor is within those bracket pair
     */
    if (nodeName.equals(filteredTokens.get(0).getText()) && terminalToken.equals(nodeType)) {
        String tokenText;
        for (Token token : filteredTokens) {
            tokenText = token.getText();
            if (tokenText.equals("(")) {
                openBracket = token;
            } else if (tokenText.equals(")") && openBracket != null) {
                Position cursorPos = lsContext.get(DocumentServiceKeys.POSITION_KEY).getPosition();
                int openBLine = openBracket.getLine() - 1;
                int openBCol = openBracket.getCharPositionInLine();
                int closeBLine = token.getLine() - 1;
                int closeBCol = token.getCharPositionInLine();
                int cursorLine = cursorPos.getLine();
                int cursorCol = cursorPos.getCharacter();

                isWithinParams = (cursorLine > openBLine && cursorLine < closeBLine)
                        || (cursorLine == openBLine && cursorCol > openBCol && cursorLine < closeBLine)
                        || (cursorLine > openBLine && cursorCol < closeBCol && cursorLine == closeBLine)
                        || (cursorLine == openBLine && cursorLine == closeBLine && cursorCol >= openBCol
                                && cursorCol <= closeBCol);
                if (isWithinParams) {
                    break;
                } else {
                    openBracket = null;
                }
            }
        }
    }

    if (isWithinParams) {
        treeVisitor.populateSymbols(treeVisitor.resolveAllVisibleSymbols(env), env);
        treeVisitor.forceTerminateVisitor();
    }

    return isWithinParams;
}

From source file:org.beetl.core.AntlrProgramBuilder.java

License:BSD License

protected BlockStatement parseBlock(List list, ParserRuleContext ctx) {
    pbCtx.enterBlock();//w w  w. j  a  va  2  s  .com
    ASTNode[] statements = new ASTNode[list.size()];
    List<Statement> nodes = new ArrayList<Statement>();
    boolean hasGoto = false;
    for (int i = 0; i < statements.length; i++) {
        nodes.add(parseStatment((ParserRuleContext) list.get(i)));

    }

    BlockStatement block = new BlockStatement(nodes.toArray(new Statement[0]), this.getBTToken(ctx.getStart()));
    this.checkGoto(block);
    pbCtx.exitBlock();
    return block;
}

From source file:org.cfeclipse.cfml.parser.docitems.ScriptItem.java

License:Open Source License

public ScriptItem(ParserRuleContext ctx, String name) {
    super(ctx.getStart().getLine(), ctx.getStart().getStartIndex(), ctx.getStop().getStopIndex(), name);
    // TODO Auto-generated constructor stub
}

From source file:org.elasticsearch.painless.AnalyzerUtility.java

License:Apache License

/**
 * A utility method to output consistent error messages.
 * @param ctx The ANTLR node the error occurred in.
 * @return The error message with tacked on line number and character position.
 *//*from ww  w  .j  av  a 2s.c om*/
static String error(final ParserRuleContext ctx) {
    return "Analyzer Error [" + ctx.getStart().getLine() + ":" + ctx.getStart().getCharPositionInLine() + "]: ";
}

From source file:org.elasticsearch.painless.Metadata.java

License:Apache License

/**
 * A utility method to output consistent error messages.
 * @param ctx The ANTLR node the error occurred in.
 * @return The error message with tacked on line number and character position.
 *//*from   www.j a  v a2s.com*/
static String error(final ParserRuleContext ctx) {
    return "Error [" + ctx.getStart().getLine() + ":" + ctx.getStart().getCharPositionInLine() + "]: ";
}

From source file:org.elasticsearch.painless.WriterUtility.java

License:Apache License

/**
 * A utility method to output consistent error messages.
 * @param ctx The ANTLR node the error occurred in.
 * @return The error message with tacked on line number and character position.
 *///from w  ww.j a  v  a  2 s. c o  m
static String error(final ParserRuleContext ctx) {
    return "Writer Error [" + ctx.getStart().getLine() + ":" + ctx.getStart().getCharPositionInLine() + "]: ";
}

From source file:org.elasticsearch.plan.a.Adapter.java

License:Apache License

static String error(final ParserRuleContext ctx) {
    return "Error [" + ctx.getStart().getLine() + ":" + ctx.getStart().getCharPositionInLine() + "]: ";
}

From source file:org.elasticsearch.xpack.sql.parser.AbstractBuilder.java

License:Open Source License

static Location source(ParserRuleContext parserRuleContext) {
    Check.notNull(parserRuleContext, "parserRuleContext is null");
    return source(parserRuleContext.getStart());
}

From source file:org.geotoolkit.cql.JCQLTextPane.java

License:Open Source License

private void syntaxHighLight(ParseTree tree, StyledDocument doc, AtomicInteger position) {

    if (tree instanceof ParserRuleContext) {
        final ParserRuleContext prc = (ParserRuleContext) tree;
        if (prc.exception != null) {
            //error nodes
            final Token tokenStart = prc.getStart();
            Token tokenEnd = prc.getStop();
            if (tokenEnd == null)
                tokenEnd = tokenStart;/*from  w w  w  .jav  a2  s.c  o m*/
            final int offset = tokenStart.getStartIndex();
            final int length = tokenEnd.getStopIndex() - tokenStart.getStartIndex() + 1;
            doc.setCharacterAttributes(offset, length, styleError, true);
            return;
        }

        //special case for functions
        if (prc instanceof CQLParser.ExpressionTermContext) {
            final CQLParser.ExpressionTermContext ctx = (CQLParser.ExpressionTermContext) prc;
            if (ctx.NAME() != null && ctx.LPAREN() != null) {
                final int nbChild = tree.getChildCount();
                for (int i = 0; i < nbChild; i++) {
                    final ParseTree pt = tree.getChild(i);
                    if (pt instanceof TerminalNode
                            && ((TerminalNode) pt).getSymbol().getType() == CQLLexer.NAME) {
                        final TerminalNode tn = (TerminalNode) pt;
                        // if index<0 = missing token
                        final Token token = tn.getSymbol();
                        final int offset = token.getStartIndex();
                        final int length = token.getStopIndex() - token.getStartIndex() + 1;
                        position.addAndGet(length);
                        doc.setCharacterAttributes(offset, length, styleFunction, true);
                    } else {
                        syntaxHighLight(pt, doc, position);
                    }
                }
                return;
            }
        }

    }

    if (tree instanceof TerminalNode) {
        final TerminalNode tn = (TerminalNode) tree;
        // if index<0 = missing token
        final Token token = tn.getSymbol();
        final int offset = token.getStartIndex();
        final int length = token.getStopIndex() - token.getStartIndex() + 1;
        position.addAndGet(length);

        switch (token.getType()) {

        case CQLLexer.COMMA:
        case CQLLexer.UNARY:
        case CQLLexer.MULT:
            doc.setCharacterAttributes(offset, length, styleDefault, true);
            break;

        // EXpressions -------------------------------------------------
        case CQLLexer.TEXT:
        case CQLLexer.INT:
        case CQLLexer.FLOAT:
        case CQLLexer.DATE:
        case CQLLexer.DURATION_P:
        case CQLLexer.DURATION_T:
        case CQLLexer.POINT:
        case CQLLexer.LINESTRING:
        case CQLLexer.POLYGON:
        case CQLLexer.MPOINT:
        case CQLLexer.MLINESTRING:
        case CQLLexer.MPOLYGON:
            doc.setCharacterAttributes(offset, length, styleLiteral, true);
            break;
        case CQLLexer.PROPERTY_NAME:
            doc.setCharacterAttributes(offset, length, stylePropertyName, true);
            break;
        case CQLLexer.NAME:
            if (tree.getChildCount() == 0) {
                //property name
                doc.setCharacterAttributes(offset, length, stylePropertyName, true);
            } else {
                //function name
                doc.setCharacterAttributes(offset, length, styleFunction, true);
            }
            break;
        case CQLLexer.RPAREN:
        case CQLLexer.LPAREN:
            doc.setCharacterAttributes(offset, length, styleParenthese, true);
            break;

        case CQLLexer.COMPARE:
        case CQLLexer.LIKE:
        case CQLLexer.IS:
        case CQLLexer.BETWEEN:
        case CQLLexer.IN:
            doc.setCharacterAttributes(offset, length, styleOperator, true);
            break;
        case CQLLexer.AND:
        case CQLLexer.OR:
        case CQLLexer.NOT:
            doc.setCharacterAttributes(offset, length, styleBinary, true);
            break;
        case CQLLexer.BBOX:
        case CQLLexer.BEYOND:
        case CQLLexer.CONTAINS:
        case CQLLexer.CROSSES:
        case CQLLexer.DISJOINT:
        case CQLLexer.DWITHIN:
        case CQLLexer.EQUALS:
        case CQLLexer.INTERSECTS:
        case CQLLexer.OVERLAPS:
        case CQLLexer.TOUCHES:
        case CQLLexer.WITHIN:
            doc.setCharacterAttributes(offset, length, styleBinary, true);
            break;
        default:
            doc.setCharacterAttributes(offset, length, styleError, true);
            break;
        }
    }

    final int nbChild = tree.getChildCount();
    for (int i = 0; i < nbChild; i++) {
        syntaxHighLight(tree.getChild(i), doc, position);
    }
}