org.codehaus.groovy.ast.expr.CastExpression Java Examples

The following examples show how to use org.codehaus.groovy.ast.expr.CastExpression. 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: InvocationWriter.java    From groovy with Apache License 2.0 6 votes vote down vote up
public void writeInvokeMethod(MethodCallExpression call) {
    if (isClosureCall(call)) {
        // let's invoke the closure method
        invokeClosure(call.getArguments(), call.getMethodAsString());
    } else {
        if (isFunctionInterfaceCall(call)) {
            call = transformToRealMethodCall(call);
        }
        MethodCallerMultiAdapter adapter = invokeMethod;
        Expression objectExpression = call.getObjectExpression();
        if (AsmClassGenerator.isSuperExpression(objectExpression)) {
            adapter = invokeMethodOnSuper;
        } else if (AsmClassGenerator.isThisExpression(objectExpression)) {
            adapter = invokeMethodOnCurrent;
        }
        if (isStaticInvocation(call)) {
            adapter = invokeStaticMethod;
        }
        Expression messageName = new CastExpression(ClassHelper.STRING_TYPE, call.getMethod());
        makeCall(call, objectExpression, messageName, call.getArguments(), adapter, call.isSafe(), call.isSpreadSafe(), call.isImplicitThis());
    }
}
 
Example #2
Source File: InvocationWriter.java    From groovy with Apache License 2.0 6 votes vote down vote up
protected String getMethodName(final Expression message) {
    String methodName = null;
    if (message instanceof CastExpression) {
        CastExpression msg = (CastExpression) message;
        if (msg.getType() == ClassHelper.STRING_TYPE) {
            final Expression methodExpr = msg.getExpression();
            if (methodExpr instanceof ConstantExpression) {
                methodName = methodExpr.getText();
            }
        }
    }

    if (methodName == null && message instanceof ConstantExpression) {
        ConstantExpression constantExpression = (ConstantExpression) message;
        methodName = constantExpression.getText();
    }
    return methodName;
}
 
Example #3
Source File: AsmClassGenerator.java    From groovy with Apache License 2.0 6 votes vote down vote up
void visitTupleExpression(final TupleExpression expression, final boolean useWrapper) {
    MethodVisitor mv = controller.getMethodVisitor();
    int size = expression.getExpressions().size();

    BytecodeHelper.pushConstant(mv, size);
    mv.visitTypeInsn(ANEWARRAY, "java/lang/Object");

    for (int i = 0; i < size; i += 1) {
        mv.visitInsn(DUP);
        BytecodeHelper.pushConstant(mv, i);
        Expression argument = expression.getExpression(i);
        argument.visit(this);
        controller.getOperandStack().box();
        if (useWrapper && argument instanceof CastExpression) loadWrapper(argument);

        mv.visitInsn(AASTORE);
        controller.getOperandStack().remove(1);
    }
}
 
Example #4
Source File: AsmClassGenerator.java    From groovy with Apache License 2.0 6 votes vote down vote up
@Override
public void visitCastExpression(final CastExpression castExpression) {
    ClassNode type = castExpression.getType();
    Expression subExpression = castExpression.getExpression();
    subExpression.visit(this);
    if (ClassHelper.OBJECT_TYPE.equals(type)) return;
    if (castExpression.isCoerce()) {
        controller.getOperandStack().doAsType(type);
    } else {
        if (isNullConstant(subExpression) && !ClassHelper.isPrimitiveType(type)) {
            controller.getOperandStack().replace(type);
        } else {
            ClassNode subExprType = controller.getTypeChooser().resolveType(subExpression, controller.getClassNode());
            if (castExpression.isStrict() ||
                    (!ClassHelper.isPrimitiveType(type) && WideningCategories.implementsInterfaceOrSubclassOf(subExprType, type))) {
                BytecodeHelper.doCast(controller.getMethodVisitor(), type);
                controller.getOperandStack().replace(type);
            } else {
                controller.getOperandStack().doGroovyCast(type);
            }
        }
    }
}
 
