List of usage examples for org.antlr.v4.runtime ParserRuleContext getChild
@Override public ParseTree getChild(int i)
From source file:com.liferay.dynamic.data.mapping.expression.internal.DDMExpressionEvaluatorVisitor.java
License:Open Source License
protected <T> T visitChild(ParserRuleContext parserRuleContext, int childIndex) { ParseTree parseTree = parserRuleContext.getChild(childIndex); return (T) parseTree.accept(this); }
From source file:com.satisfyingstructures.J2S.J2SConverter.java
License:Open Source License
private void mapInitialModifiersInContext(ParserRuleContext ctx) { ParseTree pt;/*from w w w . j a va 2s.c o m*/ int i = 0; while (null != (pt = ctx.getChild(i++)) && ParserRuleContext.class.isInstance(pt)) { ParserRuleContext context = (ParserRuleContext) pt; int contextRuleIndex = context.getRuleIndex(); switch (contextRuleIndex) { case Java8Parser.RULE_interfaceModifier: case Java8Parser.RULE_interfaceMethodModifier: case Java8Parser.RULE_classModifier: case Java8Parser.RULE_constructorModifier: case Java8Parser.RULE_methodModifier: case Java8Parser.RULE_annotationTypeElementModifier: case Java8Parser.RULE_variableModifier: case Java8Parser.RULE_constantModifier: case Java8Parser.RULE_fieldModifier: break; default: return; } TerminalNode tn = context.getChild(TerminalNode.class, 0); if (null == tn) continue; // annotation - dealt with separately Token token = tn.getSymbol(); // Handle special token cases switch (token.getType()) { case Java8Parser.STATIC: if (contextRuleIndex == Java8Parser.RULE_classModifier) { rewriter.deleteAndAdjustWhitespace(tn); // static not allowed for classes in Swift continue; } break; case Java8Parser.PRIVATE: case Java8Parser.PROTECTED: case Java8Parser.PUBLIC: if (contextRuleIndex == Java8Parser.RULE_interfaceMethodModifier) { rewriter.deleteAndAdjustWhitespace(tn); // access control not allowed for protocols in Swift continue; } break; } mapModifierToken(token); } }
From source file:com.yahoo.yqlplus.language.parser.ProgramParser.java
private String assignAlias(String alias, ParserRuleContext node, Scope scope) { if (alias == null) { alias = "source"; }/*from w ww . j av a2 s. c o m*/ if (node != null && node instanceof yqlplusParser.Alias_defContext) { //alias_def : (AS? ID); ParseTree idChild = node; if (node.getChildCount() > 1) { idChild = node.getChild(1); } alias = idChild.getText(); if (scope.isCursor(alias)) { throw new ProgramCompileException(toLocation(scope, idChild), "Source alias '%s' is already used", alias); } scope.defineDataSource(toLocation(scope, idChild), alias, true); return alias; } else { String candidate = alias; int c = 0; while (scope.isCursor(candidate)) { candidate = alias + (++c); } scope.defineDataSource(null, candidate); return alias; } }
From source file:com.yahoo.yqlplus.language.parser.ProgramParser.java
private OperatorNode<SequenceOperator> convertSource(ParserRuleContext sourceSpecNode, Scope scope) { // DataSources String alias;/* w w w .j a va2 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:com.yahoo.yqlplus.language.parser.ProgramParser.java
private OperatorNode<StatementOperator> convertProgram(ParserRuleContext program, yqlplusParser parser, String programName) {//from w w w.j av a2s .c o m 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.ja v a 2s. c o 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:jasy.lang.ASMCompiler.java
private static jasy.lang.ast.CodeAST getStatement(ParserRuleContext ctx, MetaProcessing mp) { jasy.lang.ast.CodeAST r = ctx.accept(new JasyBaseVisitor<jasy.lang.ast.CodeAST>() { @Override// w w w . j av a 2 s . co m public CodeAST visitStatement(JasyParser.StatementContext ctx) { if (ctx.nonDelimitedStatement() != null) return ctx.nonDelimitedStatement().accept(this); if (ctx.delimitedStatement() != null) return ctx.delimitedStatement().accept(this); if (ctx.metaBlock() != null) return ctx.metaBlock().accept(this); return null; } @Override public CodeAST visitDelimitedStatement(JasyParser.DelimitedStatementContext ctx) { if (ctx.expression() != null) { ExpressionAST expression = getExpression(ctx.expression(), mp); return new RootExpressionAST(new Region(ctx), expression); } return ctx.getChild(0).accept(this); } @Override public CodeAST visitReturnStatement(JasyParser.ReturnStatementContext ctx) { ExpressionAST expression = getExpression(ctx.expression(), mp); return new ReturnAST(new Region(ctx), expression); } @Override public CodeAST visitVariableDeclaration(JasyParser.VariableDeclarationContext ctx) { String type = ctx.typeQualifier().getText(); String name = ctx.identifier().getText(); ExpressionAST value; if (ctx.expression() != null) value = getExpression(ctx.expression(), mp); else value = null; return new VariableDeclarationAST(new Region(ctx), name, new NameTypeAST(new Region(ctx.typeQualifier()), type), value); } @Override public CodeAST visitMetaBlock(JasyParser.MetaBlockContext ctx) { List<CodeAST> statements = getStatements(ctx.statements(), mp); return new MetaCodeAST(null, new BlockAST(null, statements)); } // @Override // public CodeAST visitInjectStatement(JasyParser.InjectStatementContext ctx) { // ExpressionAST expression = getExpression(ctx.expression(), mp); // // return new InjectAST(new Region(ctx), expression); // } @Override public CodeAST visitIfElseStatement(JasyParser.IfElseStatementContext ctx) { ExpressionAST condition = getExpression(ctx.condition, mp); CodeAST ifTrueBody = getBody(ctx.ifTrueBlock); CodeAST ifFalseBody = ctx.ifFalseBlock != null ? getBody(ctx.ifFalseBlock) : null; return new IfElseAST(new Region(ctx), condition, ifTrueBody, ifFalseBody); } @Override public CodeAST visitWhileStatement(JasyParser.WhileStatementContext ctx) { ExpressionAST condition = getExpression(ctx.condition, mp); CodeAST body = getBody(ctx.whileTrueBlock); return new WhileAST(new Region(ctx), condition, body); } @Override public CodeAST visitForStatement(JasyParser.ForStatementContext ctx) { List<CodeAST> initialization = ctx.initialization != null ? getStatements(ctx.initialization.delimitedStatement(), mp) : null; ExpressionAST condition = ctx.condition != null ? getExpression(ctx.condition, mp) : null; List<CodeAST> update = ctx.update != null ? getStatements(ctx.update.delimitedStatement(), mp) : null; List<CodeAST> body = getStatements(ctx.whileTrueBlock.statements(), mp); ArrayList<CodeAST> statements = new ArrayList<>(); statements.addAll(initialization); ArrayList<CodeAST> whileBody = new ArrayList<>(); whileBody.addAll(body); whileBody.addAll(update); statements.add(new WhileAST(new Region(ctx), condition, new BlockAST(new Region(ctx.whileTrueBlock), whileBody))); return new BlockAST(new Region(ctx), statements); // return new WhileAST(new Region(ctx), condition, body); } private CodeAST getBody(JasyParser.SingleOrMultiStatementContext ctx) { return ctx.statement() != null ? getStatement(ctx.statement(), mp) : new BlockAST(new Region(ctx), getStatements(ctx.statements(), mp)); } }); return r; }
From source file:jetbrick.template.parser.AstCodeVisitor.java
License:Open Source License
private Position pos(ParserRuleContext ctx, int childIndex) { ParseTree node = ctx.getChild(childIndex); if (node instanceof TerminalNode) { Token token = ((TerminalNode) node).getSymbol(); return new Position(token.getLine(), token.getCharPositionInLine()); } else if (node instanceof ParserRuleContext) { Token token = ctx.getStart();// w ww . j a v a2 s. co m return new Position(token.getLine(), token.getCharPositionInLine()); } throw new UnsupportedOperationException(); }
From source file:net.certiv.json.converter.JsonPhaseBase.java
License:Open Source License
public String childText(ParserRuleContext rc, int idx) { return rc.getChild(idx).getText(); }
From source file:org.eclipse.titan.common.parsers.cfg.CfgParseTreePrinter.java
License:Open Source License
/** * RECURSIVE//from w w w.java 2 s .c o m * Builds parse tree text including hidden tokens * @param aParseTree parse tree * @param aTokens token list from the lexer (all, hidden and not hidden also) * @param aPrintHiddenBefore true to print hidden tokens before the parse tree * (NOTE: hidden tokens in the parse tree will be printed) * @param aResolveMode mode of resolving * @param aFile the parse tree of this file to print * needed only if aResolveMode != NO_RESOLVING, in case of [ORDERED_INCLUDE] */ private void print(final ParseTree aParseTree, final List<Token> aTokens, final boolean aPrintHiddenBefore, final ResolveMode aResolveMode, final Path aFile) { if (aParseTree == null) { ErrorReporter.logWarning("ConfigTreeNodeUtilities.print(): aParseTree == null"); return; } if (aParseTree instanceof ParserRuleContext) { final ParserRuleContext rule = (ParserRuleContext) aParseTree; if (mDisallowedNodes != null && mDisallowedNodes.contains(rule.start.getType())) { return; } if (aPrintHiddenBefore && rule.getChildCount() > 0 && rule.getChild(0) instanceof AddedParseTree) { // special case: if AddedParseTree is the 1st in the rule, it has no information // about the hidden tokens, as it has no position in the token list, but the rule may have printHiddenTokensBefore(rule, aTokens); } } else if (aParseTree instanceof TerminalNodeImpl) { final TerminalNodeImpl tn = (TerminalNodeImpl) aParseTree; final Token token = tn.getSymbol(); if (mDisallowedNodes == null || !mDisallowedNodes.contains(token.getType())) { printToken(token, aTokens, aPrintHiddenBefore, aResolveMode, aFile); } } else if (aParseTree instanceof AddedParseTree) { final AddedParseTree t = (AddedParseTree) aParseTree; mSb.append(t.getText()); } else { ErrorReporter.INTERNAL_ERROR("ConfigTreeNodeUtilities.print(): unexpected ParseTree type"); } for (int i = 0; i < aParseTree.getChildCount(); i++) { ParseTree child = aParseTree.getChild(i); if (child == aParseTree) { ErrorReporter.INTERNAL_ERROR("ConfigTreeNodeUtilities.print(): child == aParseTree"); } else { print(child, aTokens, aPrintHiddenBefore || i > 0, aResolveMode, aFile); } } }