Java Code Examples for org.codehaus.groovy.ast.expr.MethodCallExpression#setImplicitThis()

The following examples show how to use org.codehaus.groovy.ast.expr.MethodCallExpression#setImplicitThis() . 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: AstBuilderTransformation.java    From groovy with Apache License 2.0 6 votes vote down vote up
@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 2
Source File: MemoizedASTTransformation.java    From groovy with Apache License 2.0 6 votes vote down vote up
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 3
Source File: AutoCloneASTTransformation.java    From groovy with Apache License 2.0 5 votes vote down vote up
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 4
Source File: ExternalizeMethodsASTTransformation.java    From groovy with Apache License 2.0 5 votes vote down vote up
private static void createWriteExternal(ClassNode cNode, List<String> excludes, List<FieldNode> list) {
    final BlockStatement body = new BlockStatement();
    Parameter out = param(OBJECTOUTPUT_TYPE, "out");
    for (FieldNode fNode : list) {
        if (excludes != null && excludes.contains(fNode.getName())) continue;
        if ((fNode.getModifiers() & ACC_TRANSIENT) != 0) continue;
        MethodCallExpression writeObject = callX(varX(out), "write" + suffixForField(fNode), varX(fNode));
        writeObject.setImplicitThis(false);
        body.addStatement(stmt(writeObject));
    }
    ClassNode[] exceptions = {make(IOException.class)};
    addGeneratedMethod(cNode, "writeExternal", ACC_PUBLIC, ClassHelper.VOID_TYPE, params(out), exceptions, body);
}
 
Example 5
Source File: TraitReceiverTransformer.java    From groovy with Apache License 2.0 5 votes vote down vote up
private Expression createFieldHelperCall(Expression exp, ClassNode weavedType, String propName) {
    String method = Traits.helperGetterName(new FieldNode(propName, 0, ClassHelper.OBJECT_TYPE, weavedType, null));
    MethodCallExpression mce = new MethodCallExpression(
            createFieldHelperReceiver(),
            method,
            ArgumentListExpression.EMPTY_ARGUMENTS
    );
    mce.setSourcePosition(exp instanceof PropertyExpression ? ((PropertyExpression) exp).getProperty() : exp);
    mce.setImplicitThis(false);
    return mce;
}
 
Example 6
Source File: VariableScopeVisitor.java    From groovy with Apache License 2.0 5 votes vote down vote up
@Override
public void visitMethodCallExpression(final MethodCallExpression expression) {
    if (expression.isImplicitThis() && expression.getMethod() instanceof ConstantExpression) {
        ConstantExpression methodNameConstant = (ConstantExpression) expression.getMethod();
        String methodName = methodNameConstant.getText();

        if (methodName == null) {
            throw new GroovyBugError("method name is null");
        }

        Variable variable = findVariableDeclaration(methodName);
        if (variable != null && !(variable instanceof DynamicVariable)) {
            checkVariableContextAccess(variable, expression);
        }

        if (variable instanceof VariableExpression || variable instanceof Parameter) {
            VariableExpression object = new VariableExpression(variable);
            object.setSourcePosition(methodNameConstant);
            expression.setObjectExpression(object);
            ConstantExpression method = new ConstantExpression("call");
            method.setSourcePosition(methodNameConstant); // important for GROOVY-4344
            expression.setImplicitThis(false);
            expression.setMethod(method);
        }
    }
    super.visitMethodCallExpression(expression);
}
 
Example 7
Source File: SuperCallTraitTransformer.java    From groovy with Apache License 2.0 5 votes vote down vote up
private Expression transformMethodCallExpression(final MethodCallExpression exp) {
    if (isTraitSuperPropertyExpression(exp.getObjectExpression())) {
        Expression objectExpression = exp.getObjectExpression();
        ClassNode traitReceiver = ((PropertyExpression) objectExpression).getObjectExpression().getType();

        if (traitReceiver != null) {
            // (SomeTrait.super).foo() --> SomeTrait$Helper.foo(this)
            ClassExpression receiver = new ClassExpression(
                    getHelper(traitReceiver)
            );
            ArgumentListExpression newArgs = new ArgumentListExpression();
            Expression arguments = exp.getArguments();
            newArgs.addExpression(new VariableExpression("this"));
            if (arguments instanceof TupleExpression) {
                List<Expression> expressions = ((TupleExpression) arguments).getExpressions();
                for (Expression expression : expressions) {
                    newArgs.addExpression(transform(expression));
                }
            } else {
                newArgs.addExpression(transform(arguments));
            }
            MethodCallExpression result = new MethodCallExpression(
                    receiver,
                    transform(exp.getMethod()),
                    newArgs
            );
            result.setImplicitThis(false);
            result.setSpreadSafe(exp.isSpreadSafe());
            result.setSafe(exp.isSafe());
            result.setSourcePosition(exp);
            return result;
        }
    }
    return super.transform(exp);
}
 