Example #5
Source File: SandboxCpsTransformer.java    From groovy-cps with Apache License 2.0 5 votes vote down vote up
@Override
public void visitCastExpression(final CastExpression exp) {
    makeNode("sandboxCastOrCoerce", new Runnable() {
        @Override
        public void run() {
            loc(exp);
            visit(exp.getExpression());
            literal(exp.getType());
            literal(exp.isIgnoringAutoboxing());
            literal(exp.isCoerce());
            literal(exp.isStrict());
        }
    });
}
 
Example #6
Source File: OperandStack.java    From groovy with Apache License 2.0 5 votes vote down vote up
public void pushDynamicName(Expression name) {
    if (name instanceof ConstantExpression) {
        ConstantExpression ce = (ConstantExpression) name;
        Object value = ce.getValue();
        if (value instanceof String) {
            pushConstant(ce);
            return;
        }
    }
    new CastExpression(ClassHelper.STRING_TYPE, name).visit(controller.getAcg());
}
 
Example #7
Source File: CallSiteWriter.java    From groovy with Apache License 2.0 5 votes vote down vote up
public void fallbackAttributeOrPropertySite(PropertyExpression expression, Expression objectExpression, String name, MethodCallerMultiAdapter adapter) {
    if (controller.getCompileStack().isLHS()) controller.getOperandStack().box();
    controller.getInvocationWriter().makeCall(
            expression,
            objectExpression, // receiver
            new CastExpression(ClassHelper.STRING_TYPE, expression.getProperty()), // messageName
            MethodCallExpression.NO_ARGUMENTS, adapter,
            expression.isSafe(), expression.isSpreadSafe(), expression.isImplicitThis()
    );
}
 
Example #8
Source File: StaticCompilationTransformer.java    From groovy with Apache License 2.0 5 votes vote down vote up
@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 #9
Source File: TraitComposer.java    From groovy with Apache License 2.0 5 votes vote down vote up
private static Statement createSuperFallback(MethodNode forwarderMethod, ClassNode returnType) {
    ArgumentListExpression args = new ArgumentListExpression();
    Parameter[] forwarderMethodParameters = forwarderMethod.getParameters();
    for (final Parameter forwarderMethodParameter : forwarderMethodParameters) {
        args.addExpression(new VariableExpression(forwarderMethodParameter));
    }
    BinaryExpression instanceOfExpr = new BinaryExpression(new VariableExpression("this"), Token.newSymbol(Types.KEYWORD_INSTANCEOF, -1, -1), new ClassExpression(Traits.GENERATED_PROXY_CLASSNODE));
    MethodCallExpression superCall = new MethodCallExpression(
            new VariableExpression("super"),
            forwarderMethod.getName(),
            args
    );
    superCall.setImplicitThis(false);
    CastExpression proxyReceiver = new CastExpression(Traits.GENERATED_PROXY_CLASSNODE, new VariableExpression("this"));
    MethodCallExpression getProxy = new MethodCallExpression(proxyReceiver, "getProxyTarget", ArgumentListExpression.EMPTY_ARGUMENTS);
    getProxy.setImplicitThis(true);
    StaticMethodCallExpression proxyCall = new StaticMethodCallExpression(
            ClassHelper.make(InvokerHelper.class),
            "invokeMethod",
            new ArgumentListExpression(getProxy, new ConstantExpression(forwarderMethod.getName()), new ArrayExpression(ClassHelper.OBJECT_TYPE, args.getExpressions()))
    );
    IfStatement stmt = new IfStatement(
            new BooleanExpression(instanceOfExpr),
            new ExpressionStatement(new CastExpression(returnType,proxyCall)),
            new ExpressionStatement(superCall)
    );
    return stmt;
}
 
