org.codehaus.groovy.ast.expr.ClosureExpression Java Examples
The following examples show how to use
org.codehaus.groovy.ast.expr.ClosureExpression.
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: ClosureWriter.java From groovy with Apache License 2.0 | 6 votes |
protected BlockStatement createBlockStatementForConstructor(final ClosureExpression expression, final ClassNode outerClass, final ClassNode thisClassNode) { BlockStatement block = new BlockStatement(); // this block does not get a source position, because we don't // want this synthetic constructor to show up in corbertura reports VariableExpression outer = new VariableExpression(OUTER_INSTANCE, outerClass); outer.setSourcePosition(expression); block.getVariableScope().putReferencedLocalVariable(outer); VariableExpression thisObject = new VariableExpression(THIS_OBJECT, thisClassNode); thisObject.setSourcePosition(expression); block.getVariableScope().putReferencedLocalVariable(thisObject); TupleExpression conArgs = new TupleExpression(outer, thisObject); block.addStatement( new ExpressionStatement( new ConstructorCallExpression( ClassNode.SUPER, conArgs))); return block; }
Example #2
Source File: GroovyGradleParser.java From size-analyzer with Apache License 2.0 | 6 votes |
/** * This will return an initial guess as to the string representation of the parent parent object, * based solely on the method callstack hierarchy. Any direct property or variable parents should * be resolved by using the getValidStringRepresentation function. */ private String getParentParent() { for (int i = methodCallStack.size() - 2; i >= 0; i--) { MethodCallExpression expression = methodCallStack.get(i); Expression arguments = expression.getArguments(); if (arguments instanceof ArgumentListExpression) { ArgumentListExpression ale = (ArgumentListExpression) arguments; List<Expression> expressions = ale.getExpressions(); if (expressions.size() == 1 && expressions.get(0) instanceof ClosureExpression) { return expression.getMethodAsString(); } } } return null; }
Example #3
Source File: DependenciesVisitor.java From synopsys-detect with Apache License 2.0 | 6 votes |
@Override public void visitArgumentlistExpression(final ArgumentListExpression argumentListExpression) { if (inDependenciesBlock) { final List<Expression> expressions = argumentListExpression.getExpressions(); if (expressions.size() == 1 && expressions.get(0) instanceof ClosureExpression) { final ClosureExpression closureExpression = (ClosureExpression) expressions.get(0); if (closureExpression.getCode() instanceof BlockStatement) { final BlockStatement blockStatement = (BlockStatement) closureExpression.getCode(); final List<Statement> statements = blockStatement.getStatements(); for (final Statement statement : statements) { addDependencyFromStatement(statement); } } } } super.visitArgumentlistExpression(argumentListExpression); }
Example #4
Source File: MapConstructorASTTransformation.java From groovy with Apache License 2.0 | 6 votes |
private static ClassCodeExpressionTransformer makeMapTypedArgsTransformer() { return new ClassCodeExpressionTransformer() { @Override public Expression transform(Expression exp) { if (exp instanceof ClosureExpression) { ClosureExpression ce = (ClosureExpression) exp; ce.getCode().visit(this); } else if (exp instanceof VariableExpression) { VariableExpression ve = (VariableExpression) exp; if ("args".equals(ve.getName()) && ve.getAccessedVariable() instanceof DynamicVariable) { VariableExpression newVe = varX(param(MAP_TYPE, "args")); newVe.setSourcePosition(ve); return newVe; } } return exp.transformExpression(this); } @Override protected SourceUnit getSourceUnit() { return null; } }; }
Example #5
Source File: AutoNewLineTransformer.java From groovy with Apache License 2.0 | 6 votes |
@Override public void visitMethodCallExpression(final MethodCallExpression call) { boolean old = inBuilderMethod; inBuilderMethod = false; if (call.isImplicitThis() && call.getArguments() instanceof TupleExpression) { List<Expression> expressions = ((TupleExpression) call.getArguments()).getExpressions(); if (!expressions.isEmpty()) { Expression lastArg = expressions.get(expressions.size() - 1); if (lastArg instanceof ClosureExpression) { call.getObjectExpression().visit(this); call.getMethod().visit(this); for (Expression expression : expressions) { inBuilderMethod = (expression == lastArg); expression.visit(this); } } } } else { super.visitMethodCallExpression(call); } inBuilderMethod = old; }
Example #6
Source File: AutoNewLineTransformer.java From groovy with Apache License 2.0 | 6 votes |
@Override public void visitClosureExpression(final ClosureExpression expression) { super.visitClosureExpression(expression); if (inBuilderMethod) { Statement oldCode = expression.getCode(); BlockStatement block = oldCode instanceof BlockStatement? ((BlockStatement)oldCode): new BlockStatement(Collections.singletonList(oldCode), new VariableScope()); List<Statement> statements = block.getStatements(); if (!statements.isEmpty()) { Statement first = statements.get(0); Statement last = statements.get(statements.size()-1); if (expression.getLineNumber()<first.getLineNumber()) { // there's a new line between { -> ... and the first statement statements.add(0,createNewLine(expression)); } if (expression.getLastLineNumber()>last.getLastLineNumber()) { // there's a new line between { -> ... and the first statement statements.add(createNewLine(expression)); } } expression.setCode(block); } }
Example #7
Source File: AstBuilderTransformation.java From groovy with Apache License 2.0 | 6 votes |
@Override protected boolean handleTargetMethodCallExpression(MethodCallExpression call) { ClosureExpression closureExpression = getClosureArgument(call); List<Expression> otherArgs = getNonClosureArguments(call); String source = convertClosureToSource(closureExpression); // parameter order is build(CompilePhase, boolean, String) otherArgs.add(new ConstantExpression(source)); call.setArguments(new ArgumentListExpression(otherArgs)); call.setMethod(new ConstantExpression("buildFromBlock")); call.setSpreadSafe(false); call.setSafe(false); call.setImplicitThis(false); return false; }
Example #8
Source File: MacroGroovyMethods.java From groovy with Apache License 2.0 | 6 votes |
protected static ClosureExpression getClosureArgument(SourceUnit source, MethodCallExpression call) { TupleExpression tupleArguments = getMacroArguments(source, call); int size = tupleArguments == null ? -1 : tupleArguments.getExpressions().size(); if (size < 1) { source.addError(new SyntaxException("Call arguments should have at least one argument" + '\n', tupleArguments)); return null; } Expression result = tupleArguments.getExpression(size - 1); if (!(result instanceof ClosureExpression)) { source.addError(new SyntaxException("Last call argument should be a closure" + '\n', result)); return null; } return (ClosureExpression) result; }
Example #9
Source File: MemoizedASTTransformation.java From groovy with Apache License 2.0 | 6 votes |
private static MethodCallExpression buildMemoizeClosureCallExpression(MethodNode privateMethod, int protectedCacheSize, int maxCacheSize) { Parameter[] srcParams = privateMethod.getParameters(); Parameter[] newParams = cloneParams(srcParams); List<Expression> argList = new ArrayList<Expression>(newParams.length); for (int i = 0; i < srcParams.length; i++) { argList.add(varX(newParams[i])); } ClosureExpression expression = new ClosureExpression( newParams, stmt(callThisX(privateMethod.getName(), args(argList))) ); MethodCallExpression mce; if (protectedCacheSize == 0 && maxCacheSize == 0) { mce = callX(expression, MEMOIZE_METHOD_NAME); } else if (protectedCacheSize == 0) { mce = callX(expression, MEMOIZE_AT_MOST_METHOD_NAME, args(constX(maxCacheSize))); } else if (maxCacheSize == 0) { mce = callX(expression, MEMOIZE_AT_LEAST_METHOD_NAME, args(constX(protectedCacheSize))); } else { mce = callX(expression, MEMOIZE_BETWEEN_METHOD_NAME, args(constX(protectedCacheSize), constX(maxCacheSize))); } mce.setImplicitThis(false); return mce; }
Example #10
Source File: GeneralUtils.java From groovy with Apache License 2.0 | 6 votes |
public static boolean copyStatementsWithSuperAdjustment(final ClosureExpression pre, final BlockStatement body) { Statement preCode = pre.getCode(); boolean changed = false; if (preCode instanceof BlockStatement) { BlockStatement block = (BlockStatement) preCode; List<Statement> statements = block.getStatements(); for (int i = 0, n = statements.size(); i < n; i += 1) { Statement statement = statements.get(i); // adjust the first statement if it's a super call if (i == 0 && statement instanceof ExpressionStatement) { ExpressionStatement es = (ExpressionStatement) statement; Expression preExp = es.getExpression(); if (preExp instanceof MethodCallExpression) { MethodCallExpression mce = (MethodCallExpression) preExp; String name = mce.getMethodAsString(); if ("super".equals(name)) { es.setExpression(new ConstructorCallExpression(ClassNode.SUPER, mce.getArguments())); changed = true; } } } body.addStatement(statement); } } return changed; }
Example #11
Source File: VariableScopeVisitor.java From groovy with Apache License 2.0 | 6 votes |
@Override public void visitClosureExpression(final ClosureExpression expression) { pushState(); expression.setVariableScope(currentScope); inClosure = !isAnonymous(currentScope.getParent().getClassScope()); if (expression.isParameterSpecified()) { for (Parameter parameter : expression.getParameters()) { parameter.setInStaticContext(currentScope.isInStaticContext()); if (parameter.hasInitialExpression()) { parameter.getInitialExpression().visit(this); } declare(parameter, expression); } } else if (expression.getParameters() != null) { Parameter var = new Parameter(ClassHelper.OBJECT_TYPE, "it"); var.setInStaticContext(currentScope.isInStaticContext()); currentScope.putDeclaredVariable(var); } super.visitClosureExpression(expression); markClosureSharedVariables(); popState(); }
Example #12
Source File: FieldASTTransformation.java From groovy with Apache License 2.0 | 5 votes |
@Override public void visitClosureExpression(final ClosureExpression expression) { ClosureExpression old = currentClosure; currentClosure = expression; super.visitClosureExpression(expression); currentClosure = old; }
Example #13
Source File: AutoImplementASTTransformation.java From groovy with Apache License 2.0 | 5 votes |
private void createMethods(ClassNode cNode, ClassNode exception, String message, ClosureExpression code) { for (MethodNode candidate : getAllCorrectedMethodsMap(cNode).values()) { if (candidate.isAbstract()) { addGeneratedMethod(cNode, candidate.getName(), Opcodes.ACC_PUBLIC, candidate.getReturnType(), candidate.getParameters(), candidate.getExceptions(), methodBody(exception, message, code, candidate.getReturnType())); } } }
Example #14
Source File: GeneralUtils.java From groovy with Apache License 2.0 | 5 votes |
private static boolean hasClosureMember(final AnnotationNode annotation) { Map<String, Expression> members = annotation.getMembers(); for (Map.Entry<String, Expression> member : members.entrySet()) { if (member.getValue() instanceof ClosureExpression) return true; if (member.getValue() instanceof ClassExpression) { ClassExpression classExpression = (ClassExpression) member.getValue(); Class<?> typeClass = classExpression.getType().isResolved() ? classExpression.getType().redirect().getTypeClass() : null; if (typeClass != null && GeneratedClosure.class.isAssignableFrom(typeClass)) return true; } } return false; }
Example #15
Source File: AutoImplementASTTransformation.java From groovy with Apache License 2.0 | 5 votes |
private BlockStatement methodBody(ClassNode exception, String message, ClosureExpression code, ClassNode returnType) { BlockStatement body = new BlockStatement(); if (code != null) { body.addStatement(code.getCode()); } else if (exception != null) { body.addStatement(throwS(ctorX(exception, message == null ? EMPTY_ARGUMENTS : constX(message)))); } else { Expression result = getDefaultValueForPrimitive(returnType); if (result != null) { body.addStatement(returnS(result)); } } return body; }
Example #16
Source File: FinalVariableAnalyzer.java From groovy with Apache License 2.0 | 5 votes |
@Override public void visitClosureExpression(final ClosureExpression expression) { boolean old = inAssignmentRHS; inAssignmentRHS = false; Map<Variable, VariableState> origState = new StateMap(); origState.putAll(getState()); super.visitClosureExpression(expression); cleanLocalVars(origState, getState()); inAssignmentRHS = old; }
Example #17
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 #18
Source File: ClosureWriter.java From groovy with Apache License 2.0 | 5 votes |
public ClassNode getOrAddClosureClass(final ClosureExpression expression, final int modifiers) { ClassNode closureClass = closureClasses.get(expression); if (closureClass == null) { closureClass = createClosureClass(expression, modifiers); closureClasses.put(expression, closureClass); controller.getAcg().addInnerClass(closureClass); closureClass.addInterface(ClassHelper.GENERATED_CLOSURE_Type); closureClass.putNodeMetaData(WriterControllerFactory.class, (WriterControllerFactory) x -> controller); } return closureClass; }
Example #19
Source File: ClosureWriter.java From groovy with Apache License 2.0 | 5 votes |
protected ConstructorNode addConstructor(final ClosureExpression expression, final Parameter[] localVariableParams, final InnerClassNode answer, final BlockStatement block) { Parameter[] params = new Parameter[2 + localVariableParams.length]; params[0] = new Parameter(ClassHelper.OBJECT_TYPE, OUTER_INSTANCE); params[1] = new Parameter(ClassHelper.OBJECT_TYPE, THIS_OBJECT); System.arraycopy(localVariableParams, 0, params, 2, localVariableParams.length); ConstructorNode constructorNode = answer.addConstructor(ACC_PUBLIC, params, ClassNode.EMPTY_ARRAY, block); constructorNode.setSourcePosition(expression); return constructorNode; }
Example #20
Source File: MethodInvocationTrap.java From groovy with Apache License 2.0 | 5 votes |
/** * Converts a ClosureExpression into the String source. * * @param expression a closure * @return the source the closure was created from */ protected String convertClosureToSource(ClosureExpression expression) { try { return ClosureUtils.convertClosureToSource(source, expression); } catch (Exception e) { addError(e.getMessage(), expression); } return null; }
Example #21
Source File: StaticCompilationTransformer.java From groovy with Apache License 2.0 | 5 votes |
@Override public Expression transform(Expression expr) { if (expr instanceof StaticMethodCallExpression) { return staticMethodCallExpressionTransformer.transformStaticMethodCallExpression((StaticMethodCallExpression) expr); } if (expr instanceof BinaryExpression) { return binaryExpressionTransformer.transformBinaryExpression((BinaryExpression)expr); } if (expr instanceof MethodCallExpression) { return methodCallExpressionTransformer.transformMethodCallExpression((MethodCallExpression) expr); } if (expr instanceof ClosureExpression) { return closureExpressionTransformer.transformClosureExpression((ClosureExpression) expr); } if (expr instanceof ConstructorCallExpression) { return constructorCallTransformer.transformConstructorCall((ConstructorCallExpression) expr); } if (expr instanceof BooleanExpression) { return booleanExpressionTransformer.transformBooleanExpression((BooleanExpression)expr); } if (expr instanceof VariableExpression) { return variableExpressionTransformer.transformVariableExpression((VariableExpression)expr); } if (expr instanceof RangeExpression) { return rangeExpressionTransformer.transformRangeExpression(((RangeExpression)expr)); } if (expr instanceof ListExpression) { return listExpressionTransformer.transformListExpression((ListExpression) expr); } if (expr instanceof CastExpression) { return castExpressionTransformer.transformCastExpression(((CastExpression)expr)); } return super.transform(expr); }
Example #22
Source File: ClosureExpressionTransformer.java From groovy with Apache License 2.0 | 5 votes |
Expression transformClosureExpression(final ClosureExpression expr) { for (Parameter parameter : getParametersSafe(expr)) { if (parameter.hasInitialExpression()) { parameter.setInitialExpression(transformer.transform(parameter.getInitialExpression())); } } Statement code = expr.getCode(); transformer.visitClassCodeContainer(code); return transformer.superTransform(expr); }
Example #23
Source File: StaticTypeCheckingSupport.java From groovy with Apache License 2.0 | 5 votes |
/** * Called on method call checks in order to determine if a method call corresponds to the * idiomatic o.with { ... } structure * * @param name name of the method called * @param arguments method call arguments * @return true if the name is "with" and arguments consist of a single closure */ public static boolean isWithCall(final String name, final Expression arguments) { if ("with".equals(name) && arguments instanceof ArgumentListExpression) { List<Expression> args = ((ArgumentListExpression) arguments).getExpressions(); if (args.size() == 1 && args.get(0) instanceof ClosureExpression) { return true; } } return false; }
Example #24
Source File: AutoCloneASTTransformation.java From groovy with Apache License 2.0 | 5 votes |
private void createCloneSerialization(ClassNode cNode) { final BlockStatement body = new BlockStatement(); // def baos = new ByteArrayOutputStream() final Expression baos = localVarX("baos"); body.addStatement(declS(baos, ctorX(BAOS_TYPE))); // baos.withObjectOutputStream{ it.writeObject(this) } MethodCallExpression writeObject = callX(castX(OOS_TYPE, varX("it")), "writeObject", varX("this")); writeObject.setImplicitThis(false); ClosureExpression writeClos = closureX(block(stmt(writeObject))); writeClos.setVariableScope(new VariableScope()); body.addStatement(stmt(callX(baos, "withObjectOutputStream", args(writeClos)))); // def bais = new ByteArrayInputStream(baos.toByteArray()) final Expression bais = localVarX("bais"); body.addStatement(declS(bais, ctorX(BAIS_TYPE, args(callX(baos, "toByteArray"))))); // return bais.withObjectInputStream(getClass().classLoader){ (<type>) it.readObject() } MethodCallExpression readObject = callX(castX(OIS_TYPE, varX("it")), "readObject"); readObject.setImplicitThis(false); ClosureExpression readClos = closureX(block(stmt(castX(GenericsUtils.nonGeneric(cNode), readObject)))); readClos.setVariableScope(new VariableScope()); Expression classLoader = callX(callThisX("getClass"), "getClassLoader"); body.addStatement(returnS(callX(bais, "withObjectInputStream", args(classLoader, readClos)))); new VariableScopeVisitor(sourceUnit, true).visitClass(cNode); ClassNode[] exceptions = {make(CloneNotSupportedException.class)}; addGeneratedMethod(cNode, "clone", ACC_PUBLIC, GenericsUtils.nonGeneric(cNode), Parameter.EMPTY_ARRAY, exceptions, body); }
Example #25
Source File: ASTNodeVisitor.java From groovy-language-server with Apache License 2.0 | 5 votes |
public void visitClosureExpression(ClosureExpression node) { pushASTNode(node); try { super.visitClosureExpression(node); } finally { popASTNode(); } }
Example #26
Source File: ResolveVisitor.java From groovy with Apache License 2.0 | 5 votes |
@Override public Expression transform(final Expression exp) { if (exp == null) return null; Expression ret; if (exp instanceof VariableExpression) { ret = transformVariableExpression((VariableExpression) exp); } else if (exp.getClass() == PropertyExpression.class) { ret = transformPropertyExpression((PropertyExpression) exp); } else if (exp instanceof DeclarationExpression) { ret = transformDeclarationExpression((DeclarationExpression) exp); } else if (exp instanceof BinaryExpression) { ret = transformBinaryExpression((BinaryExpression) exp); } else if (exp instanceof MethodCallExpression) { ret = transformMethodCallExpression((MethodCallExpression) exp); } else if (exp instanceof ClosureExpression) { ret = transformClosureExpression((ClosureExpression) exp); } else if (exp instanceof ConstructorCallExpression) { ret = transformConstructorCallExpression((ConstructorCallExpression) exp); } else if (exp instanceof AnnotationConstantExpression) { ret = transformAnnotationConstantExpression((AnnotationConstantExpression) exp); } else { resolveOrFail(exp.getType(), exp); ret = exp.transformExpression(this); } if (ret != null && ret != exp) { ret.setSourcePosition(exp); } return ret; }
Example #27
Source File: StaticVerifier.java From groovy with Apache License 2.0 | 5 votes |
@Override public void visitClosureExpression(ClosureExpression ce) { boolean oldInClosure = inClosure; inClosure = true; super.visitClosureExpression(ce); inClosure = oldInClosure; }
Example #28
Source File: StaticImportVisitor.java From groovy with Apache License 2.0 | 5 votes |
protected Expression transformClosureExpression(ClosureExpression ce) { boolean oldInClosure = inClosure; inClosure = true; for (Parameter p : getParametersSafe(ce)) { if (p.hasInitialExpression()) { p.setInitialExpression(transform(p.getInitialExpression())); } } Statement code = ce.getCode(); if (code != null) code.visit(this); inClosure = oldInClosure; return ce; }
Example #29
Source File: ContextHelper.java From netbeans with Apache License 2.0 | 5 votes |
/** * Returns the next enclosing {@link ModuleNode} for the given request. * * @param request completion request which includes position information * @return the next surrounding {@link ModuleNode} */ public static ASTNode getSurroundingMethodOrClosure(CompletionContext request) { if (request.path == null) { LOG.log(Level.FINEST, "path == null"); // NOI18N return null; } LOG.log(Level.FINEST, "getSurroundingMethodOrClosure() ----------------------------------------"); LOG.log(Level.FINEST, "Path : {0}", request.path); for (Iterator<ASTNode> it = request.path.iterator(); it.hasNext();) { ASTNode current = it.next(); if (current instanceof MethodNode) { MethodNode mn = (MethodNode) current; LOG.log(Level.FINEST, "Found Method: {0}", mn.getName()); // NOI18N return mn; } else if (current instanceof FieldNode) { FieldNode fn = (FieldNode) current; if (fn.isClosureSharedVariable()) { LOG.log(Level.FINEST, "Found Closure(Field): {0}", fn.getName()); // NOI18N return fn; } } else if (current instanceof ClosureExpression) { LOG.log(Level.FINEST, "Found Closure(Expr.): {0}", ((ClosureExpression) current).getText()); // NOI18N return current; } } return null; }
Example #30
Source File: MacroGroovyMethods.java From groovy with Apache License 2.0 | 5 votes |
@Macro public static Expression macro(MacroContext macroContext, PropertyExpression phaseExpression, ConstantExpression asIsConstantExpression, ClosureExpression closureExpression) { if (closureExpression.getParameters() != null && closureExpression.getParameters().length > 0) { macroContext.getSourceUnit().addError(new SyntaxException("Macro closure arguments are not allowed" + '\n', closureExpression)); return macroContext.getCall(); } final String source; try { source = ClosureUtils.convertClosureToSource(macroContext.getSourceUnit().getSource(), closureExpression); } catch (Exception e) { throw new RuntimeException(e); } BlockStatement closureBlock = (BlockStatement) closureExpression.getCode(); Boolean asIs = (Boolean) asIsConstantExpression.getValue(); return callX( propX(classX(ClassHelper.makeWithoutCaching(MacroBuilder.class, false)), "INSTANCE"), "macro", args( phaseExpression != null ? phaseExpression : constX(null), asIsConstantExpression, constX(source), buildSubstitutions(macroContext.getSourceUnit(), closureExpression), classX(ClassHelper.makeWithoutCaching(MacroBuilder.getMacroValue(closureBlock, asIs).getClass(), false)) ) ); }