Example 8
Source File: DefaultPropertyHandler.java    From groovy with Apache License 2.0 5 votes vote down vote up
private static Statement assignFieldS(boolean useSetters, Parameter map, String name) {
    ArgumentListExpression nameArg = args(constX(name));
    MethodCallExpression var = callX(varX(map), "get", nameArg);
    var.setImplicitThis(false);
    MethodCallExpression containsKey = callX(varX(map), "containsKey", nameArg);
    containsKey.setImplicitThis(false);
    return ifS(containsKey, useSetters ?
            setViaSetterS(name, var) :
            assignToFieldS(name, var));
}
 
Example 9
Source File: StaticTypesCallSiteWriter.java    From groovy with Apache License 2.0 5 votes vote down vote up
private void makeDynamicGetProperty(final Expression receiver, final String propertyName, final boolean safe) {
    MethodNode target = safe ? INVOKERHELPER_GETPROPERTYSAFE_METHOD : INVOKERHELPER_GETPROPERTY_METHOD;
    MethodCallExpression call = callX(
            classX(INVOKERHELPER_TYPE),
            target.getName(),
            args(receiver, constX(propertyName))
    );
    call.setImplicitThis(false);
    call.setMethodTarget(target);
    call.setSafe(false);
    call.visit(controller.getAcg());
}
 
Example 10
Source File: TraitReceiverTransformer.java    From groovy with Apache License 2.0 5 votes vote down vote up
private Expression transformPrivateMethodCallOnThisInClosure(final MethodCallExpression call,
                                                             final Expression arguments, final String methodName) {
    ArgumentListExpression newArgs = createArgumentList(arguments);
    MethodCallExpression transformed = new MethodCallExpression(
            new ClassExpression(traitHelperClass),
            methodName,
            newArgs
    );
    transformed.setSourcePosition(call);
    transformed.setSafe(call.isSafe());
    transformed.setSpreadSafe(call.isSpreadSafe());
    transformed.setImplicitThis(true);
    return transformed;
}
 
Example 11
Source File: TryWithResourcesASTTransformation.java    From groovy with Apache License 2.0 5 votes vote down vote up
private ExpressionStatement createCloseResourceStatement(String firstResourceIdentifierName) {
    MethodCallExpression closeMethodCallExpression =
            new MethodCallExpression(new VariableExpression(firstResourceIdentifierName), "close", new ArgumentListExpression());

    closeMethodCallExpression.setImplicitThis(false);
    closeMethodCallExpression.setSafe(true);

    return new ExpressionStatement(closeMethodCallExpression);
}
 
Example 12
Source File: TraitReceiverTransformer.java    From groovy with Apache License 2.0 5 votes vote down vote up
private Expression transformMethodCallOnThisInClosure(final MethodCallExpression call) {
    MethodCallExpression transformed = new MethodCallExpression(
            (Expression) call.getReceiver(),
            call.getMethod(),
            transform(call.getArguments())
    );
    transformed.setSourcePosition(call);
    transformed.setSafe(call.isSafe());
    transformed.setSpreadSafe(call.isSpreadSafe());
    transformed.setImplicitThis(call.isImplicitThis());
    return transformed;
}
 
