org.codehaus.groovy.ast.ClassHelper Java Examples

The following examples show how to use org.codehaus.groovy.ast.ClassHelper. 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: 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 #2
Source File: Java8.java    From groovy with Apache License 2.0 6 votes vote down vote up
private Expression annotationValueToExpression (Object value) {
    if (value == null || value instanceof String || value instanceof Number || value instanceof Character || value instanceof Boolean)
        return new ConstantExpression(value);

    if (value instanceof Class)
        return new ClassExpression(ClassHelper.makeWithoutCaching((Class<?>)value));

    if (value.getClass().isArray()) {
        ListExpression elementExprs = new ListExpression();
        int len = Array.getLength(value);
        for (int i = 0; i != len; ++i)
            elementExprs.addExpression(annotationValueToExpression(Array.get(value, i)));
        return elementExprs;
    }

    return null;
}
 
Example #3
Source File: AssertionWriter.java    From groovy with Apache License 2.0 6 votes vote down vote up
private void record(int normalizedColumn) {
    if (assertionTracker==null) return;
    
    MethodVisitor mv = controller.getMethodVisitor();
    OperandStack operandStack = controller.getOperandStack();
    
    operandStack.dup();
    operandStack.box();
    
    mv.visitVarInsn(ALOAD, assertionTracker.recorderIndex);
    operandStack.push(ClassHelper.OBJECT_TYPE);
    //helper.swapWithObject(ClassHelper.OBJECT_TYPE);
    operandStack.swap();
    mv.visitLdcInsn(normalizedColumn);
    mv.visitMethodInsn(INVOKEVIRTUAL, "org/codehaus/groovy/runtime/powerassert/ValueRecorder", "record", "(Ljava/lang/Object;I)Ljava/lang/Object;", false);
    mv.visitInsn(POP);
    operandStack.remove(2);
}
 
Example #4
Source File: OperandStack.java    From groovy with Apache License 2.0 6 votes vote down vote up
private boolean convertPrimitive(ClassNode top, ClassNode target) {
    if (top==target) return true;
    if (top==ClassHelper.int_TYPE) {
        return convertFromInt(target);
    } else if ( top==ClassHelper.char_TYPE || 
                top==ClassHelper.byte_TYPE ||
                top==ClassHelper.short_TYPE)
    {
        return target == ClassHelper.int_TYPE || convertFromInt(target);
    } else if ( top==ClassHelper.float_TYPE) {
        return convertFromFloat(target);
    } else if ( top==ClassHelper.double_TYPE) {
        return convertFromDouble(target);
    } else if ( top==ClassHelper.long_TYPE) {
        return convertFromLong(target);
    }
    return false;
}
 
Example #5
Source File: BinaryExpressionHelper.java    From groovy with Apache License 2.0 6 votes vote down vote up
private void evaluateLogicalOrExpression(final BinaryExpression expression) {
    AsmClassGenerator acg = controller.getAcg();
    MethodVisitor mv = controller.getMethodVisitor();
    OperandStack operandStack = controller.getOperandStack();

    expression.getLeftExpression().visit(acg);
    operandStack.doGroovyCast(ClassHelper.boolean_TYPE);
    Label trueCase = operandStack.jump(IFNE);

    expression.getRightExpression().visit(acg);
    operandStack.doGroovyCast(ClassHelper.boolean_TYPE);
    Label falseCase = operandStack.jump(IFEQ);

    mv.visitLabel(trueCase);
    ConstantExpression.PRIM_TRUE.visit(acg);
    Label end = new Label();
    operandStack.jump(GOTO, end);

    mv.visitLabel(falseCase);
    ConstantExpression.PRIM_FALSE.visit(acg);

    mv.visitLabel(end);
}
 
