List of usage examples for org.antlr.v4.runtime ParserRuleContext getRuleIndex
public int getRuleIndex()
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;/*from w w w . j a v a 2 s.c o 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.satisfyingstructures.J2S.J2SConverter.java
License:Open Source License
private boolean isVariableTypeCompletelyImpliedByInitializer(Java8Parser.UnannTypeContext typeCtx, ParserRuleContext initCtx, boolean inEnhancedFor) { // Task: examine the variable initializer initCtx and see if its result type is the same as the type for the // variable receiving the result. If inEnhancedFor, the initialiser result is expected to be a collection // of some form, and we look for a match between the collection's component type and the unannType - . if (null == initCtx || null == typeCtx) return false; Java8Parser.ExpressionContext initializerExpressionCtx = null; Java8Parser.ArrayInitializerContext initializerArrayCtx = null; // We expect initCtx to be an expression or an array initializer switch (initCtx.getRuleIndex()) { case Java8Parser.RULE_expression: initializerExpressionCtx = (Java8Parser.ExpressionContext) initCtx; break;//from www . j a va 2 s . c o m case Java8Parser.RULE_arrayInitializer: initializerArrayCtx = (Java8Parser.ArrayInitializerContext) initCtx; break; default: return false; // not a parameter we expect } Java8Parser.UnannReferenceTypeContext refTypeCtx = typeCtx.unannReferenceType(); Java8Parser.UnannArrayTypeContext arrayTypeCtx = null != refTypeCtx ? refTypeCtx.unannArrayType() : null; if (!inEnhancedFor && null != initializerArrayCtx && null != arrayTypeCtx) return isArrayVariableTypeCompletelyImpliedByInitializer(arrayTypeCtx, initializerArrayCtx); if (inEnhancedFor && null != initializerArrayCtx && null == arrayTypeCtx) { Java8Parser.VariableInitializerListContext list = initializerArrayCtx.variableInitializerList(); // ...all members same type as typeCtx ? } if (!inEnhancedFor && null == initializerArrayCtx && null == arrayTypeCtx) return isNonArrayVariableTypeCompletelyImpliedByInitializer(typeCtx, initializerExpressionCtx); return false; }
From source file:com.satisfyingstructures.J2S.J2SConverter.java
License:Open Source License
private void addBracesAroundStatementIfNecessary(ParserRuleContext ctx) { // Ensure the statement(s) with if(else), for, while and do is always wrapped in braces. // At the same time, remove the parentheses around the test/control part for the statement int statementRule = ctx.getRuleIndex(); if (statementRule != Java8Parser.RULE_statement && statementRule != Java8Parser.RULE_statementNoShortIf) return; // not our expected parameter type ParserRuleContext parent = ctx.getParent(); int parentRule = parent.getRuleIndex(); switch (parentRule) { case Java8Parser.RULE_ifThenElseStatement: case Java8Parser.RULE_ifThenElseStatementNoShortIf: { // if this statement is an ifThen or an ifThenElse sitting within an ifThenElse, then // check if it follows the else, because we don't wrap the trailing 'if' part of 'else if' int statementSubRule = ctx.getChild(ParserRuleContext.class, 0).getRuleIndex(); if (statementSubRule == Java8Parser.RULE_ifThenStatement || statementSubRule == Java8Parser.RULE_ifThenElseStatement || statementSubRule == Java8Parser.RULE_ifThenElseStatementNoShortIf) { // the statement after else is the last child if (parent.getChild(parent.getChildCount() - 1) == ctx) break; }//from w ww .jav a 2 s. c om } // fallthru case Java8Parser.RULE_ifThenStatement: case Java8Parser.RULE_basicForStatement: case Java8Parser.RULE_basicForStatementNoShortIf: case Java8Parser.RULE_enhancedForStatement: case Java8Parser.RULE_enhancedForStatementNoShortIf: case Java8Parser.RULE_whileStatement: case Java8Parser.RULE_whileStatementNoShortIf: case Java8Parser.RULE_doStatement: if (ctx.start.getType() != Java8Parser.LBRACE) { rewriter.insertBefore(ctx.start, "{ "); // rewriter.insertAfter( ctx.stop, " }" ); // ...we don't insert, because it binds to the following token and we may need to change/modify it // higher up the stack. Instead, we replace the current content of the stop token. This is necessary // because the stop can be the end of more than one statement, e.g. last semicolon in... // for(;;i++) // if (i%7) // break; // ...gets wrapped twice to give // for(;;i++) // { if (i%7) // { break; } } String current = rewriter.getText(ctx.stop); rewriter.replace(ctx.stop, current + " }"); } break; default: return; } // Remove the parentheses around the test/control part for the statement removeParenthesesAroundExpression(parent); }
From source file:com.satisfyingstructures.J2S.J2SConverter.java
License:Open Source License
private boolean statementEndsWithSwitchExit(ParserRuleContext ctx) { ParserRuleContext subCtx = ctx;//from ww w .jav a2 s .c o m for (ctx = subCtx; ctx != null; ctx = subCtx) { switch (ctx.getRuleIndex()) { case Java8Parser.RULE_blockStatements: subCtx = ctx.getChild(Java8Parser.BlockStatementContext.class, ctx.getChildCount() - 1); continue; case Java8Parser.RULE_blockStatement: subCtx = ctx.getChild(ParserRuleContext.class, 0); // class or local var decl, or other statement continue; case Java8Parser.RULE_localVariableDeclarationStatement: return false; case Java8Parser.RULE_classDeclaration: return false; case Java8Parser.RULE_statement: case Java8Parser.RULE_statementNoShortIf: subCtx = ctx.getChild(ParserRuleContext.class, 0); continue; case Java8Parser.RULE_statementWithoutTrailingSubstatement: subCtx = ctx.getChild(ParserRuleContext.class, 0); continue; case Java8Parser.RULE_labeledStatement: case Java8Parser.RULE_labeledStatementNoShortIf: // Identifier ':' (statement|statementNoShortIf) // nodes 1 & 2 are terminal nodes; node 3 is first rule node subCtx = ctx.getChild(ParserRuleContext.class, 0); continue; case Java8Parser.RULE_breakStatement: case Java8Parser.RULE_continueStatement: case Java8Parser.RULE_returnStatement: case Java8Parser.RULE_throwStatement: return true; case Java8Parser.RULE_ifThenStatement: return false; case Java8Parser.RULE_ifThenElseStatement: case Java8Parser.RULE_ifThenElseStatementNoShortIf: // 'if' '(' expression ')' statementNoShortIf 'else' statement // if-statement is second rule node; else-statement is third rule node; others are terminal nodes return statementEndsWithSwitchExit(ctx.getChild(ParserRuleContext.class, 1)) && statementEndsWithSwitchExit(ctx.getChild(ParserRuleContext.class, 2)); case Java8Parser.RULE_whileStatement: case Java8Parser.RULE_whileStatementNoShortIf: case Java8Parser.RULE_forStatement: case Java8Parser.RULE_forStatementNoShortIf: case Java8Parser.RULE_doStatement: // indeterminate: whether a nested exit is hit depends on data return false; case Java8Parser.RULE_block: // '{' blockStatements? '}' // ctx.getChildCount() counts both rule and terminal nodes; nbr of rule nodes is two less here; subCtx = ctx.getChild(ParserRuleContext.class, ctx.getChildCount() - 3); continue; case Java8Parser.RULE_emptyStatement: case Java8Parser.RULE_expressionStatement: case Java8Parser.RULE_assertStatement: return false; case Java8Parser.RULE_switchStatement: // too much work return false; case Java8Parser.RULE_synchronizedStatement: // 'synchronized' '(' expression ')' block case Java8Parser.RULE_tryStatement: // 'try' block catches | 'try' block catches? finally_ | tryWithResourcesStatement subCtx = ctx.getChild(Java8Parser.BlockContext.class, 0); continue; default: return false; } } return false; }
From source file:com.satisfyingstructures.J2S.J2SConverter.java
License:Open Source License
private void convertPrimaryVariants(ParserRuleContext ctx) { // To be called with one of the primaryNoNewArray_lf~ rules. // Convert 'this' to 'self' and '.' 'class' to '.' 'Type' int ctxRuleIndex = ctx.getRuleIndex(); switch (ctxRuleIndex) { case Java8Parser.RULE_primaryNoNewArray: case Java8Parser.RULE_primaryNoNewArray_lfno_arrayAccess: case Java8Parser.RULE_primaryNoNewArray_lfno_primary: case Java8Parser.RULE_primaryNoNewArray_lfno_primary_lfno_arrayAccess_lfno_primary: break;/*from www . j a va 2s . c om*/ default: return; } TerminalNode tn; if (null != (tn = ctx.getToken(Java8Parser.THIS, 0))) rewriter.replace(tn, "self"); else if (null != (tn = ctx.getToken(Java8Parser.CLASS, 0))) rewriter.replace(tn, "Type"); }
From source file:com.satisfyingstructures.J2S.J2SConverter.java
License:Open Source License
@Override public void exitPostfixExpression(Java8Parser.PostfixExpressionContext ctx) { int increments = ctx.getChildCount() - 1; int increment = 0; for (int i = 0; i < increments; i++) { ParserRuleContext postfixCtx = ctx.getChild(ParserRuleContext.class, i + 1); switch (postfixCtx.getRuleIndex()) { case Java8Parser.RULE_postIncrementExpression_lf_postfixExpression: increment++;/*from ww w .j a v a2 s. c om*/ break; case Java8Parser.RULE_postDecrementExpression_lf_postfixExpression: increment--; break; } rewriter.delete(postfixCtx); } if (0 != increment) rewriter.replace(ctx.stop, 0 < increment ? (" += " + increment) : (" -= " + -increment)); }
From source file:com.satisfyingstructures.J2S.J2SGrammarUtils.java
License:Open Source License
public static ParserRuleContext descendToSignificantExpression(ParserRuleContext ctx) { // These expressions are chained by precedence in the grammar. We descend into the subrulecontexts until we // find a rule context that is significant, i.e. its not just a context with one child that is another // expression. // First validate parameter switch (ctx.getRuleIndex()) { case Java8Parser.RULE_constantExpression: case Java8Parser.RULE_expression: case Java8Parser.RULE_assignmentExpression: case Java8Parser.RULE_conditionalExpression: case Java8Parser.RULE_conditionalOrExpression: case Java8Parser.RULE_conditionalAndExpression: case Java8Parser.RULE_inclusiveOrExpression: case Java8Parser.RULE_exclusiveOrExpression: case Java8Parser.RULE_andExpression: case Java8Parser.RULE_equalityExpression: case Java8Parser.RULE_relationalExpression: case Java8Parser.RULE_shiftExpression: case Java8Parser.RULE_additiveExpression: case Java8Parser.RULE_multiplicativeExpression: case Java8Parser.RULE_unaryExpression: case Java8Parser.RULE_unaryExpressionNotPlusMinus: case Java8Parser.RULE_postfixExpression: case Java8Parser.RULE_primary: case Java8Parser.RULE_primaryNoNewArray_lfno_primary: break;/*from ww w . ja v a 2s . c o m*/ default: return ctx; // not an acceptable parameter type } descent: while (ctx.getChildCount() == 1) { ParserRuleContext childCtx = ctx.getChild(ParserRuleContext.class, 0); if (null == childCtx) break; switch (ctx.getRuleIndex()) { case Java8Parser.RULE_unaryExpression: if (childCtx.getRuleIndex() != Java8Parser.RULE_unaryExpressionNotPlusMinus) break descent; case Java8Parser.RULE_unaryExpressionNotPlusMinus: if (childCtx.getRuleIndex() != Java8Parser.RULE_postfixExpression) break descent; case Java8Parser.RULE_postfixExpression: if (childCtx.getRuleIndex() != Java8Parser.RULE_primary) break descent; } ctx = childCtx; } return ctx; }
From source file:com.yahoo.yqlplus.language.parser.ProgramParser.java
private OperatorNode<StatementOperator> convertProgram(ParserRuleContext program, yqlplusParser parser, String programName) {//w w w . j ava 2 s . c om Scope scope = new Scope(parser, programName); List<OperatorNode<StatementOperator>> stmts = Lists.newArrayList(); int output = 0; for (ParseTree node : program.children) { if (!(node instanceof ParserRuleContext)) { continue; } ParserRuleContext ruleContext = (ParserRuleContext) node; switch (ruleContext.getRuleIndex()) { case yqlplusParser.RULE_params: { // ^(ARGUMENT ident typeref expression?) ParamsContext paramsContext = (ParamsContext) ruleContext; Program_arglistContext program_arglistContext = paramsContext.program_arglist(); if (program_arglistContext != null) { List<Procedure_argumentContext> argList = program_arglistContext.procedure_argument(); for (Procedure_argumentContext procedureArgumentContext : argList) { if (procedureArgumentContext.array_eq_argument() != null) { Array_eq_argumentContext arrayArgument = procedureArgumentContext.array_eq_argument(); String name = arrayArgument.ident().getText(); OperatorNode<TypeOperator> type = OperatorNode.create(TypeOperator.ARRAY, decodeType(scope, arrayArgument.getChild(TypenameContext.class, 0))); OperatorNode<ExpressionOperator> defaultValue = OperatorNode .create(ExpressionOperator.NULL); if (arrayArgument.expression() != null) { defaultValue = convertExpr(arrayArgument.expression(), scope); } scope.defineVariable(toLocation(scope, arrayArgument), name); scope.arrayArgument(name); stmts.add(OperatorNode.create(StatementOperator.ARGUMENT, name, type, defaultValue)); } else { String name = procedureArgumentContext.ident().getText(); OperatorNode<TypeOperator> type = decodeType(scope, procedureArgumentContext.getChild(TypenameContext.class, 0)); OperatorNode<ExpressionOperator> defaultValue = OperatorNode .create(ExpressionOperator.NULL); if (procedureArgumentContext.expression() != null) { defaultValue = convertExpr(procedureArgumentContext.expression(), scope); } scope.defineVariable(toLocation(scope, procedureArgumentContext), name); if (type.getOperator() == TypeOperator.ARRAY) { scope.arrayArgument(name); } stmts.add(OperatorNode.create(StatementOperator.ARGUMENT, name, type, defaultValue)); } } } break; } case yqlplusParser.RULE_import_statement: { Import_statementContext importContext = (Import_statementContext) ruleContext; if (null == importContext.import_list()) { List<String> name = createBindingName(node.getChild(1)); String target; Location location = toLocation(scope, node.getChild(1)); if (node.getChildCount() == 2) { target = name.get(0); } else if (node.getChildCount() == 4) { target = node.getChild(3).getText(); } else { throw new ProgramCompileException("Unknown node count for IMPORT: " + node.toStringTree()); } scope.bindModule(location, name, target); } else { // | FROM moduleName IMPORT import_list -> ^(IMPORT_FROM // moduleName import_list+) Import_listContext importListContext = importContext.import_list(); List<String> name = createBindingName(importContext.moduleName()); Location location = toLocation(scope, importContext.moduleName()); List<ModuleIdContext> moduleIds = importListContext.moduleId(); List<String> symbols = Lists.newArrayListWithExpectedSize(moduleIds.size()); for (ModuleIdContext cnode : moduleIds) { symbols.add(cnode.ID().getText()); } for (String sym : symbols) { scope.bindModuleSymbol(location, name, sym, sym); } } break; } // DDL case yqlplusParser.RULE_ddl: ruleContext = (ParserRuleContext) ruleContext.getChild(0); case yqlplusParser.RULE_view: { // view and projection expansion now has to be done by the // execution engine // since views/projections, in order to be useful, have to // support being used from outside the same program ViewContext viewContext = (ViewContext) ruleContext; Location loc = toLocation(scope, viewContext); scope.getRoot().defineView(loc, viewContext.ID().getText()); stmts.add(OperatorNode.create(loc, StatementOperator.DEFINE_VIEW, viewContext.ID().getText(), convertQuery(viewContext.source_statement(), scope.getRoot()))); break; } case yqlplusParser.RULE_statement: { // ^(STATEMENT_QUERY source_statement paged_clause? // output_spec?) StatementContext statementContext = (StatementContext) ruleContext; switch (getParseTreeIndex(ruleContext.getChild(0))) { case yqlplusParser.RULE_selectvar_statement: { // ^(STATEMENT_SELECTVAR ident source_statement) Selectvar_statementContext selectVarContext = (Selectvar_statementContext) ruleContext .getChild(0); String variable = selectVarContext.ident().getText(); OperatorNode<SequenceOperator> query = convertQuery(selectVarContext.source_statement(), scope); Location location = toLocation(scope, selectVarContext.ident()); scope.defineVariable(location, variable); stmts.add(OperatorNode.create(location, StatementOperator.EXECUTE, query, variable)); break; } case yqlplusParser.RULE_next_statement: { // NEXT^ literalString OUTPUT! AS! ident Next_statementContext nextStateContext = (Next_statementContext) ruleContext.getChild(0); String continuationValue = StringUnescaper.unquote(nextStateContext.literalString().getText()); String variable = nextStateContext.ident().getText(); Location location = toLocation(scope, node); OperatorNode<SequenceOperator> next = OperatorNode.create(location, SequenceOperator.NEXT, continuationValue); stmts.add(OperatorNode.create(location, StatementOperator.EXECUTE, next, variable)); stmts.add(OperatorNode.create(location, StatementOperator.OUTPUT, variable)); scope.defineVariable(location, variable); break; } case yqlplusParser.RULE_output_statement: Source_statementContext source_statement = statementContext.output_statement() .source_statement(); OperatorNode<SequenceOperator> query; if (source_statement.getChildCount() == 1) { query = convertQuery(source_statement.query_statement().getChild(0), scope); } else { query = convertQuery(source_statement, scope); } String variable = "result" + (++output); boolean isCountVariable = false; OperatorNode<ExpressionOperator> pageSize = null; ParseTree outputStatement = node.getChild(0); Location location = toLocation(scope, outputStatement); for (int i = 1; i < outputStatement.getChildCount(); ++i) { ParseTree child = outputStatement.getChild(i); switch (getParseTreeIndex(child)) { case yqlplusParser.RULE_paged_clause: Paged_clauseContext pagedContext = (Paged_clauseContext) child; pageSize = convertExpr(pagedContext.fixed_or_parameter(), scope); break; case yqlplusParser.RULE_output_spec: Output_specContext outputSpecContext = (Output_specContext) child; variable = outputSpecContext.ident().getText(); if (outputSpecContext.COUNT() != null) { isCountVariable = true; } break; default: throw new ProgramCompileException( "Unknown statement attribute: " + child.toStringTree()); } } scope.defineVariable(location, variable); if (pageSize != null) { query = OperatorNode.create(SequenceOperator.PAGE, query, pageSize); } stmts.add(OperatorNode.create(location, StatementOperator.EXECUTE, query, variable)); stmts.add(OperatorNode.create(location, isCountVariable ? StatementOperator.COUNT : StatementOperator.OUTPUT, variable)); } break; } default: throw new ProgramCompileException("Unknown program element: " + node.getText()); } } // traverse the tree, find all of the namespaced calls not covered by // imports so we can // define "implicit" import statements for them (to make engine // implementation easier) return OperatorNode.create(new Location(programName, 0, 0), StatementOperator.PROGRAM, stmts); }
From source file:com.yahoo.yqlplus.language.parser.ProgramParser.java
private OperatorNode<ExpressionOperator> readValues(ParserRuleContext node, Scope scope) { List<String> fieldNames; List<OperatorNode<ExpressionOperator>> fieldValues; if (node.getRuleIndex() == yqlplusParser.RULE_field_def) { Field_defContext fieldDefContext = (Field_defContext) node; //TODO double check fieldNames = Lists.newArrayListWithExpectedSize(node.getChildCount()); fieldValues = Lists.newArrayListWithExpectedSize(node.getChildCount()); for (int i = 0; i < node.getChildCount(); i++) { fieldNames//from w ww. j a v a 2 s. co m .add((String) convertExpr(node.getChild(i).getChild(0).getChild(0), scope).getArgument(1)); fieldValues.add(convertExpr(node.getChild(i).getChild(0).getChild(1), scope)); } } else { assert node.getChildCount() % 2 == 0; int numPairs = node.getChildCount() / 2; fieldNames = Lists.newArrayListWithExpectedSize(numPairs); fieldValues = Lists.newArrayListWithExpectedSize(numPairs); for (int i = 0; i < numPairs; i++) { fieldNames.add((String) convertExpr(node.getChild(i).getChild(0), scope).getArgument(1)); fieldValues.add(convertExpr(node.getChild(numPairs + i), scope)); } } return OperatorNode.create(ExpressionOperator.MAP, fieldNames, fieldValues); }
From source file:de.uni.bremen.monty.moco.util.ParseTreePrinter.java
License:Open Source License
@Override public void enterEveryRule(ParserRuleContext ctx) { builder.append("\n"); intended = false;/*from ww w. j ava 2 s . c o m*/ if (builder.length() > 0) { builder.append(' '); } if (!ctx.equals(lastOne)) { intend++; } int ruleIndex = ctx.getRuleIndex(); String ruleName; if (ruleIndex >= 0 && ruleIndex < ruleNames.size()) { ruleName = ruleNames.get(ruleIndex); } else { ruleName = Integer.toString(ruleIndex); } append(ruleName); lastOne = ctx; }