Example 13
Source File: ImmutablePropertyHandler.java    From groovy with Apache License 2.0 5 votes vote down vote up
private static Statement assignFieldWithDefault(Parameter map, FieldNode fNode, Statement assignStmt, Statement assignInit) {
    if (map == null) {
        return assignStmt;
    }
    ArgumentListExpression nameArg = args(constX(fNode.getName()));
    MethodCallExpression var = callX(varX(map), "get", nameArg);
    var.setImplicitThis(false);
    MethodCallExpression containsKey = callX(varX(map), "containsKey", nameArg);
    containsKey.setImplicitThis(false);
    fNode.getDeclaringClass().getField(fNode.getName()).setInitialValueExpression(null); // to avoid default initialization
    return ifElseS(containsKey, assignStmt, assignInit);
}
 
Example 14
Source File: AutoNewLineTransformer.java    From groovy with Apache License 2.0 5 votes vote down vote up
private Statement createNewLine(final ASTNode node) {
    MethodCallExpression mce = new MethodCallExpression(
            new VariableExpression("this"),
            "newLine",
            ArgumentListExpression.EMPTY_ARGUMENTS
    );
    mce.setImplicitThis(true);
    mce.setSourcePosition(node);
    ExpressionStatement stmt = new ExpressionStatement(mce);
    stmt.setSourcePosition(node);
    return stmt;
}
 
Example 15
Source File: MarkupBuilderCodeTransformer.java    From groovy with Apache License 2.0 5 votes vote down vote up
private Expression tryTransformInclude(final MethodCallExpression exp) {
    Expression arguments = exp.getArguments();
    if (arguments instanceof TupleExpression) {
        List<Expression> expressions = ((TupleExpression) arguments).getExpressions();
        if (expressions.size() == 1 && expressions.get(0) instanceof MapExpression) {
            MapExpression map = (MapExpression) expressions.get(0);
            List<MapEntryExpression> entries = map.getMapEntryExpressions();
            if (entries.size() == 1) {
                MapEntryExpression mapEntry = entries.get(0);
                Expression keyExpression = mapEntry.getKeyExpression();
                try {
                    IncludeType includeType = IncludeType.valueOf(keyExpression.getText().toLowerCase());
                    MethodCallExpression call = new MethodCallExpression(
                            exp.getObjectExpression(),
                            includeType.getMethodName(),
                            new ArgumentListExpression(
                                    mapEntry.getValueExpression()
                            )
                    );
                    call.setImplicitThis(true);
                    call.setSafe(exp.isSafe());
                    call.setSpreadSafe(exp.isSpreadSafe());
                    call.setSourcePosition(exp);
                    return call;
                } catch (IllegalArgumentException e) {
                    // not a valid import type, do not modify the code
                }
            }

        }
    }
    return super.transform(exp);
}
 
Example 16
Source File: MemoizedASTTransformation.java    From groovy with Apache License 2.0 4 votes vote down vote up
public void visit(ASTNode[] nodes, final SourceUnit source) {
    init(nodes, source);
    AnnotationNode annotationNode = (AnnotationNode) nodes[0];
    AnnotatedNode annotatedNode = (AnnotatedNode) nodes[1];
    if (MY_TYPE.equals(annotationNode.getClassNode()) && annotatedNode instanceof MethodNode) {
        MethodNode methodNode = (MethodNode) annotatedNode;
        if (methodNode.isAbstract()) {
            addError("Annotation " + MY_TYPE_NAME + " cannot be used for abstract methods.", methodNode);
            return;
        }
        if (methodNode.isVoidMethod()) {
            addError("Annotation " + MY_TYPE_NAME + " cannot be used for void methods.", methodNode);
            return;
        }

        ClassNode ownerClassNode = methodNode.getDeclaringClass();
        MethodNode delegatingMethod = buildDelegatingMethod(methodNode, ownerClassNode);
        addGeneratedMethod(ownerClassNode, delegatingMethod);

        int modifiers = FieldNode.ACC_PRIVATE | FieldNode.ACC_FINAL;
        if (methodNode.isStatic()) {
            modifiers = modifiers | FieldNode.ACC_STATIC;
        }

        int protectedCacheSize = getMemberIntValue(annotationNode, PROTECTED_CACHE_SIZE_NAME);
        int maxCacheSize = getMemberIntValue(annotationNode, MAX_CACHE_SIZE_NAME);
        MethodCallExpression memoizeClosureCallExpression =
                buildMemoizeClosureCallExpression(delegatingMethod, protectedCacheSize, maxCacheSize);

        String memoizedClosureFieldName = buildUniqueName(ownerClassNode, CLOSURE_LABEL, methodNode);
        FieldNode memoizedClosureField = new FieldNode(memoizedClosureFieldName, modifiers,
                newClass(ClassHelper.CLOSURE_TYPE), null, memoizeClosureCallExpression);
        ownerClassNode.addField(memoizedClosureField);

        BlockStatement newCode = new BlockStatement();
        MethodCallExpression closureCallExpression = callX(
                fieldX(memoizedClosureField), CLOSURE_CALL_METHOD_NAME, args(methodNode.getParameters()));
        closureCallExpression.setImplicitThis(false);
        newCode.addStatement(returnS(closureCallExpression));
        methodNode.setCode(newCode);
        VariableScopeVisitor visitor = new VariableScopeVisitor(source, ownerClassNode instanceof InnerClassNode);
        if (ownerClassNode instanceof InnerClassNode) {
            visitor.visitClass(((InnerClassNode) ownerClassNode).getOuterMostClass());
        } else {
            visitor.visitClass(ownerClassNode);
        }
    }
}
 