Example #6
Source File: BuilderASTTransformation.java    From groovy with Apache License 2.0 6 votes vote down vote up
private BuilderStrategy createBuilderStrategy(AnnotationNode anno, GroovyClassLoader loader) {
    ClassNode strategyClass = getMemberClassValue(anno, "builderStrategy", ClassHelper.make(DefaultStrategy.class));

    if (strategyClass == null) {
        addError("Couldn't determine builderStrategy class", anno);
        return null;
    }

    String className = strategyClass.getName();
    try {
        Object instance = loader.loadClass(className).getDeclaredConstructor().newInstance();
        if (!BuilderStrategy.class.isAssignableFrom(instance.getClass())) {
            addError("The builderStrategy class '" + strategyClass.getName() + "' on " + MY_TYPE_NAME + " is not a builderStrategy", anno);
            return null;
        }

        return (BuilderStrategy) instance;
    } catch (Exception e) {
        addError("Can't load builderStrategy '" + className + "' " + e, anno);
        return null;
    }
}
 
Example #7
Source File: TypeCheckingExtension.java    From groovy with Apache License 2.0 6 votes vote down vote up
/**
 * Given a method call, first checks that it's a static method call, and if it is, returns the
 * class node for the receiver. For example, with the following code:
 * <code></code>Person.findAll { ... }</code>, it would return the class node for <i>Person</i>.
 * If it's not a static method call, returns null.
 * @param call a method call
 * @return null if it's not a static method call, or the class node for the receiver instead.
 */
public ClassNode extractStaticReceiver(MethodCall call) {
    if (call instanceof StaticMethodCallExpression) {
        return ((StaticMethodCallExpression) call).getOwnerType();
    } else if (call instanceof MethodCallExpression) {
        Expression objectExpr = ((MethodCallExpression) call).getObjectExpression();
        if (objectExpr instanceof ClassExpression && ClassHelper.CLASS_Type.equals(objectExpr.getType())) {
            GenericsType[] genericsTypes = objectExpr.getType().getGenericsTypes();
            if (genericsTypes!=null && genericsTypes.length==1) {
                return genericsTypes[0].getType();
            }
        }
        if (objectExpr instanceof ClassExpression) {
            return objectExpr.getType();
        }
    }
    return null;
}
 
Example #8
Source File: AsmClassGenerator.java    From groovy with Apache License 2.0 6 votes vote down vote up
public void despreadList(final List<Expression> expressions, final boolean wrap) {
    List<Expression> spreadIndexes = new ArrayList<>();
    List<Expression> spreadExpressions = new ArrayList<>();
    List<Expression> normalArguments = new ArrayList<>();
    for (int i = 0, n = expressions.size(); i < n; i += 1) {
        Expression expr = expressions.get(i);
        if (!(expr instanceof SpreadExpression)) {
            normalArguments.add(expr);
        } else {
            spreadIndexes.add(new ConstantExpression(i - spreadExpressions.size(), true));
            spreadExpressions.add(((SpreadExpression) expr).getExpression());
        }
    }

    // load normal arguments as array
    visitTupleExpression(new ArgumentListExpression(normalArguments), wrap);
    // load spread expressions as array
    new TupleExpression(spreadExpressions).visit(this);
    // load insertion index
    new ArrayExpression(ClassHelper.int_TYPE, spreadIndexes, null).visit(this);

    controller.getOperandStack().remove(1);
    despreadList.call(controller.getMethodVisitor());
}
 
Example #9
Source File: NullCheckASTTransformation.java    From groovy with Apache License 2.0 6 votes vote down vote up
private void adjustMethod(MethodNode mn, boolean includeGenerated) {
    BlockStatement newCode = getCodeAsBlock(mn);
    if (mn.getParameters().length == 0) return;
    boolean generated = isGenerated(mn);
    int startingIndex = 0;
    if (!includeGenerated && generated) return;
    if (isMarkedAsProcessed(mn)) return;
    if (mn instanceof ConstructorNode) {
        // some transform has been here already and we assume it knows what it is doing
        if (mn.getFirstStatement() instanceof BytecodeSequence) return;
        // ignore any constructors calling this(...) or super(...)
        ConstructorCallExpression cce = ConstructorNodeUtils.getFirstIfSpecialConstructorCall(mn.getCode());
        if (cce != null) {
            if (generated) {
                return;
            } else {
                startingIndex = 1; // skip over this/super() call
            }
        }
    }
    for (Parameter p : mn.getParameters()) {
        if (ClassHelper.isPrimitiveType(p.getType())) continue;
        newCode.getStatements().add(startingIndex, ifS(isNullX(varX(p)), makeThrowStmt(p.getName())));
    }
    mn.setCode(newCode);
}
 
