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

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

Introduction

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

Prototype

@Override
public String getText() 

Source Link

Document

Return the combined text of all child nodes.

Usage

From source file:com.blazebit.persistence.parser.expression.JPQLSelectExpressionVisitorImpl.java

License:Apache License

public Expression visitMacroExpression(String macroName, ParserRuleContext ctx) {
    List<Expression> funcArgs = new ArrayList<Expression>(ctx.getChildCount());
    // Special handling of empty invocation, the position 2 contains an empty child node
    if (ctx.getChildCount() != 4 || !ctx.getChild(2).getText().isEmpty()) {
        for (int i = 0; i < ctx.getChildCount(); i++) {
            if (!(ctx.getChild(i) instanceof TerminalNode)) {
                funcArgs.add(ctx.getChild(i).accept(this));
            }// w  w  w.  j  ava 2  s  . c o m
        }
    }

    MacroFunction macro = macros.get(macroName);
    if (macro == null) {
        throw new SyntaxErrorException("The macro '" + macroName + "' could not be found in the macro map!");
    }
    if (usedMacros != null) {
        usedMacros.add(macroName);
    }
    try {
        return macro.apply(funcArgs);
    } catch (RuntimeException ex) {
        throw new IllegalArgumentException("Could not apply the macro for the expression: " + ctx.getText(),
                ex);
    }
}

From source file:com.github.drrb.rust.netbeans.LoggingParseListener.java

License:Open Source License

@Override
public void enterEveryRule(ParserRuleContext ctx) {
    log("Entering %s: %s", ctx.getClass().getSimpleName(), ctx.getText());
    depth++;/*  w  w  w  .  j a v a  2  s .  com*/
}

From source file:com.github.drrb.rust.netbeans.LoggingParseListener.java

License:Open Source License

@Override
public void exitEveryRule(ParserRuleContext ctx) {
    log("Exiting  %s: %s", ctx.getClass().getSimpleName(), ctx.getText());
    depth--;//  w  ww.  j a  v a  2s .  c  o m
}

From source file:com.ibm.bi.dml.parser.python.PydmlSyntacticValidator.java

License:Open Source License

private void setFileLineColumn(Expression expr, ParserRuleContext ctx) {
    // expr.setFilename(helper.getCurrentFileName());
    String txt = ctx.getText();
    expr.setFilename(_currentPath);//from  w  w  w .  j ava  2s. c  o m
    expr.setBeginLine(ctx.start.getLine());
    expr.setBeginColumn(ctx.start.getCharPositionInLine());
    expr.setEndLine(ctx.stop.getLine());
    expr.setEndColumn(ctx.stop.getCharPositionInLine());
    if (expr.getBeginColumn() == expr.getEndColumn() && expr.getBeginLine() == expr.getEndLine()
            && txt.length() > 1) {
        expr.setEndColumn(expr.getBeginColumn() + txt.length() - 1);
    }
}

From source file:com.ibm.bi.dml.parser.python.PydmlSyntacticValidator.java

License:Open Source License

private void setFileLineColumn(Statement stmt, ParserRuleContext ctx) {
    String txt = ctx.getText();
    stmt.setFilename(helper.getCurrentFileName());
    stmt.setBeginLine(ctx.start.getLine());
    stmt.setBeginColumn(ctx.start.getCharPositionInLine());
    stmt.setEndLine(ctx.stop.getLine());
    stmt.setEndColumn(ctx.stop.getCharPositionInLine());
    if (stmt.getBeginColumn() == stmt.getEndColumn() && stmt.getBeginLine() == stmt.getEndLine()
            && txt.length() > 1) {
        stmt.setEndColumn(stmt.getBeginColumn() + txt.length() - 1);
    }/*  w w  w  .j a  va2s.  c  om*/
}

From source file:com.satisfyingstructures.J2S.J2SConvertBasicFor.java

License:Open Source License