Example #10
Source File: InvokeDynamicWriter.java    From groovy with Apache License 2.0 5 votes vote down vote up
private void makeIndyCall(MethodCallerMultiAdapter adapter, Expression receiver, boolean implicitThis, boolean safe, String methodName, Expression arguments) {
    OperandStack operandStack = controller.getOperandStack();

    StringBuilder sig = new StringBuilder(prepareIndyCall(receiver, implicitThis));

    // load arguments
    int numberOfArguments = 1;
    ArgumentListExpression ae = makeArgumentList(arguments);
    boolean containsSpreadExpression = AsmClassGenerator.containsSpreadExpression(arguments);
    AsmClassGenerator acg = controller.getAcg();
    if (containsSpreadExpression) {
        acg.despreadList(ae.getExpressions(), true);
        sig.append(getTypeDescription(Object[].class));
    } else {
        for (Expression arg : ae.getExpressions()) {
            arg.visit(acg);
            if (arg instanceof CastExpression) {
                operandStack.box();
                acg.loadWrapper(arg);
                sig.append(getTypeDescription(Wrapper.class));
            } else {
                sig.append(getTypeDescription(operandStack.getTopOperand()));
            }
            numberOfArguments++;
        }
    }

    sig.append(")Ljava/lang/Object;");
    String callSiteName = METHOD.getCallSiteName();
    if (adapter == null) callSiteName = INIT.getCallSiteName();
    int flags = getMethodCallFlags(adapter, safe, containsSpreadExpression);
    finishIndyCall(BSM, callSiteName, sig.toString(), numberOfArguments, methodName, flags);
}
 
Example #11
Source File: ASTNodeVisitor.java    From groovy-language-server with Apache License 2.0 5 votes vote down vote up
public void visitCastExpression(CastExpression node) {
	pushASTNode(node);
	try {
		super.visitCastExpression(node);
	} finally {
		popASTNode();
	}
}
 
Example #12
Source File: GeneralUtils.java    From groovy with Apache License 2.0 4 votes vote down vote up
public static CastExpression castX(final ClassNode type, final Expression expression) {
    return new CastExpression(type, expression);
}
 
Example #13
Source File: DependencyTracker.java    From groovy with Apache License 2.0 4 votes vote down vote up
@Override
public void visitCastExpression(CastExpression expression) {
    super.visitCastExpression(expression);
    addToCache(expression.getType());
}
 
Example #14
Source File: InvocationWriter.java    From groovy with Apache License 2.0 4 votes vote down vote up
protected void makeUncachedCall(Expression origin, ClassExpression sender, Expression receiver, Expression message, Expression arguments, MethodCallerMultiAdapter adapter, boolean safe, boolean spreadSafe, boolean implicitThis, boolean containsSpreadExpression) {
    OperandStack operandStack = controller.getOperandStack();
    CompileStack compileStack = controller.getCompileStack();
    AsmClassGenerator acg = controller.getAcg();

    // ensure VariableArguments are read, not stored
    compileStack.pushLHS(false);

    // sender only for call sites
    if (adapter == AsmClassGenerator.setProperty) {
        ConstantExpression.NULL.visit(acg);
    } else {
        sender.visit(acg);
    }

    String methodName = getMethodName(message);
    if (adapter == invokeMethodOnSuper && methodName != null) {
        controller.getSuperMethodNames().add(methodName);
    }

    // receiver
    compileStack.pushImplicitThis(implicitThis);
    receiver.visit(acg);
    operandStack.box();
    compileStack.popImplicitThis();

    int operandsToRemove = 2;
    // message
    if (message != null) {
        message.visit(acg);
        operandStack.box();
        operandsToRemove += 1;
    }

    // arguments
    int numberOfArguments = containsSpreadExpression ? -1 : AsmClassGenerator.argumentSize(arguments);
    if (numberOfArguments > MethodCallerMultiAdapter.MAX_ARGS || containsSpreadExpression) {
        ArgumentListExpression ae = makeArgumentList(arguments);
        if (containsSpreadExpression) {
            acg.despreadList(ae.getExpressions(), true);
        } else {
            ae.visit(acg);
        }
    } else if (numberOfArguments > 0) {
        operandsToRemove += numberOfArguments;
        TupleExpression te = (TupleExpression) arguments;
        for (int i = 0; i < numberOfArguments; i += 1) {
            Expression argument = te.getExpression(i);
            argument.visit(acg);
            operandStack.box();
            if (argument instanceof CastExpression) acg.loadWrapper(argument);
        }
    }

    if (adapter == null) adapter = invokeMethod;
    adapter.call(controller.getMethodVisitor(), numberOfArguments, safe, spreadSafe);

    compileStack.popLHS();
    operandStack.replace(ClassHelper.OBJECT_TYPE, operandsToRemove);
}
 