Example 17
Source File: MarkupBuilderCodeTransformer.java    From groovy with Apache License 2.0 4 votes vote down vote up
@Override
public Expression transform(final Expression exp) {
    if (exp instanceof BinaryExpression) {
        return transformBinaryExpression((BinaryExpression) exp);
    }
    if (exp instanceof MethodCallExpression) {
        return transformMethodCall((MethodCallExpression) exp);
    }
    if (exp instanceof ClosureExpression) {
        ClosureExpression cl = (ClosureExpression) exp;
        cl.getCode().visit(this);
        return cl;
    }
    if (exp instanceof VariableExpression) {
        VariableExpression var = (VariableExpression) exp;
        if (var.getAccessedVariable() instanceof DynamicVariable) {
            MethodCallExpression callGetModel = new MethodCallExpression(
                    new VariableExpression("this"),
                    "getModel",
                    ArgumentListExpression.EMPTY_ARGUMENTS
            );
            callGetModel.setImplicitThis(true);
            callGetModel.setSourcePosition(exp);
            String varName = var.getName();
            if ("model".equals(varName) || "unescaped".equals(varName)) {
                return callGetModel;
            }
            MethodCallExpression mce = new MethodCallExpression(
                    callGetModel,
                    "get",
                    new ArgumentListExpression(new ConstantExpression(varName))
            );
            mce.setSourcePosition(exp);
            mce.setImplicitThis(false);
            MethodCallExpression yield = new MethodCallExpression(
                    new VariableExpression("this"),
                    "tryEscape",
                    new ArgumentListExpression(mce)
            );
            yield.setImplicitThis(true);
            yield.setSourcePosition(exp);
            yield.putNodeMetaData(TARGET_VARIABLE, varName);
            return autoEscape?yield:mce;
        }
    }
    return super.transform(exp);
}
 