Example #10
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 #11
Source File: AbstractTypeCheckingExtension.java    From groovy with Apache License 2.0 6 votes vote down vote up
public MethodNode newMethod(final String name,
                            final Callable<ClassNode> returnType) {
    MethodNode node = new MethodNode(name,
            Opcodes.ACC_PUBLIC,
            ClassHelper.OBJECT_TYPE,
            Parameter.EMPTY_ARRAY,
            ClassNode.EMPTY_ARRAY,
            EmptyStatement.INSTANCE) {
        @Override
        public ClassNode getReturnType() {
            try {
                return returnType.call();
            } catch (Exception e) {
                return super.getReturnType();
            }
        }
    };
    generatedMethods.add(node);
    return node;
}
 
Example #12
Source File: BinaryIntExpressionHelper.java    From groovy with Apache License 2.0 6 votes vote down vote up
/**
 * writes a std compare. This involves the tokens IF_ICMPEQ, IF_ICMPNE, 
 * IF_ICMPEQ, IF_ICMPNE, IF_ICMPGE, IF_ICMPGT, IF_ICMPLE and IF_ICMPLT
 * @param type the token type
 * @return true if a successful std compare write
 */
protected boolean writeStdCompare(int type, boolean simulate) {
    type = type-COMPARE_NOT_EQUAL;
    // look if really compare
    if (type<0||type>7) return false;

    if (!simulate) {
        MethodVisitor mv = getController().getMethodVisitor();
        OperandStack operandStack = getController().getOperandStack();
        // operands are on the stack already
        int bytecode = stdCompareCodes[type];
        Label l1 = new Label();
        mv.visitJumpInsn(bytecode,l1);
        mv.visitInsn(ICONST_1);
        Label l2 = new Label();
        mv.visitJumpInsn(GOTO, l2);
        mv.visitLabel(l1);
        mv.visitInsn(ICONST_0);
        mv.visitLabel(l2);
        operandStack.replace(ClassHelper.boolean_TYPE, 2);
    }
    return true;
}
 
Example #13
Source File: AnnotationCollectorTransform.java    From groovy with Apache License 2.0 6 votes vote down vote up
private static List<AnnotationNode> makeListOfAnnotations(Object[][] data) {
    if (data.length == 0) {
        return Collections.emptyList();
    }
    List<AnnotationNode> ret = new ArrayList<>(data.length);
    for (Object[] inner : data) {
        Class<?> anno = (Class<?>) inner[0];
        AnnotationNode toAdd = new AnnotationNode(ClassHelper.make(anno));
        ret.add(toAdd);

        @SuppressWarnings("unchecked")
        Map<String,Object> member = (Map<String, Object>) inner[1];
        if (member.isEmpty()) {
            continue;
        }
        Map<String, Expression> generated = new HashMap<>(member.size());
        for (Map.Entry<String, Object> entry : member.entrySet()) {
            generated.put(entry.getKey(), makeExpression(entry.getValue()));
        }
        copyMembers(generated, toAdd);
    }
    return ret;
}
 
Example #14
Source File: StaticInvocationWriter.java    From groovy with Apache License 2.0 6 votes vote down vote up
@Override
public void visit(final GroovyCodeVisitor visitor) {
    receiver.visit(visitor);
    if (visitor instanceof AsmClassGenerator) {
        ClassNode topOperand = controller.getOperandStack().getTopOperand();
        ClassNode type = getType();
        if (ClassHelper.GSTRING_TYPE.equals(topOperand) && ClassHelper.STRING_TYPE.equals(type)) {
            // perform regular type conversion
            controller.getOperandStack().doGroovyCast(type);
            return;
        }
        if (ClassHelper.isPrimitiveType(topOperand) && !ClassHelper.isPrimitiveType(type)) {
            controller.getOperandStack().box();
        } else if (!ClassHelper.isPrimitiveType(topOperand) && ClassHelper.isPrimitiveType(type)) {
            controller.getOperandStack().doGroovyCast(type);
        }
        if (StaticTypeCheckingSupport.implementsInterfaceOrIsSubclassOf(topOperand, type)) return;
        controller.getMethodVisitor().visitTypeInsn(CHECKCAST, type.isArray()
                ? BytecodeHelper.getTypeDescription(type)
                : BytecodeHelper.getClassInternalName(type.getName()));
        controller.getOperandStack().replace(type);
    }
}
 