Example #15
Source File: GeneralUtils.java    From groovy with Apache License 2.0 4 votes vote down vote up
public static CastExpression castX(final ClassNode type, final Expression expression, final boolean ignoreAutoboxing) {
    return new CastExpression(type, expression, ignoreAutoboxing);
}
 
Example #16
Source File: CodeVisitorSupport.java    From groovy with Apache License 2.0 4 votes vote down vote up
@Override
public void visitCastExpression(CastExpression expression) {
    expression.getExpression().visit(this);
}
 
Example #17
Source File: TransformingCodeVisitor.java    From groovy with Apache License 2.0 4 votes vote down vote up
@Override
public void visitCastExpression(final CastExpression expression) {
    super.visitCastExpression(expression);
    trn.visitCastExpression(expression);
}
 
Example #18
Source File: EqualsAndHashCodeASTTransformation.java    From groovy with Apache License 2.0 4 votes vote down vote up
public static void createEquals(ClassNode cNode, boolean includeFields, boolean callSuper, boolean useCanEqual, List<String> excludes, List<String> includes, boolean allNames, boolean allProperties) {
    if (useCanEqual) createCanEqual(cNode);
    // make a public method if none exists otherwise try a private method with leading underscore
    boolean hasExistingEquals = hasDeclaredMethod(cNode, "equals", 1);
    if (hasExistingEquals && hasDeclaredMethod(cNode, "_equals", 1)) return;

    final BlockStatement body = new BlockStatement();
    VariableExpression other = varX("other");

    // some short circuit cases for efficiency
    body.addStatement(ifS(equalsNullX(other), returnS(constX(Boolean.FALSE, true))));
    body.addStatement(ifS(sameX(varX("this"), other), returnS(constX(Boolean.TRUE, true))));

    if (useCanEqual) {
        body.addStatement(ifS(notX(isInstanceOfX(other, GenericsUtils.nonGeneric(cNode))), returnS(constX(Boolean.FALSE,true))));
    } else {
        body.addStatement(ifS(notX(hasClassX(other, GenericsUtils.nonGeneric(cNode))), returnS(constX(Boolean.FALSE,true))));
    }

    VariableExpression otherTyped = localVarX("otherTyped", GenericsUtils.nonGeneric(cNode));
    CastExpression castExpression = new CastExpression(GenericsUtils.nonGeneric(cNode), other);
    castExpression.setStrict(true);
    body.addStatement(declS(otherTyped, castExpression));

    if (useCanEqual) {
        body.addStatement(ifS(notX(callX(otherTyped, "canEqual", varX("this"))), returnS(constX(Boolean.FALSE,true))));
    }

    final Set<String> names = new HashSet<String>();
    final List<PropertyNode> pList = getAllProperties(names, cNode, true, includeFields, allProperties, false, false, false);
    for (PropertyNode pNode : pList) {
        if (shouldSkipUndefinedAware(pNode.getName(), excludes, includes, allNames)) continue;
        boolean canBeSelf = StaticTypeCheckingSupport.implementsInterfaceOrIsSubclassOf(
                pNode.getOriginType(), cNode
        );
        if (!canBeSelf) {
            body.addStatement(ifS(notX(hasEqualPropertyX(otherTyped.getOriginType(), pNode, otherTyped)), returnS(constX(Boolean.FALSE, true))));
        } else {
            body.addStatement(
                    ifS(notX(hasSamePropertyX(pNode, otherTyped)),
                            ifElseS(differentSelfRecursivePropertyX(pNode, otherTyped),
                                    returnS(constX(Boolean.FALSE, true)),
                                    ifS(notX(bothSelfRecursivePropertyX(pNode, otherTyped)),
                                            ifS(notX(hasEqualPropertyX(otherTyped.getOriginType(), pNode, otherTyped)), returnS(constX(Boolean.FALSE, true))))
                            )
                    )
            );
        }
    }
    List<FieldNode> fList = new ArrayList<FieldNode>();
    if (includeFields) {
        fList.addAll(getInstanceNonPropertyFields(cNode));
    }
    for (FieldNode fNode : fList) {
        if (shouldSkipUndefinedAware(fNode.getName(), excludes, includes, allNames)) continue;
        body.addStatement(
                ifS(notX(hasSameFieldX(fNode, otherTyped)),
                        ifElseS(differentSelfRecursiveFieldX(fNode, otherTyped),
                                returnS(constX(Boolean.FALSE,true)),
                                ifS(notX(bothSelfRecursiveFieldX(fNode, otherTyped)),
                                        ifS(notX(hasEqualFieldX(fNode, otherTyped)), returnS(constX(Boolean.FALSE,true)))))
                ));
    }
    if (callSuper) {
        body.addStatement(ifS(
                notX(isTrueX(callSuperX("equals", other))),
                returnS(constX(Boolean.FALSE,true))
        ));
    }

    // default
    body.addStatement(returnS(constX(Boolean.TRUE,true)));

    MethodNode equal = addGeneratedMethod(cNode,
            hasExistingEquals ? "_equals" : "equals",
            hasExistingEquals ? ACC_PRIVATE : ACC_PUBLIC,
            ClassHelper.boolean_TYPE,
            params(param(OBJECT_TYPE, other.getName())),
            ClassNode.EMPTY_ARRAY,
            body);
    // don't null check this: prefer false to IllegalArgumentException
    NullCheckASTTransformation.markAsProcessed(equal);
}
 
