org.codehaus.groovy.ast.stmt.ReturnStatement Java Examples
The following examples show how to use
org.codehaus.groovy.ast.stmt.ReturnStatement.
You can vote up the ones you like or vote down the ones you don't like,
and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: AnnotationVisitor.java From groovy with Apache License 2.0 | 6 votes |
public void checkCircularReference(ClassNode searchClass, ClassNode attrType, Expression startExp) { if (!isValidAnnotationClass(attrType)) return; if (!(startExp instanceof AnnotationConstantExpression)) { addError("Found '" + startExp.getText() + "' when expecting an Annotation Constant", startExp); return; } AnnotationConstantExpression ace = (AnnotationConstantExpression) startExp; AnnotationNode annotationNode = (AnnotationNode) ace.getValue(); if (annotationNode.getClassNode().equals(searchClass)) { addError("Circular reference discovered in " + searchClass.getName(), startExp); return; } ClassNode cn = annotationNode.getClassNode(); for (MethodNode method : cn.getMethods()) { if (method.getReturnType().equals(searchClass)) { addError("Circular reference discovered in " + cn.getName(), startExp); } ReturnStatement code = (ReturnStatement) method.getCode(); if (code == null) continue; checkCircularReference(searchClass, method.getReturnType(), code.getExpression()); } }
Example #2
Source File: UnknownElementsIndexerTest.java From bonita-studio with GNU General Public License v2.0 | 6 votes |
@Test public void should_add_to_overriden_variables_a_variable_declared_and_already_in_the_process_scope() throws Exception { final BonitaScriptGroovyCompilationUnit groovyCompilationUnit = mock(BonitaScriptGroovyCompilationUnit.class, RETURNS_DEEP_STUBS); Map<String, ScriptVariable> context = new HashMap<String, ScriptVariable>(); context.put("declaredVar", null); when(groovyCompilationUnit.getContext()).thenReturn(context); final List<Statement> statements = new ArrayList<Statement>(); statements.add(new ExpressionStatement( new DeclarationExpression(new VariableExpression("declaredVar"), Token.NULL, new VariableExpression("something")))); statements.add(new ReturnStatement(new VariableExpression("declaredVar"))); final VariableScope variableScope = new VariableScope(); variableScope.putDeclaredVariable(new VariableExpression("declaredVar")); final BlockStatement blockStatement = new BlockStatement(statements, variableScope); when(groovyCompilationUnit.getModuleNode().getStatementBlock()).thenReturn(blockStatement); final UnknownElementsIndexer unknownElementsIndexer = new UnknownElementsIndexer(groovyCompilationUnit); unknownElementsIndexer.run(new NullProgressMonitor()); assertThat(unknownElementsIndexer.getOverridenVariables()).containsExactly(entry("declaredVar", new Position(0))); }
Example #3
Source File: UnknownElementsIndexerTest.java From bonita-studio with GNU General Public License v2.0 | 6 votes |
@Test public void should_not_add_to_unknonwn_variables_a_variable_declared_but_not_in_the_process_scope() throws Exception { final BonitaScriptGroovyCompilationUnit groovyCompilationUnit = mock(BonitaScriptGroovyCompilationUnit.class, RETURNS_DEEP_STUBS); final List<Statement> statements = new ArrayList<Statement>(); statements.add(new ExpressionStatement( new DeclarationExpression(new VariableExpression("declaredVar"), Token.NULL, new VariableExpression("something")))); statements.add(new ReturnStatement(new VariableExpression("declaredVar"))); final VariableScope variableScope = new VariableScope(); variableScope.putDeclaredVariable(new VariableExpression("declaredVar")); final BlockStatement blockStatement = new BlockStatement(statements, variableScope); when(groovyCompilationUnit.getModuleNode().getStatementBlock()).thenReturn(blockStatement); final UnknownElementsIndexer unknownElementsIndexer = new UnknownElementsIndexer(groovyCompilationUnit); unknownElementsIndexer.run(new NullProgressMonitor()); assertThat(unknownElementsIndexer.getUnknownVaraibles()).isEmpty(); }
Example #4
Source File: UnknownElementsIndexerTest.java From bonita-studio with GNU General Public License v2.0 | 6 votes |
@Test public void should_add_to_unknonwn_variables_a_variable_not_declared_and_not_in_the_process_scope() throws Exception { final BonitaScriptGroovyCompilationUnit groovyCompilationUnit = mock(BonitaScriptGroovyCompilationUnit.class, RETURNS_DEEP_STUBS); final List<Statement> statements = new ArrayList<Statement>(); statements.add(new ReturnStatement(new VariableExpression("unkownVariable"))); final VariableScope variableScope = new VariableScope(); variableScope.putDeclaredVariable(new VariableExpression("unkownVariable")); final BlockStatement blockStatement = new BlockStatement(statements, variableScope); when(groovyCompilationUnit.getModuleNode().getStatementBlock()).thenReturn(blockStatement); final UnknownElementsIndexer unknownElementsIndexer = new UnknownElementsIndexer( groovyCompilationUnit); unknownElementsIndexer.run(new NullProgressMonitor()); assertThat(unknownElementsIndexer.getUnknownVaraibles()).containsExactly("unkownVariable"); }
Example #5
Source File: DefaultScriptCompilationHandler.java From Pushjet-Android with BSD 2-Clause "Simplified" License | 6 votes |
private boolean isEmpty(SourceUnit source) { if (!source.getAST().getMethods().isEmpty()) { return false; } List<Statement> statements = source.getAST().getStatementBlock().getStatements(); if (statements.size() > 1) { return false; } if (statements.isEmpty()) { return true; } Statement statement = statements.get(0); if (statement instanceof ReturnStatement) { ReturnStatement returnStatement = (ReturnStatement) statement; if (returnStatement.getExpression() instanceof ConstantExpression) { ConstantExpression constantExpression = (ConstantExpression) returnStatement.getExpression(); if (constantExpression.getValue() == null) { return true; } } } return false; }
Example #6
Source File: DefaultScriptCompilationHandler.java From Pushjet-Android with BSD 2-Clause "Simplified" License | 6 votes |
private boolean isEmpty(SourceUnit source) { if (!source.getAST().getMethods().isEmpty()) { return false; } List<Statement> statements = source.getAST().getStatementBlock().getStatements(); if (statements.size() > 1) { return false; } if (statements.isEmpty()) { return true; } Statement statement = statements.get(0); if (statement instanceof ReturnStatement) { ReturnStatement returnStatement = (ReturnStatement) statement; if (returnStatement.getExpression() instanceof ConstantExpression) { ConstantExpression constantExpression = (ConstantExpression) returnStatement.getExpression(); if (constantExpression.getValue() == null) { return true; } } } return false; }
Example #7
Source File: FinalVariableAnalyzer.java From groovy with Apache License 2.0 | 6 votes |
/** * @return true if the block falls through, i.e. no break/return */ private boolean fallsThrough(Statement statement) { if (statement instanceof EmptyStatement) { return true; } if (statement instanceof ReturnStatement) { // from ReturnAdder return false; } BlockStatement block = (BlockStatement) statement; // currently only possibility if (block.getStatements().size() == 0) { return true; } Statement last = DefaultGroovyMethods.last(block.getStatements()); boolean completesAbruptly = last instanceof ReturnStatement || last instanceof BreakStatement || last instanceof ThrowStatement || last instanceof ContinueStatement; return !completesAbruptly; }
Example #8
Source File: FinalVariableAnalyzer.java From groovy with Apache License 2.0 | 6 votes |
/** * @return true if the block's last statement is a return or throw */ private boolean returningBlock(Statement block) { if (block instanceof ReturnStatement || block instanceof ThrowStatement) { return true; } if (!(block instanceof BlockStatement)) { return false; } BlockStatement bs = (BlockStatement) block; if (bs.getStatements().size() == 0) { return false; } Statement last = DefaultGroovyMethods.last(bs.getStatements()); if (last instanceof ReturnStatement || last instanceof ThrowStatement) { return true; } return false; }
Example #9
Source File: InnerClassVisitorHelper.java From groovy with Apache License 2.0 | 6 votes |
protected static void setMethodDispatcherCode(BlockStatement block, Expression thiz, Parameter[] parameters) { List<ConstantExpression> gStringStrings = new ArrayList<ConstantExpression>(); gStringStrings.add(new ConstantExpression("")); gStringStrings.add(new ConstantExpression("")); List<Expression> gStringValues = new ArrayList<Expression>(); gStringValues.add(new VariableExpression(parameters[0])); block.addStatement( new ReturnStatement( new MethodCallExpression( thiz, new GStringExpression("$name", gStringStrings, gStringValues), new ArgumentListExpression( new SpreadExpression(new VariableExpression(parameters[1])) ) ) ) ); }
Example #10
Source File: StaticTypeCheckingSupport.java From groovy with Apache License 2.0 | 6 votes |
/** * A helper method that can be used to evaluate expressions as found in annotation * parameters. For example, it will evaluate a constant, be it referenced directly as * an integer or as a reference to a field. * <p> * If this method throws an exception, then the expression cannot be evaluated on its own. * * @param expr the expression to be evaluated * @param config the compiler configuration * @return the result of the expression */ public static Object evaluateExpression(final Expression expr, final CompilerConfiguration config) { String className = "Expression$" + UUID.randomUUID().toString().replace('-', '$'); ClassNode node = new ClassNode(className, Opcodes.ACC_PUBLIC, OBJECT_TYPE); ReturnStatement code = new ReturnStatement(expr); addGeneratedMethod(node, "eval", Opcodes.ACC_PUBLIC + Opcodes.ACC_STATIC, OBJECT_TYPE, Parameter.EMPTY_ARRAY, ClassNode.EMPTY_ARRAY, code); CompilerConfiguration copyConf = new CompilerConfiguration(config); CompilationUnit cu = new CompilationUnit(copyConf); cu.addClassNode(node); cu.compile(Phases.CLASS_GENERATION); List<GroovyClass> classes = cu.getClasses(); Class<?> aClass = cu.getClassLoader().defineClass(className, classes.get(0).getBytes()); try { return aClass.getMethod("eval").invoke(null); } catch (IllegalAccessException | NoSuchMethodException | InvocationTargetException e) { throw new GroovyBugError(e); } }
Example #11
Source File: DefaultScriptCompilationHandler.java From pushfish-android with BSD 2-Clause "Simplified" License | 6 votes |
private boolean isEmpty(SourceUnit source) { if (!source.getAST().getMethods().isEmpty()) { return false; } List<Statement> statements = source.getAST().getStatementBlock().getStatements(); if (statements.size() > 1) { return false; } if (statements.isEmpty()) { return true; } Statement statement = statements.get(0); if (statement instanceof ReturnStatement) { ReturnStatement returnStatement = (ReturnStatement) statement; if (returnStatement.getExpression() instanceof ConstantExpression) { ConstantExpression constantExpression = (ConstantExpression) returnStatement.getExpression(); if (constantExpression.getValue() == null) { return true; } } } return false; }
Example #12
Source File: DefaultScriptCompilationHandler.java From pushfish-android with BSD 2-Clause "Simplified" License | 6 votes |
private boolean isEmpty(SourceUnit source) { if (!source.getAST().getMethods().isEmpty()) { return false; } List<Statement> statements = source.getAST().getStatementBlock().getStatements(); if (statements.size() > 1) { return false; } if (statements.isEmpty()) { return true; } Statement statement = statements.get(0); if (statement instanceof ReturnStatement) { ReturnStatement returnStatement = (ReturnStatement) statement; if (returnStatement.getExpression() instanceof ConstantExpression) { ConstantExpression constantExpression = (ConstantExpression) returnStatement.getExpression(); if (constantExpression.getValue() == null) { return true; } } } return false; }
Example #13
Source File: NotYetImplementedASTTransformation.java From groovy with Apache License 2.0 | 6 votes |
public void visit(ASTNode[] nodes, SourceUnit source) { init(nodes, source); AnnotationNode anno = (AnnotationNode) nodes[0]; MethodNode methodNode = (MethodNode) nodes[1]; ClassNode exception = getMemberClassValue(anno, "exception"); if (exception == null) { exception = DEFAULT_THROW_TYPE; } ConstructorNode cons = exception.getDeclaredConstructor(new Parameter[]{new Parameter(ClassHelper.STRING_TYPE, "dummy")}); if (cons == null) { addError("Error during @NotYetImplemented processing: supplied exception " + exception.getNameWithoutPackage() + " doesn't have expected String constructor", methodNode); } if (methodNode.getCode() instanceof BlockStatement && !methodNode.getCode().isEmpty()) { // wrap code in try/catch with return for failure path followed by throws for success path TryCatchStatement tryCatchStatement = tryCatchS(methodNode.getCode()); tryCatchStatement.addCatch(catchS(param(CATCH_TYPE, "ignore"), ReturnStatement.RETURN_NULL_OR_VOID)); ThrowStatement throwStatement = throwS(ctorX(exception, args(constX("Method is marked with @NotYetImplemented but passes unexpectedly")))); methodNode.setCode(block(tryCatchStatement, throwStatement)); } }
Example #14
Source File: AnnotationConstantsVisitor.java From groovy with Apache License 2.0 | 5 votes |
private static void visitStatement(Statement statement, ClassNode returnType) { if (statement instanceof ReturnStatement) { // normal path ReturnStatement rs = (ReturnStatement) statement; rs.setExpression(transformConstantExpression(rs.getExpression(), returnType)); } else if (statement instanceof ExpressionStatement) { // path for JavaStubGenerator ExpressionStatement es = (ExpressionStatement) statement; es.setExpression(transformConstantExpression(es.getExpression(), returnType)); } }
Example #15
Source File: ClosureWriter.java From groovy with Apache License 2.0 | 5 votes |
protected void addFieldsAndGettersForLocalVariables(final InnerClassNode answer, final Parameter[] localVariableParams) { for (Parameter param : localVariableParams) { String paramName = param.getName(); ClassNode type = param.getType(); VariableExpression initialValue = new VariableExpression(paramName); initialValue.setAccessedVariable(param); initialValue.setUseReferenceDirectly(true); ClassNode realType = type; type = ClassHelper.makeReference(); param.setType(ClassHelper.makeReference()); FieldNode paramField = answer.addField(paramName, ACC_PRIVATE | ACC_SYNTHETIC, type, initialValue); paramField.setOriginType(ClassHelper.getWrapper(param.getOriginType())); paramField.setHolder(true); String methodName = Verifier.capitalize(paramName); // let's add a getter & setter Expression fieldExp = new FieldExpression(paramField); markAsGenerated(answer, answer.addMethod( "get" + methodName, ACC_PUBLIC, realType.getPlainNodeReference(), Parameter.EMPTY_ARRAY, ClassNode.EMPTY_ARRAY, new ReturnStatement(fieldExp)), true); } }
Example #16
Source File: Verifier.java From groovy with Apache License 2.0 | 5 votes |
private static void checkReturnInObjectInitializer(List<Statement> init) { GroovyCodeVisitor visitor = new CodeVisitorSupport() { @Override public void visitClosureExpression(ClosureExpression expression) { // return is OK in closures in object initializers } @Override public void visitReturnStatement(ReturnStatement statement) { throw new RuntimeParserException("'return' is not allowed in object initializer", statement); } }; for (Statement stmt : init) { stmt.visit(visitor); } }
Example #17
Source File: ReturnAdder.java From groovy with Apache License 2.0 | 5 votes |
private static boolean returns(final Statement statement) { return statement instanceof ReturnStatement || statement instanceof BlockStatement || statement instanceof IfStatement || statement instanceof ExpressionStatement || statement instanceof EmptyStatement || statement instanceof TryCatchStatement || statement instanceof ThrowStatement || statement instanceof SynchronizedStatement || statement instanceof BytecodeSequence; }
Example #18
Source File: OptimizingStatementWriter.java From groovy with Apache License 2.0 | 5 votes |
@Override public void writeReturn(final ReturnStatement statement) { if (controller.isFastPath()) { super.writeReturn(statement); } else { StatementMeta meta = statement.getNodeMetaData(StatementMeta.class); if (isNewPathFork(meta) && writeDeclarationExtraction(statement)) { if (meta.declaredVariableExpression != null) { // declaration was replaced by assignment so we need to define the variable controller.getCompileStack().defineVariable(meta.declaredVariableExpression, false); } FastPathData fastPathData = writeGuards(meta, statement); boolean oldFastPathBlock = fastPathBlocked; fastPathBlocked = true; super.writeReturn(statement); fastPathBlocked = oldFastPathBlock; if (fastPathData == null) return; writeFastPathPrelude(fastPathData); super.writeReturn(statement); writeFastPathEpilogue(fastPathData); } else { super.writeReturn(statement); } } }
Example #19
Source File: OptimizingStatementWriter.java From groovy with Apache License 2.0 | 5 votes |
@Override public void visitReturnStatement(final ReturnStatement statement) { opt.push(); super.visitReturnStatement(statement); if (opt.shouldOptimize()) { addMeta(statement,opt); } opt.pop(opt.shouldOptimize()); }
Example #20
Source File: StaticTypesClosureWriter.java From groovy with Apache License 2.0 | 5 votes |
private static void createDirectCallMethod(final ClassNode closureClass, final MethodNode doCallMethod) { // in case there is no "call" method on the closure, we can create a "fast invocation" paths // to avoid going through ClosureMetaClass by call(Object...) method // we can't have a specialized version of call(Object...) because the dispatch logic in ClosureMetaClass // is too complex! // call(Object) Parameter args = new Parameter(ClassHelper.OBJECT_TYPE, "args"); MethodCallExpression doCall1arg = new MethodCallExpression( new VariableExpression("this", closureClass), "doCall", new ArgumentListExpression(new VariableExpression(args)) ); doCall1arg.setImplicitThis(true); doCall1arg.setMethodTarget(doCallMethod); closureClass.addMethod( new MethodNode("call", Opcodes.ACC_PUBLIC, ClassHelper.OBJECT_TYPE, new Parameter[]{args}, ClassNode.EMPTY_ARRAY, new ReturnStatement(doCall1arg))); // call() MethodCallExpression doCallNoArgs = new MethodCallExpression(new VariableExpression("this", closureClass), "doCall", new ArgumentListExpression(new ConstantExpression(null))); doCallNoArgs.setImplicitThis(true); doCallNoArgs.setMethodTarget(doCallMethod); closureClass.addMethod( new MethodNode("call", Opcodes.ACC_PUBLIC, ClassHelper.OBJECT_TYPE, Parameter.EMPTY_ARRAY, ClassNode.EMPTY_ARRAY, new ReturnStatement(doCallNoArgs))); }
Example #21
Source File: InnerClassVisitorHelper.java From groovy with Apache License 2.0 | 5 votes |
protected static void setPropertyGetterDispatcher(BlockStatement block, Expression thiz, Parameter[] parameters) { List<ConstantExpression> gStringStrings = new ArrayList<ConstantExpression>(); gStringStrings.add(new ConstantExpression("")); gStringStrings.add(new ConstantExpression("")); List<Expression> gStringValues = new ArrayList<Expression>(); gStringValues.add(new VariableExpression(parameters[0])); block.addStatement( new ReturnStatement( new PropertyExpression( thiz, new GStringExpression("$name", gStringStrings, gStringValues) ) ) ); }
Example #22
Source File: ASTNodeVisitor.java From groovy-language-server with Apache License 2.0 | 5 votes |
public void visitReturnStatement(ReturnStatement node) { pushASTNode(node); try { super.visitReturnStatement(node); } finally { popASTNode(); } }
Example #23
Source File: StatementWriter.java From groovy with Apache License 2.0 | 5 votes |
public void writeReturn(final ReturnStatement statement) { controller.getAcg().onLineNumber(statement, "visitReturnStatement"); writeStatementLabel(statement); MethodVisitor mv = controller.getMethodVisitor(); OperandStack operandStack = controller.getOperandStack(); ClassNode returnType = controller.getReturnType(); if (returnType == ClassHelper.VOID_TYPE) { if (!(statement.isReturningNullOrVoid())) { //TODO: move to Verifier controller.getAcg().throwException("Cannot use return statement with an expression on a method that returns void"); } controller.getCompileStack().applyBlockRecorder(); mv.visitInsn(RETURN); return; } Expression expression = statement.getExpression(); expression.visit(controller.getAcg()); operandStack.doGroovyCast(returnType); if (controller.getCompileStack().hasBlockRecorder()) { ClassNode type = operandStack.getTopOperand(); int returnValueIdx = controller.getCompileStack().defineTemporaryVariable("returnValue", returnType, true); controller.getCompileStack().applyBlockRecorder(); operandStack.load(type, returnValueIdx); controller.getCompileStack().removeVar(returnValueIdx); } BytecodeHelper.doReturn(mv, returnType); operandStack.remove(1); }
Example #24
Source File: MethodTest.java From groovy with Apache License 2.0 | 5 votes |
public void testMethods() throws Exception { ClassNode classNode = new ClassNode("Foo", ACC_PUBLIC, ClassHelper.OBJECT_TYPE); classNode.addConstructor(new ConstructorNode(ACC_PUBLIC, null)); Statement statementA = new ReturnStatement(new ConstantExpression("calledA")); Statement statementB = new ReturnStatement(new ConstantExpression("calledB")); Statement emptyStatement = new BlockStatement(); classNode.addMethod(new MethodNode("a", ACC_PUBLIC, ClassHelper.OBJECT_TYPE, Parameter.EMPTY_ARRAY, ClassNode.EMPTY_ARRAY, statementA)); classNode.addMethod(new MethodNode("b", ACC_PUBLIC, null, Parameter.EMPTY_ARRAY, ClassNode.EMPTY_ARRAY, statementB)); classNode.addMethod(new MethodNode("noReturnMethodA", ACC_PUBLIC, null, Parameter.EMPTY_ARRAY, ClassNode.EMPTY_ARRAY, emptyStatement)); classNode.addMethod(new MethodNode("noReturnMethodB", ACC_PUBLIC, ClassHelper.OBJECT_TYPE, Parameter.EMPTY_ARRAY, ClassNode.EMPTY_ARRAY, emptyStatement)); classNode.addMethod(new MethodNode("c", ACC_PUBLIC, ClassHelper.VOID_TYPE, Parameter.EMPTY_ARRAY, ClassNode.EMPTY_ARRAY, emptyStatement)); Class fooClass = loadClass(classNode); assertTrue("Loaded a new class", fooClass != null); Object bean = fooClass.getDeclaredConstructor().newInstance(); assertTrue("Created instance of class: " + bean, bean != null); assertCallMethod(bean, "a", "calledA"); assertCallMethod(bean, "b", "calledB"); assertCallMethod(bean, "noReturnMethodA", null); assertCallMethod(bean, "noReturnMethodB", null); assertCallMethod(bean, "c", null); }
Example #25
Source File: DefaultTypeCheckingExtension.java From groovy with Apache License 2.0 | 5 votes |
@Override public boolean handleIncompatibleReturnType(ReturnStatement returnStatement, ClassNode inferredReturnType) { for (TypeCheckingExtension handler : handlers) { if (handler.handleIncompatibleReturnType(returnStatement, inferredReturnType)) return true; } return false; }
Example #26
Source File: GroovyTypeCheckingExtensionSupport.java From groovy with Apache License 2.0 | 5 votes |
@Override public boolean handleIncompatibleReturnType(final ReturnStatement returnStatement, ClassNode inferredReturnType) { setHandled(false); List<Closure> list = eventHandlers.get("handleIncompatibleReturnType"); if (list != null) { for (Closure closure : list) { safeCall(closure, returnStatement, inferredReturnType); } } return handled; }
Example #27
Source File: Java8.java From groovy with Apache License 2.0 | 4 votes |
private static void setMethodDefaultValue(MethodNode mn, Method m) { ConstantExpression cExp = new ConstantExpression(m.getDefaultValue()); mn.setCode(new ReturnStatement(cExp)); mn.setAnnotationDefault(true); }
Example #28
Source File: ASTFinder.java From groovy with Apache License 2.0 | 4 votes |
@Override public void visitReturnStatement(final ReturnStatement statement) { super.visitReturnStatement(statement); tryFind(ReturnStatement.class, statement); }
Example #29
Source File: PathFinderVisitor.java From netbeans with Apache License 2.0 | 4 votes |
@Override public void visitReturnStatement(ReturnStatement node) { if (isInside(node, line, column)) { super.visitReturnStatement(node); } }
Example #30
Source File: SecureASTCustomizer.java From groovy with Apache License 2.0 | 4 votes |
@Override public void visitReturnStatement(final ReturnStatement statement) { assertStatementAuthorized(statement); statement.getExpression().visit(this); }