Example #15
Source File: SortableASTTransformation.java    From groovy with Apache License 2.0 5 votes vote down vote up
private static void createComparatorFor(ClassNode classNode, PropertyNode property, boolean reversed) {
    String propName = StringGroovyMethods.capitalize((CharSequence) property.getName());
    String className = classNode.getName() + "$" + propName + "Comparator";
    ClassNode superClass = makeClassSafeWithGenerics(AbstractComparator.class, classNode);
    InnerClassNode cmpClass = new InnerClassNode(classNode, className, ACC_PRIVATE | ACC_STATIC, superClass);
    addGeneratedInnerClass(classNode, cmpClass);

    addGeneratedMethod(cmpClass,
            "compare",
            ACC_PUBLIC,
            ClassHelper.int_TYPE,
            params(param(newClass(classNode), ARG0), param(newClass(classNode), ARG1)),
            ClassNode.EMPTY_ARRAY,
            createCompareMethodBody(property, reversed)
    );

    String fieldName = "this$" + propName + "Comparator";
    // private final Comparator this$<property>Comparator = new <type>$<property>Comparator();
    FieldNode cmpField = classNode.addField(
            fieldName,
            ACC_STATIC | ACC_FINAL | ACC_PRIVATE | ACC_SYNTHETIC,
            COMPARATOR_TYPE,
            ctorX(cmpClass));

    addGeneratedMethod(classNode,
            "comparatorBy" + propName,
            ACC_PUBLIC | ACC_STATIC,
            COMPARATOR_TYPE,
            Parameter.EMPTY_ARRAY,
            ClassNode.EMPTY_ARRAY,
            returnS(fieldX(cmpField))
    );
}
 
Example #16
Source File: AsmClassGenerator.java    From groovy with Apache License 2.0 5 votes vote down vote up
@Override
public void visitRangeExpression(final RangeExpression expression) {
    OperandStack operandStack = controller.getOperandStack();
    expression.getFrom().visit(this);
    operandStack.box();
    expression.getTo().visit(this);
    operandStack.box();
    operandStack.pushBool(expression.isInclusive());

    createRangeMethod.call(controller.getMethodVisitor());
    operandStack.replace(ClassHelper.RANGE_TYPE, 3);
}
 
Example #17
Source File: Java8.java    From groovy with Apache License 2.0 5 votes vote down vote up
private static ClassNode configureClass(Class<?> c) {
    if (c.isPrimitive()) {
        return ClassHelper.make(c);
    } else {
        return ClassHelper.makeWithoutCaching(c, false);
    }
}
 
Example #18
Source File: AstUtils.java    From pushfish-android with BSD 2-Clause "Simplified" License 5 votes vote down vote up
public static MethodNode getGeneratedClosureImplMethod(ClassNode classNode) {
    if (!classNode.implementsInterface(ClassHelper.GENERATED_CLOSURE_Type)) {
        throw new IllegalArgumentException("expecting generated closure class node");
    }

    List<MethodNode> doCallMethods = classNode.getDeclaredMethods("doCall");
    return doCallMethods.get(0);
}
 
Example #19
Source File: BytecodeHelper.java    From groovy with Apache License 2.0 5 votes vote down vote up
/**
 * Visits a class literal. If the type of the classnode is a primitive type,
 * the generated bytecode will be a GETSTATIC Integer.TYPE.
 * If the classnode is not a primitive type, we will generate a LDC instruction.
 */
public static void visitClassLiteral(MethodVisitor mv, ClassNode classNode) {
    if (ClassHelper.isPrimitiveType(classNode)) {
        mv.visitFieldInsn(
                GETSTATIC,
                getClassInternalName(ClassHelper.getWrapper(classNode)),
                "TYPE",
                "Ljava/lang/Class;");
    } else {
        mv.visitLdcInsn(org.objectweb.asm.Type.getType(getTypeDescription(classNode)));
    }
}
 