Example #19
Source File: TraitReceiverTransformer.java    From groovy with Apache License 2.0 4 votes vote down vote up
private Expression createFieldHelperReceiver() {
    return ClassHelper.CLASS_Type.equals(weaved.getOriginType()) ? weaved : new CastExpression(fieldHelper, weaved);
}
 
Example #20
Source File: SecureASTCustomizer.java    From groovy with Apache License 2.0 4 votes vote down vote up
@Override
public void visitCastExpression(final CastExpression expression) {
    assertExpressionAuthorized(expression);
    expression.getExpression().visit(this);
}
 
Example #21
Source File: ContextualClassCodeVisitor.java    From groovy with Apache License 2.0 4 votes vote down vote up
@Override
public void visitCastExpression(final CastExpression expression) {
    pushContext(expression);
    super.visitCastExpression(expression);
    popContext();
}
 
Example #22
Source File: ASTFinder.java    From groovy with Apache License 2.0 4 votes vote down vote up
@Override
public void visitCastExpression(final CastExpression expression) {
    super.visitCastExpression(expression);
    tryFind(CastExpression.class, expression);
}
 
Example #23
Source File: PathFinderVisitor.java    From netbeans with Apache License 2.0 4 votes vote down vote up
@Override
public void visitCastExpression(CastExpression node) {
    if (isInside(node, line, column)) {
        super.visitCastExpression(node);
    }
}
 
Example #24
Source File: GroovyCodeVisitor.java    From groovy with Apache License 2.0 votes vote down vote up
void visitCastExpression(CastExpression expression);