private String convertBasicForStatementToForInLoopOrSayWhyNot(ParserRuleContext ctx) {
    int forRule = ctx.getRuleIndex();
    if (forRule != Java8Parser.RULE_basicForStatement && forRule != Java8Parser.RULE_basicForStatementNoShortIf)
        return "statement kind is not as expected"; // not our expected parameter type
    // Get to know more about our for statement
    // 'for' '(' forInit? ';' expression? ';' forUpdate? ')' ( statement | statementNoShortIf )
    Boolean noShortIf = forRule == Java8Parser.RULE_basicForStatementNoShortIf;
    Java8Parser.ForInitContext forInitCtx = ctx.getChild(Java8Parser.ForInitContext.class, 0);
    Java8Parser.ExpressionContext expressionCtx = ctx.getChild(Java8Parser.ExpressionContext.class, 0);
    Java8Parser.ForUpdateContext forUpdateCtx = ctx.getChild(Java8Parser.ForUpdateContext.class, 0);
    ParserRuleContext statementCtx = ctx.getChild(
            noShortIf ? Java8Parser.StatementNoShortIfContext.class : Java8Parser.StatementContext.class, 0);
    ParserRuleContext statementSubCtx = statementCtx.getChild(ParserRuleContext.class, 0);
    ParserRuleContext statementSubSubCtx = statementSubCtx.getChild(ParserRuleContext.class, 0);
    Boolean statementisEmpty = statementSubSubCtx.getRuleIndex() == Java8Parser.RULE_emptyStatement;
    /*/* ww  w .  j av a 2  s  .  co m*/
    'for' '(' forInit? ';' expression? ';' forUpdate? ')' ( statement | statementNoShortIf )
            
    Swift 3.0 has got rid of for(;;) statements for stong business cases such as...
        'It is rarely used'
        'not very Swift-like'
        'The value of this construct is limited'
    ...and other total crap.
            
    We can convert simple equivalents of
        for ( i = startvalue ; i < endvalue ; i += step)
    to
        for i in start..<end
    or
        for i in start.stride(to: end by: step)
            
    To identify this we look for
    1) have a forUpdate, which...
        a) operates on a single loop variable
            forUpdate().statementExpressionList().statementExpression().count()==1
        b) incorporates increment or decrement by a constant step (++i,i++,i+=step,--i,i--,i-=step,)
            statementExpression rule is RULE_(assignment|preinc|postinc|predec|postdec)
        c) operates on the same variable tested in expression (compare - 2b)
    2) have an expression, which...
        a) should be a simple comparison (<,<=,!=,>,>=, implicit non-zero)
        b) one side should be same as the loop var (compare - 1c)
        c) other side should not mutate within the loop - we can't tell this, too difficult
    3) forInit
        a) must be
            i) empty(start with loop var existing value), or
            ii) simple init of a single loop var, or
            iii) simple declaration of a loop var
    */
    // 1) Update statement. We need one...
    if (null == forUpdateCtx)
        return "it lacks an update statement";
    // 1a) and it must operate on a single variable
    if (forUpdateCtx.statementExpressionList().getChildCount() != 1)
        return "there is more than one expression in the update statement";
    // 1b) and it must be a simple increment or decrement
    Java8Parser.StatementExpressionContext updateStatementExpressionCtx = forUpdateCtx.statementExpressionList()
            .statementExpression(0);
    //  statementExpression : assignment | preIncrementExpression | preDecrementExpression
    //                                   | postIncrementExpression | postDecrementExpression
    //                                   | methodInvocation | classInstanceCreationExpression
    ParserRuleContext updateExpressionCtx = updateStatementExpressionCtx.getChild(ParserRuleContext.class, 0);
    int updateExpressionRule = updateExpressionCtx.getRuleIndex();
    boolean ascending_sequence;
    boolean open_interval;
    ParserRuleContext stepExpressionCtx = null;
    switch (updateExpressionRule) {

    // unaryExpression : preIncrementExpression | preDecrementExpression
    //                 | '+' unaryExpression | '-' unaryExpression
    //                 | unaryExpressionNotPlusMinus
    // preDecrementExpression : '--' unaryExpression
    // preIncrementExpression : '++' unaryExpression
    case Java8Parser.RULE_preDecrementExpression:
        ascending_sequence = false;
        break;
    case Java8Parser.RULE_preIncrementExpression:
        ascending_sequence = true;
        break;

    // postfixExpression : ( primary | expressionName ) ( '++' | '--')*
    // postIncrementExpression : postfixExpression '++'
    // postDecrementExpression : postfixExpression '--'
    case Java8Parser.RULE_postDecrementExpression:
        ascending_sequence = false;
        break;
    case Java8Parser.RULE_postIncrementExpression:
        ascending_sequence = true;
        break;

    // assignment : leftHandSide assignmentOperator expression
    // leftHandSide : expressionName | fieldAccess | arrayAccess
    case Java8Parser.RULE_assignment:
        if (null != updateStatementExpressionCtx.assignment().leftHandSide().arrayAccess())
            return "cant convert a loop variable that is an array element";
        TerminalNode node = updateStatementExpressionCtx.assignment().assignmentOperator()
                .getChild(TerminalNode.class, 0);
        switch (node.getSymbol().getType()) {
        case Java8Parser.ADD_ASSIGN:
            ascending_sequence = true;
            break;
        case Java8Parser.SUB_ASSIGN:
            ascending_sequence = false;
            break;
        case Java8Parser.ASSIGN: // possibilities too complex to warrant extracting simple a=a+1 cases
        default:
            return "potentially too complex to create a sequence from this update operation";
        }
        stepExpressionCtx = updateStatementExpressionCtx.assignment().expression();
        break;
    default: // methodInvocation | classInstanceCreationExpression
        return "the expression in the update statement is too complex";
    }
    // In each of the cases that we have not rejected, the loop variable is in the first child rule context of the
    // update statement. Get the text of the variable, rather than analysing the graph any further, as the
    // possibilities are endless; all that we require is that the loop variable text matches that in the text
    // expression and the init expression.
    ParserRuleContext loopVariable_updated_Ctx = updateExpressionCtx.getChild(ParserRuleContext.class, 0);
    String loopVariableTxt = loopVariable_updated_Ctx.getText(); // we want original text

    // 2) Expression
    if (null == expressionCtx)
        return "it lacks a test expression";
    // expression : lambdaExpression | assignmentExpression
    if (null != expressionCtx.lambdaExpression())
        return "cannot convert a lambda expression";
    // assignmentExpression : conditionalExpression | assignment
    if (null != expressionCtx.assignmentExpression().assignment())
        return "cannot convert an assignment within the test expression";
    // 2a) must be a simple relation:
    // Descend the chain of expression rule pass-through branches until we find the one that is significant, then
    // test to see if expression contains a terminal that is one of !=, <, <=, >, >=.
    ParserRuleContext testExpressionCtx = J2SGrammarUtils.descendToSignificantExpression(expressionCtx);
    int testExpressionRule = testExpressionCtx.getRuleIndex();
    TerminalNode node = testExpressionCtx.getChild(TerminalNode.class, 0);
    int testOperatorType = null != node ? node.getSymbol().getType() : 0;
    switch (testOperatorType) {
    case Java8Parser.NOTEQUAL:
        open_interval = true;
        break;
    case Java8Parser.LE:
        open_interval = false;
        break;
    case Java8Parser.GE:
        open_interval = false;
        break;

    case Java8Parser.LT: // can occur in relational and shift expressions
    case Java8Parser.GT: // can occur in relational and shift expressions
        if (testExpressionRule == Java8Parser.RULE_relationalExpression) {
            open_interval = true;
            break;
        }
    default:
        return "can only convert test expressions that use !=, <, <=, > or >=";
    }
    // 2b) relation must be testing same var as changed in update expression
    // The loop variable could be on the left or the right of the comparison operator
    int i;
    ParserRuleContext loopVariable_tested_Ctx = null;
    for (i = 0; i < 2; i++) {
        loopVariable_tested_Ctx = testExpressionCtx.getChild(ParserRuleContext.class, i);
        if (null != loopVariable_tested_Ctx && loopVariableTxt.equals(loopVariable_tested_Ctx.getText()))
            break; // found matching loop variable
        loopVariable_tested_Ctx = null;
    }
    if (null == loopVariable_tested_Ctx || (i == 1 && testExpressionCtx.getChildCount() > 3))
        return "the test expression must be testing the same variable as changed in update expression";
    ParserRuleContext terminalValueCtx = testExpressionCtx.getChild(ParserRuleContext.class, i ^ 1);
    // 2c) the terminal value side should not mutate within the loop
    // - way too difficult for us to determine this

    // 3) Loop init expression. Must be either...
    ParserRuleContext initialValueCtx;
    if (null == forInitCtx) // a) empty
    {
        // Using the loop variable's existing value from outside the scope
        initialValueCtx = loopVariable_tested_Ctx;
    } else if (null != forInitCtx.statementExpressionList()) // b) a simple init of a single loop var
    {
        /*
                // Could not convert...
                // for (i = 0; i<10; i++)
                // ...to a for..in statement because can only work with an assignment expression for loop variable initialisation.
                i = 0; while i<10  {j += 1 i += 1; }
        */
        if (forInitCtx.statementExpressionList().getChildCount() != 1)
            return "can only work with initialisation of a single loop variable";
        Java8Parser.StatementExpressionContext initExpressionCtx = forInitCtx.statementExpressionList()
                .statementExpression(0);
        if (null == initExpressionCtx.assignment())
            return "can only work with an assignment expression for loop variable initialisation";
        if (!loopVariableTxt.equals(initExpressionCtx.assignment().leftHandSide().getText()))
            return "the initialised variable is different from the updated variable"; // different to the loop variable
        initialValueCtx = initExpressionCtx.assignment().expression();
    } else if (null != forInitCtx.localVariableDeclaration()) // c) a simple decl of a single loop var
    {
        // localVariableDeclaration : variableModifier* unannType variableDeclaratorList
        Java8Parser.VariableDeclaratorListContext vdlc = forInitCtx.localVariableDeclaration()
                .variableDeclaratorList();
        // variableDeclaratorList : variableDeclarator (',' variableDeclarator)*
        if (vdlc.getChildCount() != 1)
            return "can only work with declaration of a single loop variable";
        Java8Parser.VariableDeclaratorContext vdc = vdlc.variableDeclarator(0);
        // variableDeclarator : variableDeclaratorId ('=' variableInitializer)?
        if (!loopVariableTxt.equals(vdc.getChild(0).getText()))
            return "the declared loop variable is be different from the updated variable";
        initialValueCtx = vdc.variableInitializer();
        if (null == initialValueCtx)
            return "there is no initialiser for the loop variable";
    } else
        return "loop initialisation is in unexpected form";

    // Now we have all the components we need
    String forInLoopText;
    // Use actual text with replacements
    String initialValueTxt = rewriter.getText(initialValueCtx);
    String terminalValueTxt = rewriter.getText(terminalValueCtx);
    // !!!: watch out...
    // if we use the actual text from the update expression, we can find that the pre/post-inc/dec has been
    // converted to the add/sub-assign form and because structure is lost when rewriting, the new form can
    // stick to the variable when we retrieve it. There's no easy solution for this (and any similar occurrences),
    // but we side step it by getting the text of loop variable from the test expression:
    loopVariableTxt = rewriter.getText(loopVariable_tested_Ctx);
    if (null != stepExpressionCtx || !ascending_sequence) {
        String stepExpressionText = stepExpressionCtx == null ? "-1"
                : ascending_sequence ? rewriter.getText(stepExpressionCtx)
                        : "-(" + rewriter.getText(stepExpressionCtx) + ")";
        forInLoopText = "for " + loopVariableTxt + " in " + loopVariableTxt + ".stride(from: " + initialValueTxt
                + (open_interval ? ", to: " : ", through: ") + terminalValueTxt + ", by: " + stepExpressionText
                + ")";
    } else {
        forInLoopText = "for " + loopVariableTxt + " in " + initialValueTxt
                + (open_interval ? " ..< " : " ... ") + terminalValueTxt;
    }

    Token startToken = ctx.getToken(Java8Parser.FOR, 0).getSymbol();
    Token endToken = ctx.getToken(Java8Parser.RPAREN, 0).getSymbol();

    CharStream cs = startToken.getInputStream();
    String originalExpressionTxt = cs.getText(Interval.of(startToken.getStartIndex(), endToken.getStopIndex()));
    rewriter.insertComment(originalExpressionTxt + " converted to", ctx,
            J2SRewriter.CommentWhere.beforeLineBreak);

    int startIndex = startToken.getTokenIndex();
    int endIndex = endToken.getTokenIndex();

    // Problem: (see notes in J2SRewriter.replaceAndAdjustWhitespace) Before converting to for-in, the loop will
    // also have had parentheses removed (and other transforms); rewriter may have coallesced some of the changes
    // so that the old end boundary no longer exists. (- a shortcoming of TokenStreamRewriter)
    // Workaround: test if endIndex is straddled by changed interval, and if so, extend our interval to the end of
    // the change. (Pretty horrendous to have to work around this here, but I don't yet see an easy way of fixing
    // the underlying problem or a generalised way of working around it.)
    Interval interval = rewriter.getChangedIntervalContaining(endIndex, endIndex);
    if (null != interval && interval.a <= endIndex && interval.b > endIndex)
        endIndex = interval.b;

    rewriter.replaceAndAdjustWhitespace(startIndex, endIndex, forInLoopText);

    return null;
}