Example #20
Source File: AutoCloneASTTransformation.java    From groovy with Apache License 2.0 5 votes vote down vote up
private static void addSimpleCloneHelperMethod(ClassNode cNode, List<FieldNode> fieldNodes, List<String> excludes) {
    Parameter methodParam = new Parameter(GenericsUtils.nonGeneric(cNode), "other");
    final Expression other = varX(methodParam);
    boolean hasParent = cNode.getSuperClass() != ClassHelper.OBJECT_TYPE;
    BlockStatement methodBody = new BlockStatement();
    if (hasParent) {
        methodBody.addStatement(stmt(callSuperX("cloneOrCopyMembers", args(other))));
    }
    for (FieldNode fieldNode : fieldNodes) {
        String name = fieldNode.getName();
        if (excludes != null && excludes.contains(name)) continue;
        ClassNode fieldType = fieldNode.getType();
        Expression direct = propX(varX("this"), name);
        Expression to = propX(other, name);
        Statement assignDirect = assignS(to, direct);
        Statement assignCloned = assignS(to, castX(fieldType, callCloneDirectX(direct)));
        Statement assignClonedDynamic = assignS(to, castX(fieldType, callCloneDynamicX(direct)));
        if (isCloneableType(fieldType)) {
            methodBody.addStatement(assignCloned);
        } else if (!possiblyCloneable(fieldType)) {
            methodBody.addStatement(assignDirect);
        } else {
            methodBody.addStatement(ifElseS(isInstanceOfX(direct, CLONEABLE_TYPE), assignClonedDynamic, assignDirect));
        }
    }
    ClassNode[] exceptions = {make(CloneNotSupportedException.class)};
    addGeneratedMethod(cNode, "cloneOrCopyMembers", ACC_PROTECTED, ClassHelper.VOID_TYPE, params(methodParam), exceptions, methodBody);
}
 
Example #21
Source File: AnnotationCollectorTransform.java    From groovy with Apache License 2.0 5 votes vote down vote up
private Expression serialize(AnnotationNode an) {
    ClassExpression type = new ClassExpression(an.getClassNode());
    type.setSourcePosition(an.getClassNode());

    MapExpression map = new MapExpression();
    for (Map.Entry<String, Expression> entry : an.getMembers().entrySet()) {
        Expression key = new ConstantExpression(entry.getKey());
        Expression val = serialize(entry.getValue());
        map.addMapEntryExpression(key, val);
    }

    return new ArrayExpression(ClassHelper.OBJECT_TYPE, Arrays.asList(type, map));
}
 
Example #22
Source File: ClassCompletionVerifierTest.java    From groovy with Apache License 2.0 5 votes vote down vote up
public void testDetectsIncorrectMethodModifiersInInterface() throws Exception {
    // can't check volatile here as it doubles up with bridge
    ClassNode node = new ClassNode("zzz", ACC_ABSTRACT | ACC_INTERFACE, ClassHelper.OBJECT_TYPE);
    node.addMethod(new MethodNode("st", ACC_STRICT, ClassHelper.OBJECT_TYPE, Parameter.EMPTY_ARRAY, ClassNode.EMPTY_ARRAY, null));
    node.addMethod(new MethodNode("na", ACC_NATIVE, ClassHelper.OBJECT_TYPE, Parameter.EMPTY_ARRAY, ClassNode.EMPTY_ARRAY, null));
    node.addMethod(new MethodNode("sy", ACC_SYNCHRONIZED, ClassHelper.OBJECT_TYPE, Parameter.EMPTY_ARRAY, ClassNode.EMPTY_ARRAY, null));
    addDummyConstructor(node);
    verifier.visitClass(node);
    checkErrorCount(3);
    checkErrorMessage(EXPECTED_STRICT_METHOD_ERROR_MESSAGE);
    checkErrorMessage(EXPECTED_NATIVE_METHOD_ERROR_MESSAGE);
    checkErrorMessage(EXPECTED_SYNCHRONIZED_METHOD_ERROR_MESSAGE);
}
 