Example 18
Source File: ToStringASTTransformation.java    From groovy with Apache License 2.0 4 votes vote down vote up
private static Expression calculateToStringStatements(ClassNode cNode, boolean includeSuper, boolean includeFields, boolean includeSuperFields, List<String> excludes, final List<String> includes, boolean includeNames, boolean ignoreNulls, boolean includePackage, boolean includeSuperProperties, boolean allProperties, BlockStatement body, boolean allNames) {
    // def _result = new StringBuilder()
    final Expression result = localVarX("_result");
    body.addStatement(declS(result, ctorX(STRINGBUILDER_TYPE)));
    List<ToStringElement> elements = new ArrayList<ToStringElement>();

    // def $toStringFirst = true
    final VariableExpression first = localVarX("$toStringFirst");
    body.addStatement(declS(first, constX(Boolean.TRUE)));

    // <class_name>(
    String className = (includePackage) ? cNode.getName() : cNode.getNameWithoutPackage();
    body.addStatement(appendS(result, constX(className + "(")));

    Set<String> names = new HashSet<String>();
    List<PropertyNode> superList;
    if (includeSuperProperties || includeSuperFields) {
        superList = getAllProperties(names, cNode, cNode.getSuperClass(), includeSuperProperties, includeSuperFields, allProperties, false, true, true, true, allNames, false);
    } else {
        superList = new ArrayList<PropertyNode>();
    }
    List<PropertyNode> list = getAllProperties(names, cNode, cNode,true, includeFields, allProperties, false, false, true, false, allNames, false);
    list.addAll(superList);

    for (PropertyNode pNode : list) {
        String name = pNode.getName();
        if (shouldSkipUndefinedAware(name, excludes, includes, allNames)) continue;
        FieldNode fNode = pNode.getField();
        if (!cNode.hasProperty(name) && fNode.getDeclaringClass() != null) {
            // it's really just a field
            elements.add(new ToStringElement(varX(fNode), name, canBeSelf(cNode, fNode.getType())));
        } else {
            Expression getter = getterThisX(cNode, pNode);
            elements.add(new ToStringElement(getter, name, canBeSelf(cNode, pNode.getType())));
        }
    }

    // append super if needed
    if (includeSuper) {
        // not through MOP to avoid infinite recursion
        elements.add(new ToStringElement(callSuperX("toString"), "super", false));
    }

    if (includes != null) {
        Comparator<ToStringElement> includeComparator = Comparator.comparingInt(tse -> includes.indexOf(tse.name));
        elements.sort(includeComparator);
    }

    for (ToStringElement el : elements) {
        appendValue(body, result, first, el.value, el.name, includeNames, ignoreNulls, el.canBeSelf);
    }

    // wrap up
    body.addStatement(appendS(result, constX(")")));
    MethodCallExpression toString = callX(result, "toString");
    toString.setImplicitThis(false);
    return toString;
}
 
Example 19
Source File: ToStringASTTransformation.java    From groovy with Apache License 2.0 4 votes vote down vote up
private static Statement appendS(Expression result, Expression expr) {
    MethodCallExpression append = callX(result, "append", expr);
    append.setImplicitThis(false);
    return stmt(append);
}
 
Example 20
Source File: MarkupBuilderCodeTransformer.java    From groovy with Apache License 2.0 4 votes vote down vote up
private Expression transformMethodCall(final MethodCallExpression exp) {
    String name = exp.getMethodAsString();
    if (exp.isImplicitThis() && "include".equals(name)) {
        return tryTransformInclude(exp);
    } else if (exp.isImplicitThis() && name.startsWith(":")) {
        List<Expression> args;
        if (exp.getArguments() instanceof ArgumentListExpression) {
            args = ((ArgumentListExpression) exp.getArguments()).getExpressions();
        } else {
            args = Collections.singletonList(exp.getArguments());
        }
        Expression newArguments = transform(new ArgumentListExpression(new ConstantExpression(name.substring(1)), new ArrayExpression(ClassHelper.OBJECT_TYPE, args)));
        MethodCallExpression call = new MethodCallExpression(
                new VariableExpression("this"),
                "methodMissing",
                newArguments
        );
        call.setImplicitThis(true);
        call.setSafe(exp.isSafe());
        call.setSpreadSafe(exp.isSpreadSafe());
        call.setSourcePosition(exp);
        return call;
    } else if (name!=null && name.startsWith("$")) {
        MethodCallExpression reformatted = new MethodCallExpression(
                exp.getObjectExpression(),
                name.substring(1),
                exp.getArguments()
        );
        reformatted.setImplicitThis(exp.isImplicitThis());
        reformatted.setSafe(exp.isSafe());
        reformatted.setSpreadSafe(exp.isSpreadSafe());
        reformatted.setSourcePosition(exp);
        // wrap in a stringOf { ... } closure call
        ClosureExpression clos = new ClosureExpression(Parameter.EMPTY_ARRAY, new ExpressionStatement(reformatted));
        clos.setVariableScope(new VariableScope());
        MethodCallExpression stringOf = new MethodCallExpression(new VariableExpression("this"),
                "stringOf",
                clos);
        stringOf.setImplicitThis(true);
        stringOf.setSourcePosition(reformatted);
        return stringOf;
    }
    return super.transform(exp);
}