From source file:com.satisfyingstructures.J2S.J2SConverter.java

License:Open Source License

private void mapPrimitiveTypeInContext(ParserRuleContext ctx) {
    String stringInJava = ctx.getText();
    String stringInSwift = types.map(stringInJava);
    if (null != stringInSwift && !stringInSwift.equals(stringInJava))
        rewriter.replace(ctx, stringInSwift);
}

From source file:com.satisfyingstructures.J2S.J2SConverter.java

License:Open Source License

private void convertVariableDeclaration(ParserRuleContext declarationCtx) {
    // Read comments in exitVariableDeclaratorId just above!

    int declarationRuleIndex = declarationCtx.getRuleIndex();
    Class<? extends ParserRuleContext> modifierContextClass = Java8Parser.VariableModifierContext.class;
    Constness constness = Constness.unknown;
    boolean isOptional = false;
    boolean hasDeclaratorList = false;
    boolean enhancedFor = false;

    switch (declarationRuleIndex) {
    case Java8Parser.RULE_constantDeclaration:
        modifierContextClass = Java8Parser.ConstantModifierContext.class;
        hasDeclaratorList = true;/*  w w w  .j a va  2 s. co  m*/
        constness = Constness.explicit;
        break;
    case Java8Parser.RULE_fieldDeclaration:
        modifierContextClass = Java8Parser.FieldModifierContext.class;
        hasDeclaratorList = true;
        break;
    case Java8Parser.RULE_localVariableDeclaration:
        hasDeclaratorList = true;
        break;
    case Java8Parser.RULE_resource:
        constness = Constness.explicit;
        break;
    case Java8Parser.RULE_formalParameter:
    case Java8Parser.RULE_lastFormalParameter:
        constness = Constness.implicit;
        break;
    case Java8Parser.RULE_catchFormalParameter:
        constness = Constness.explicit;
        break;
    case Java8Parser.RULE_enhancedForStatement:
    case Java8Parser.RULE_enhancedForStatementNoShortIf:
        enhancedFor = true;
        constness = Constness.implicit;
        break;
    default:
        return; // not our expected parameter type
    }

    // Look for and remove 'final', '@NonNull' and '@Nullable' in modifiers
    for (ParserRuleContext modifierCtx : declarationCtx.getRuleContexts(modifierContextClass)) {
        TerminalNode tn = modifierCtx.getChild(TerminalNode.class, 0);
        if (null == tn) {
            String annotationText = modifierCtx.getText();
            switch (annotationText) {
            // some spelling variations here...
            case "@Nonnull": // javax.annotation.NotNull
            case "@NonNull": // android.support.annotation.NonNull
                             // edu.umd.cs.findbugs.annotations.NonNull
            case "@NotNull": // org.jetbrains.annotations.NotNull
                isOptional = false;
                break;
            case "@Nullable":
                isOptional = true;
                break;
            default:
                continue;
            }
        } else {
            Token token = tn.getSymbol();
            mapModifierToken(token);
            switch (token.getType()) {
            case Java8Parser.FINAL:
                if (constness == Constness.unknown)
                    constness = Constness.explicit;
                break;
            default:
                continue;
            }
        }
        rewriter.deleteAndAdjustWhitespace(modifierCtx);
    }

    // Move trailing dimensions to wrap the type. First any dimensions binding to the declarator id and
    // then any dimensions binding to the right of the type.
    // a) start by finding the type context that will be wrapped.
    Java8Parser.UnannTypeContext unannTypeCtx = null;
    Java8Parser.UnannReferenceTypeContext unannReferenceTypeCtx = null;
    Java8Parser.UnannArrayTypeContext unannArrayTypeCtx = null;
    Java8Parser.DimsContext outerDimsCtx = null;
    ParserRuleContext typeCtx = null;
    if (declarationRuleIndex == Java8Parser.RULE_catchFormalParameter)
        typeCtx = declarationCtx.getChild(Java8Parser.CatchTypeContext.class, 0);
    else
        typeCtx = unannTypeCtx = declarationCtx.getChild(Java8Parser.UnannTypeContext.class, 0);
    if (null != unannTypeCtx)
        if (null != (unannReferenceTypeCtx = unannTypeCtx.unannReferenceType())
                && null != (unannArrayTypeCtx = unannReferenceTypeCtx.unannArrayType())) {
            typeCtx = unannArrayTypeCtx.getChild(ParserRuleContext.class, 0);
            outerDimsCtx = unannArrayTypeCtx.dims();
        }
    // b) process dimensions attached to declarator ids
    // ...process inside blocks below
    // c) process dimensions attached to type
    // ...process inside blocks below

    // Now insert unannTypeText at end of each variableDeclaratorId if necessary:
    ParserRuleContext ctx, varInitCtx;
    Java8Parser.VariableDeclaratorIdContext varIdCtx;
    Java8Parser.DimsContext innerDimsCtx = null;
    String unannTypeText;
    if (hasDeclaratorList) {
        // Iterate over the list of declarator-initialiser pairs backwards so that variable lists without
        // intialisers and with explicit enough types, just pick up the type from the end of the list, i.e.
        // so that we generate var a, b, c: Int, and not var a: Int, b: Int, c: Int.
        ListIterator<Java8Parser.VariableDeclaratorContext> iter;
        List<Java8Parser.VariableDeclaratorContext> list;
        String followingUnannTypeText = null;
        boolean followingVarHasExplicitType = false;
        boolean hasInitialiser;

        ctx = declarationCtx.getChild(Java8Parser.VariableDeclaratorListContext.class, 0);
        list = ctx.getRuleContexts(Java8Parser.VariableDeclaratorContext.class);
        iter = list.listIterator(list.size());
        unannTypeText = null;

        while (iter.hasPrevious()) {
            ctx = iter.previous();
            varIdCtx = ctx.getRuleContext(Java8Parser.VariableDeclaratorIdContext.class, 0);

            // Wrap the inner type string with array dimensions if we have them. Have to do this for each variable,
            // because they can have different dimensionality.
            followingUnannTypeText = unannTypeText;
            unannTypeText = rewriter.getText(typeCtx);
            if (null != (innerDimsCtx = varIdCtx.dims())) {
                unannTypeText = wrapTypeStringWithDims(unannTypeText, innerDimsCtx);
                rewriter.delete(innerDimsCtx);
            }
            if (null != outerDimsCtx)
                unannTypeText = wrapTypeStringWithDims(unannTypeText, outerDimsCtx);

            varInitCtx = ctx.getRuleContext(Java8Parser.VariableInitializerContext.class, 0);
            if (null != varInitCtx)
                varInitCtx = varInitCtx.getChild(ParserRuleContext.class, 0); // expression or arrayInitializer
            hasInitialiser = null != varInitCtx;

            // In the basic case, we have to qualify the variable with its type, but we can omit this if it has an
            // initialiser that completely implies the type, or it has no initialiser and has the same type as the
            // a contiguously following variable with explicit type.
            if (hasInitialiser
                    ? !isVariableTypeCompletelyImpliedByInitializer(unannTypeCtx, varInitCtx,
                            /*inEnhancedFor:*/false)
                    : !followingVarHasExplicitType || null == followingUnannTypeText
                            || !unannTypeText.equals(followingUnannTypeText)) {
                rewriter.insertAfter(varIdCtx, ": " + unannTypeText + (isOptional ? "?" : ""));
                followingVarHasExplicitType = !hasInitialiser;
            }
        }
    } else {
        varIdCtx = declarationCtx.getRuleContext(Java8Parser.VariableDeclaratorIdContext.class, 0);
        unannTypeText = rewriter.getText(typeCtx);
        if (null != (innerDimsCtx = varIdCtx.dims())) {
            unannTypeText = wrapTypeStringWithDims(unannTypeText, innerDimsCtx);
            rewriter.delete(innerDimsCtx);
        }
        if (null != outerDimsCtx)
            unannTypeText = wrapTypeStringWithDims(unannTypeText, outerDimsCtx);

        varInitCtx = null;
        if (declarationRuleIndex == Java8Parser.RULE_resource
                || declarationRuleIndex == Java8Parser.RULE_enhancedForStatement
                || declarationRuleIndex == Java8Parser.RULE_enhancedForStatementNoShortIf)
            varInitCtx = declarationCtx.getRuleContext(Java8Parser.ExpressionContext.class, 0);

        if (declarationRuleIndex == Java8Parser.RULE_catchFormalParameter)
            rewriter.insertAfter(varIdCtx, " as " + unannTypeText);
        else if (!isVariableTypeCompletelyImpliedByInitializer(unannTypeCtx, varInitCtx, enhancedFor))
            rewriter.insertAfter(varIdCtx, ": " + unannTypeText + (isOptional ? "?" : ""));

        // In parameter lists, add an anonymizing argument label, as argument labels not used in java method/function calls
        if (declarationRuleIndex == Java8Parser.RULE_formalParameter
                || declarationRuleIndex == Java8Parser.RULE_lastFormalParameter)
            rewriter.insertBefore(varIdCtx, "_ ");
    }

    // Finally replace the complete type context with let/var/-
    // in an enhancedForStatement, the loop var is implicitly const, but can be made variable with var if it is
    // to be modified inside the loop; we could check for this, but its a rare scenario, and a lot of work, so no.
    if (null != unannTypeCtx)
        typeCtx = unannTypeCtx;
    switch (constness) {
    case explicit:
        rewriter.replace(typeCtx, "let");
        break;
    case implicit:
        rewriter.deleteAndAdjustWhitespace(typeCtx);
        break;
    case variable:
        rewriter.replace(typeCtx, "var");
        break;
    // if still unknown, then assume variable...
    default:
        rewriter.replace(typeCtx, "var");
        break;
    }
}