Example #23
Source File: ClosureWriter.java    From groovy with Apache License 2.0 5 votes vote down vote up
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 #24
Source File: AnnotationVisitor.java    From groovy with Apache License 2.0 5 votes vote down vote up
protected void visitConstantExpression(String attrName, ConstantExpression constExpr, ClassNode attrType) {
    ClassNode constType = constExpr.getType();
    ClassNode wrapperType = ClassHelper.getWrapper(constType);
    if (!hasCompatibleType(attrType, wrapperType)) {
        addError("Attribute '" + attrName + "' should have type '" + attrType.getName()
                + "'; but found type '" + constType.getName() + "'", constExpr);
    }
}
 
Example #25
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 #26
Source File: InvocationWriter.java    From groovy with Apache License 2.0 5 votes vote down vote up
private static void loadAndCastElement(final OperandStack operandStack, final MethodVisitor mv, final Parameter[] parameters, final int p) {
    operandStack.push(ClassHelper.OBJECT_TYPE);
    mv.visitInsn(DUP);
    BytecodeHelper.pushConstant(mv, p);
    mv.visitInsn(AALOAD);
    operandStack.push(ClassHelper.OBJECT_TYPE);
    ClassNode type = parameters[p].getType();
    operandStack.doGroovyCast(type);
    operandStack.swap();
    operandStack.remove(2);
}
 
Example #27
Source File: EqualsAndHashCodeASTTransformation.java    From groovy with Apache License 2.0 5 votes vote down vote up
public static void createHashCode(ClassNode cNode, boolean cacheResult, boolean includeFields, boolean callSuper, List<String> excludes, List<String> includes, boolean allNames, boolean allProperties) {
    // make a public method if none exists otherwise try a private method with leading underscore
    boolean hasExistingHashCode = hasDeclaredMethod(cNode, "hashCode", 0);
    if (hasExistingHashCode && hasDeclaredMethod(cNode, "_hashCode", 0)) return;

    final BlockStatement body = new BlockStatement();
    // TODO use pList and fList
    if (cacheResult) {
        final FieldNode hashField = cNode.addField("$hash$code", ACC_PRIVATE | ACC_SYNTHETIC, ClassHelper.int_TYPE, null);
        final Expression hash = varX(hashField);
        body.addStatement(ifS(
                isZeroX(hash),
                calculateHashStatements(cNode, hash, includeFields, callSuper, excludes, includes, allNames, allProperties)
        ));
        body.addStatement(returnS(hash));
    } else {
        body.addStatement(calculateHashStatements(cNode, null, includeFields, callSuper, excludes, includes, allNames, allProperties));
    }

    addGeneratedMethod(cNode,
            hasExistingHashCode ? "_hashCode" : "hashCode",
            hasExistingHashCode ? ACC_PRIVATE : ACC_PUBLIC,
            ClassHelper.int_TYPE,
            Parameter.EMPTY_ARRAY,
            ClassNode.EMPTY_ARRAY,
            body);
}
 
Example #28
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 #29
Source File: UnaryExpressionHelper.java    From groovy with Apache License 2.0 5 votes vote down vote up
public void writeBitwiseNegate(BitwiseNegationExpression expression) {
    Expression subExpression = expression.getExpression();
    subExpression.visit(controller.getAcg());
    controller.getOperandStack().box();
    bitwiseNegate.call(controller.getMethodVisitor());
    controller.getOperandStack().replace(ClassHelper.OBJECT_TYPE);
    controller.getAssertionWriter().record(expression);
}
 
Example #30
Source File: ImmutablePropertyHandler.java    From groovy with Apache License 2.0 5 votes vote down vote up
protected Expression cloneCollectionExpr(Expression fieldExpr, ClassNode type) {
    return castX(type, createIfInstanceOfAsImmutableS(fieldExpr, SORTEDSET_CLASSNODE,
            createIfInstanceOfAsImmutableS(fieldExpr, SORTEDMAP_CLASSNODE,
                    createIfInstanceOfAsImmutableS(fieldExpr, SET_CLASSNODE,
                            createIfInstanceOfAsImmutableS(fieldExpr, MAP_CLASSNODE,
                                    createIfInstanceOfAsImmutableS(fieldExpr, ClassHelper.LIST_TYPE,
                                            createAsImmutableX(fieldExpr, COLLECTION_TYPE))
                            )
                    )
            )
    ));
}