From source file:com.yahoo.yqlplus.language.parser.ProgramParser.java

private OperatorNode<SequenceOperator> convertSource(ParserRuleContext sourceSpecNode, Scope scope) {

    // DataSources
    String alias;//from w  w  w . j  a v  a 2  s. c  o  m
    OperatorNode<SequenceOperator> result;
    ParserRuleContext dataSourceNode = sourceSpecNode;
    ParserRuleContext aliasContext = null;
    //data_source
    //:   call_source
    //|   LPAREN source_statement RPAREN
    //|   sequence_source
    //;
    if (sourceSpecNode instanceof Source_specContext) {
        dataSourceNode = (ParserRuleContext) sourceSpecNode.getChild(0);
        if (sourceSpecNode.getChildCount() == 2) {
            aliasContext = (ParserRuleContext) sourceSpecNode.getChild(1);
        }
        if (dataSourceNode.getChild(0) instanceof Call_sourceContext
                || dataSourceNode.getChild(0) instanceof Sequence_sourceContext) {
            dataSourceNode = (ParserRuleContext) dataSourceNode.getChild(0);
        }
        //TODO double check whether comment out this is correct            
        //            else { //source_statement
        //                dataSourceNode = (ParserRuleContext)dataSourceNode.getChild(1); 
        //            }
    }
    switch (getParseTreeIndex(dataSourceNode)) {
    case yqlplusParser.RULE_write_data_source:
    case yqlplusParser.RULE_call_source: {
        List<String> names = readName(
                (Namespaced_nameContext) dataSourceNode.getChild(Namespaced_nameContext.class, 0));
        alias = assignAlias(names.get(names.size() - 1), aliasContext, scope);
        List<OperatorNode<ExpressionOperator>> arguments = ImmutableList.of();
        ArgumentsContext argumentsContext = dataSourceNode.getRuleContext(ArgumentsContext.class, 0);
        if (argumentsContext != null) {
            List<ArgumentContext> argumentContexts = argumentsContext.argument();
            arguments = Lists.newArrayListWithExpectedSize(argumentContexts.size());
            for (ArgumentContext argumentContext : argumentContexts) {
                arguments.add(convertExpr(argumentContext, scope));
            }
        }
        if (names.size() == 1 && scope.isVariable(names.get(0))) {
            String ident = names.get(0);
            if (arguments.size() > 0) {
                throw new ProgramCompileException(toLocation(scope, argumentsContext),
                        "Invalid call-with-arguments on local source '%s'", ident);
            }
            result = OperatorNode.create(toLocation(scope, dataSourceNode), SequenceOperator.EVALUATE,
                    OperatorNode.create(toLocation(scope, dataSourceNode), ExpressionOperator.VARREF, ident));
        } else {
            result = OperatorNode.create(toLocation(scope, dataSourceNode), SequenceOperator.SCAN,
                    scope.resolvePath(names), arguments);
        }
        break;
    }
    case yqlplusParser.RULE_sequence_source: {
        IdentContext identContext = dataSourceNode.getRuleContext(IdentContext.class, 0);
        String ident = identContext.getText();
        if (!scope.isVariable(ident)) {
            throw new ProgramCompileException(toLocation(scope, identContext),
                    "Unknown variable reference '%s'", ident);
        }
        alias = assignAlias(ident, aliasContext, scope);
        result = OperatorNode.create(toLocation(scope, dataSourceNode), SequenceOperator.EVALUATE,
                OperatorNode.create(toLocation(scope, dataSourceNode), ExpressionOperator.VARREF, ident));
        break;
    }
    case yqlplusParser.RULE_source_statement: {
        alias = assignAlias(null, dataSourceNode, scope);
        result = convertQuery(dataSourceNode, scope);
        break;
    }
    case yqlplusParser.RULE_data_source: {
        alias = assignAlias("source", aliasContext, scope);
        result = convertQuery(dataSourceNode.getChild(1), scope);
        break;
    }
    default:
        throw new IllegalArgumentException(
                "Unexpected argument type to convertSource: " + dataSourceNode.getText());
    }
    result.putAnnotation("alias", alias);
    return result;
}

From source file:illarion.easynpc.parser.Utils.java

License:Open Source License

@Nonnull
private static <T extends Enum<T>> T getEnumValue(@Nullable ParserRuleContext node, @Nonnull Class<T> enumClass,
        @Nonnull T defaultValue) {/*from  w  ww .jav a 2 s . c om*/
    if (node == null) {
        LOGGER.warn("Expected node for enumerator {} not found.", enumClass.getSimpleName());
        return defaultValue;
    }
    String string = removeQuotes(node.getText());
    try {
        return Enum.valueOf(enumClass, string);
    } catch (IllegalArgumentException e) {
        node.addErrorNode(node.getStart());
        LOGGER.warn("Failed to resolve {} to enumerator {}", string, enumClass.getSimpleName());
        return defaultValue;
    }
}