Java Code Examples for org.codehaus.groovy.ast.FieldNode#getType()

The following examples show how to use org.codehaus.groovy.ast.FieldNode#getType() . 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
/**
 * RHS instance field. should move most of the code in the BytecodeHelper
 */
public void loadInstanceField(final FieldExpression expression) {
    MethodVisitor mv = controller.getMethodVisitor();
    FieldNode field = expression.getField();
    ClassNode type = field.getType();

    mv.visitVarInsn(ALOAD, 0);
    mv.visitFieldInsn(GETFIELD, getFieldOwnerName(field), field.getName(), BytecodeHelper.getTypeDescription(type));

    if (field.isHolder() && !controller.isInGeneratedFunctionConstructor()) {
        mv.visitMethodInsn(INVOKEVIRTUAL, "groovy/lang/Reference", "get", "()Ljava/lang/Object;", false);
        controller.getOperandStack().push(ClassHelper.OBJECT_TYPE);
    } else {
        controller.getOperandStack().push(type);
    }
}
 
Example 2
Source File: ImmutablePropertyHandler.java    From groovy with Apache License 2.0 6 votes vote down vote up
@Override
public Statement createPropGetter(PropertyNode pNode) {
    FieldNode fNode = pNode.getField();
    BlockStatement body = new BlockStatement();
    final ClassNode fieldType = fNode.getType();
    final Statement statement;
    if (fieldType.isArray() || implementsCloneable(fieldType)) {
        statement = createGetterBodyArrayOrCloneable(fNode);
    } else if (derivesFromDate(fieldType)) {
        statement = createGetterBodyDate(fNode);
    } else {
        statement = createGetterBodyDefault(fNode);
    }
    body.addStatement(statement);
    return body;
}
 
Example 3
Source File: LazyASTTransformation.java    From groovy with Apache License 2.0 6 votes vote down vote up
private static void addHolderClassIdiomBody(BlockStatement body, FieldNode fieldNode, Expression initExpr) {
    final ClassNode declaringClass = fieldNode.getDeclaringClass();
    final ClassNode fieldType = fieldNode.getType();
    final int visibility = ACC_PRIVATE | ACC_STATIC;
    final String fullName = declaringClass.getName() + "$" + fieldType.getNameWithoutPackage() + "Holder_" + fieldNode.getName().substring(1);
    final InnerClassNode holderClass = new InnerClassNode(declaringClass, fullName, visibility, ClassHelper.OBJECT_TYPE);
    final String innerFieldName = "INSTANCE";

    // we have two options:
    // (1) embed initExpr within holder class but redirect field access/method calls to declaring class members
    // (2) keep initExpr within a declaring class method that is only called by the holder class
    // currently we have gone with (2) for simplicity with only a slight memory footprint increase in the declaring class
    final String initializeMethodName = (fullName + "_initExpr").replace('.', '_');
    addGeneratedMethod(declaringClass, initializeMethodName, ACC_PRIVATE | ACC_STATIC | ACC_FINAL, fieldType,
            Parameter.EMPTY_ARRAY, ClassNode.EMPTY_ARRAY, returnS(initExpr));
    holderClass.addField(innerFieldName, ACC_PRIVATE | ACC_STATIC | ACC_FINAL, fieldType,
            callX(declaringClass, initializeMethodName));

    final Expression innerField = propX(classX(holderClass), innerFieldName);
    declaringClass.getModule().addClass(holderClass);
    body.addStatement(returnS(innerField));
}
 
Example 4
Source File: Verifier.java    From groovy with Apache License 2.0 6 votes vote down vote up
private static FieldNode getMetaClassField(ClassNode node) {
    FieldNode ret = node.getDeclaredField("metaClass");
    if (ret != null) {
        ClassNode mcFieldType = ret.getType();
        if (!mcFieldType.equals(ClassHelper.METACLASS_TYPE)) {
            throw new RuntimeParserException("The class " + node.getName() +
                    " cannot declare field 'metaClass' of type " + mcFieldType.getName() + " as it needs to be of " +
                    "the type " + ClassHelper.METACLASS_TYPE.getName() + " for internal groovy purposes", ret);
        }
        return ret;
    }
    ClassNode current = node;
    while (current != ClassHelper.OBJECT_TYPE) {
        current = current.getSuperClass();
        if (current == null) break;
        ret = current.getDeclaredField("metaClass");
        if (ret == null) continue;
        if (isPrivate(ret.getModifiers())) continue;
        return ret;
    }
    return null;
}
 
Example 5
Source File: ImmutablePropertyHandler.java    From groovy with Apache License 2.0 6 votes vote down vote up
protected Statement createConstructorStatement(AbstractASTTransformation xform, ClassNode cNode, PropertyNode pNode, Parameter namedArgsMap) {
    final List<String> knownImmutableClasses = ImmutablePropertyUtils.getKnownImmutableClasses(xform, cNode);
    final List<String> knownImmutables = ImmutablePropertyUtils.getKnownImmutables(xform, cNode);
    FieldNode fNode = pNode.getField();
    final ClassNode fType = fNode.getType();
    Statement statement;
    boolean shouldNullCheck = NullCheckASTTransformation.hasIncludeGenerated(cNode);
    if (ImmutablePropertyUtils.isKnownImmutableType(fType, knownImmutableClasses) || isKnownImmutable(pNode.getName(), knownImmutables)) {
        statement = createConstructorStatementDefault(fNode, namedArgsMap, shouldNullCheck);
    } else if (fType.isArray() || implementsCloneable(fType)) {
        statement = createConstructorStatementArrayOrCloneable(fNode, namedArgsMap, shouldNullCheck);
    } else if (derivesFromDate(fType)) {
        statement = createConstructorStatementDate(fNode, namedArgsMap, shouldNullCheck);
    } else if (isOrImplements(fType, COLLECTION_TYPE) || fType.isDerivedFrom(COLLECTION_TYPE) || isOrImplements(fType, MAP_TYPE) || fType.isDerivedFrom(MAP_TYPE)) {
        statement = createConstructorStatementCollection(fNode, namedArgsMap, shouldNullCheck);
    } else if (fType.isResolved()) {
        xform.addError(ImmutablePropertyUtils.createErrorMessage(cNode.getName(), fNode.getName(), fType.getName(), "compiling"), fNode);
        statement = EmptyStatement.INSTANCE;
    } else {
        statement = createConstructorStatementGuarded(fNode, namedArgsMap, knownImmutables, knownImmutableClasses, shouldNullCheck);
    }
    return statement;
}
 
Example 6
Source File: GeneralUtils.java    From groovy with Apache License 2.0 6 votes vote down vote up
public static Statement createConstructorStatementDefault(final FieldNode fNode) {
    final String name = fNode.getName();
    final ClassNode fType = fNode.getType();
    final Expression fieldExpr = propX(varX("this"), name);
    Expression initExpr = fNode.getInitialValueExpression();
    Statement assignInit;
    if (initExpr == null || (initExpr instanceof ConstantExpression && ((ConstantExpression) initExpr).isNullExpression())) {
        if (ClassHelper.isPrimitiveType(fType)) {
            assignInit = EmptyStatement.INSTANCE;
        } else {
            assignInit = assignS(fieldExpr, ConstantExpression.EMPTY_EXPRESSION);
        }
    } else {
        assignInit = assignS(fieldExpr, initExpr);
    }
    fNode.setInitialValueExpression(null);
    Expression value = findArg(name);
    return ifElseS(equalsNullX(value), assignInit, assignS(fieldExpr, castX(fType, value)));
}
 
Example 7
Source File: ImmutablePropertyHandler.java    From groovy with Apache License 2.0 6 votes vote down vote up
private static Statement createConstructorStatementArrayOrCloneable(FieldNode fNode, Parameter namedArgsMap, boolean shouldNullCheck) {
    final Expression fieldExpr = propX(varX("this"), fNode.getName());
    final ClassNode fieldType = fNode.getType();
    final Expression param = getParam(fNode, namedArgsMap != null);
    Statement assignStmt = assignS(fieldExpr, cloneArrayOrCloneableExpr(param, fieldType));
    assignStmt = ifElseS(
            equalsNullX(param),
            shouldNullCheck ? NullCheckASTTransformation.makeThrowStmt(fNode.getName()) : assignNullS(fieldExpr),
            assignStmt);
    final Statement assignInit;
    final Expression initExpr = fNode.getInitialValueExpression();
    if (initExpr == null || (initExpr instanceof ConstantExpression && ((ConstantExpression) initExpr).isNullExpression())) {
        assignInit = shouldNullCheck ? NullCheckASTTransformation.makeThrowStmt(fNode.getName()) : assignNullS(fieldExpr);
    } else {
        assignInit = assignS(fieldExpr, cloneArrayOrCloneableExpr(initExpr, fieldType));
    }
    return assignFieldWithDefault(namedArgsMap, fNode, assignStmt, assignInit);
}
 
Example 8
Source File: AsmClassGenerator.java    From groovy with Apache License 2.0 5 votes vote down vote up
private void storeThisInstanceField(final FieldExpression expression) {
    OperandStack operandStack = controller.getOperandStack();
    MethodVisitor mv = controller.getMethodVisitor();
    FieldNode field = expression.getField();
    ClassNode type = field.getType();

    if (field.isHolder() && expression.isUseReferenceDirectly()) {
        // rhs is ready to use reference, just put it in the field
        mv.visitVarInsn(ALOAD, 0);
        operandStack.push(controller.getClassNode());
        operandStack.swap();
        mv.visitFieldInsn(PUTFIELD, getFieldOwnerName(field), field.getName(), BytecodeHelper.getTypeDescription(type));
    } else if (field.isHolder()) {
        // rhs is normal value, set the value in the Reference
        operandStack.doGroovyCast(field.getOriginType());
        operandStack.box();
        mv.visitVarInsn(ALOAD, 0);
        mv.visitFieldInsn(GETFIELD, getFieldOwnerName(field), field.getName(), BytecodeHelper.getTypeDescription(type));
        mv.visitInsn(SWAP);
        mv.visitMethodInsn(INVOKEVIRTUAL, "groovy/lang/Reference", "set", "(Ljava/lang/Object;)V", false);
    } else {
        // rhs is normal value, set normal value
        operandStack.doGroovyCast(field.getOriginType());
        mv.visitVarInsn(ALOAD, 0);
        operandStack.push(controller.getClassNode());
        operandStack.swap();
        mv.visitFieldInsn(PUTFIELD, getFieldOwnerName(field), field.getName(), BytecodeHelper.getTypeDescription(type));
    }
}
 
Example 9
Source File: AsmClassGenerator.java    From groovy with Apache License 2.0 5 votes vote down vote up
public void loadStaticField(final FieldExpression expression) {
    MethodVisitor mv = controller.getMethodVisitor();
    FieldNode field = expression.getField();
    ClassNode type = field.getType();

    if (field.isHolder() && !controller.isInGeneratedFunctionConstructor()) {
        mv.visitFieldInsn(GETSTATIC, getFieldOwnerName(field), field.getName(), BytecodeHelper.getTypeDescription(type));
        mv.visitMethodInsn(INVOKEVIRTUAL, "groovy/lang/Reference", "get", "()Ljava/lang/Object;", false);
        controller.getOperandStack().push(ClassHelper.OBJECT_TYPE);
    } else {
        mv.visitFieldInsn(GETSTATIC, getFieldOwnerName(field), field.getName(), BytecodeHelper.getTypeDescription(type));
        controller.getOperandStack().push(type);
    }
}
 
Example 10
Source File: AsmClassGenerator.java    From groovy with Apache License 2.0 5 votes vote down vote up
@Override
public void visitField(final FieldNode fieldNode) {
    onLineNumber(fieldNode, "visitField: " + fieldNode.getName());
    ClassNode t = fieldNode.getType();
    String signature = BytecodeHelper.getGenericsBounds(t);

    Expression initialValueExpression = fieldNode.getInitialValueExpression();
    ConstantExpression cexp = initialValueExpression instanceof ConstantExpression? (ConstantExpression) initialValueExpression :null;
    if (cexp!=null) {
        cexp = Verifier.transformToPrimitiveConstantIfPossible(cexp);
    }
    Object value = cexp != null && ClassHelper.isStaticConstantInitializerType(cexp.getType())
            && cexp.getType().equals(t) && fieldNode.isStatic() && fieldNode.isFinal()
            ? cexp.getValue() : null; // GROOVY-5150
    if (value != null) {
        // byte, char and short require an extra cast
        if (ClassHelper.byte_TYPE.equals(t) || ClassHelper.short_TYPE.equals(t)) {
            value = ((Number) value).intValue();
        } else if (ClassHelper.char_TYPE.equals(t)) {
            value = Integer.valueOf((Character)value);
        }
    }
    FieldVisitor fv = classVisitor.visitField(
            fieldNode.getModifiers(),
            fieldNode.getName(),
            BytecodeHelper.getTypeDescription(t),
            signature,
            value);
    visitAnnotations(fieldNode, fv);
    fv.visitEnd();
}
 
Example 11
Source File: ExternalizeMethodsASTTransformation.java    From groovy with Apache License 2.0 5 votes vote down vote up
private static String suffixForField(FieldNode fNode) {
        // use primitives for efficiency
        if (fNode.getType() == ClassHelper.int_TYPE) return "Int";
        if (fNode.getType() == ClassHelper.boolean_TYPE) return "Boolean";
//        currently char isn't found due to a bug, so go with Object
//        if (fNode.getType() == ClassHelper.char_TYPE) return "Char";
        if (fNode.getType() == ClassHelper.long_TYPE) return "Long";
        if (fNode.getType() == ClassHelper.short_TYPE) return "Short";
        if (fNode.getType() == ClassHelper.byte_TYPE) return "Byte";
        if (fNode.getType() == ClassHelper.float_TYPE) return "Float";
        if (fNode.getType() == ClassHelper.double_TYPE) return "Double";
        return "Object";
    }
 
Example 12
Source File: TupleConstructorASTTransformation.java    From groovy with Apache License 2.0 5 votes vote down vote up
private static Parameter createParam(FieldNode fNode, String name, boolean defaults, AbstractASTTransformation xform, boolean makeImmutable) {
    Parameter param = new Parameter(fNode.getType(), name);
    if (defaults) {
        param.setInitialExpression(providedOrDefaultInitialValue(fNode));
    } else if (!makeImmutable) {
        // TODO we could support some default vals provided they were listed last
        if (fNode.getInitialExpression() != null) {
            xform.addError("Error during " + MY_TYPE_NAME + " processing, default value processing disabled but default value found for '" + fNode.getName() + "'", fNode);
        }
    }
    return param;
}
 
Example 13
Source File: IndexedPropertyASTTransformation.java    From groovy with Apache License 2.0 5 votes vote down vote up
public void visit(ASTNode[] nodes, SourceUnit source) {
    init(nodes, source);
    AnnotatedNode parent = (AnnotatedNode) nodes[1];
    AnnotationNode node = (AnnotationNode) nodes[0];
    if (!MY_TYPE.equals(node.getClassNode())) return;

    if (parent instanceof FieldNode) {
        FieldNode fNode = (FieldNode) parent;
        ClassNode cNode = fNode.getDeclaringClass();
        if (cNode.getProperty(fNode.getName()) == null) {
            addError("Error during " + MY_TYPE_NAME + " processing. Field '" + fNode.getName() +
                    "' doesn't appear to be a property; incorrect visibility?", fNode);
            return;
        }
        ClassNode fType = fNode.getType();
        if (fType.isArray()) {
            addArraySetter(fNode);
            addArrayGetter(fNode);
        } else if (fType.isDerivedFrom(LIST_TYPE)) {
            addListSetter(fNode);
            addListGetter(fNode);
        } else {
            addError("Error during " + MY_TYPE_NAME + " processing. Non-Indexable property '" + fNode.getName() +
                    "' found. Type must be array or list but found " + fType.getName(), fNode);
        }
    }
}
 
Example 14
Source File: AutoCloneASTTransformation.java    From groovy with Apache License 2.0 5 votes vote down vote up
private static void createClone(ClassNode cNode, List<FieldNode> fieldNodes, List<String> excludes) {
    final BlockStatement body = new BlockStatement();

    // def _result = super.clone() as cNode
    final Expression result = localVarX("_result");
    body.addStatement(declS(result, castX(cNode, callSuperX("clone"))));

    for (FieldNode fieldNode : fieldNodes) {
        if (excludes != null && excludes.contains(fieldNode.getName())) continue;
        ClassNode fieldType = fieldNode.getType();
        Expression fieldExpr = varX(fieldNode);
        Expression to = propX(result, fieldNode.getName());
        Statement doClone = assignS(to, castX(fieldType, callCloneDirectX(fieldExpr)));
        Statement doCloneDynamic = assignS(to, castX(fieldType, callCloneDynamicX(fieldExpr)));
        if (isCloneableType(fieldType)) {
            body.addStatement(doClone);
        } else if (possiblyCloneable(fieldType)) {
            body.addStatement(ifS(isInstanceOfX(fieldExpr, CLONEABLE_TYPE), doCloneDynamic));
        }
    }

    // return _result
    body.addStatement(returnS(result));

    ClassNode[] exceptions = {make(CloneNotSupportedException.class)};
    addGeneratedMethod(cNode, "clone", ACC_PUBLIC, GenericsUtils.nonGeneric(cNode), Parameter.EMPTY_ARRAY, exceptions, body);
}
 
Example 15
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 16
Source File: ResolveVisitor.java    From groovy with Apache License 2.0 5 votes vote down vote up
@Override
public void visitField(final FieldNode node) {
    ClassNode t = node.getType();
    if (!fieldTypesChecked.contains(node)) {
        resolveOrFail(t, node);
    }
    super.visitField(node);
}
 
Example 17
Source File: LazyASTTransformation.java    From groovy with Apache License 2.0 4 votes vote down vote up
private static void createSoft(FieldNode fieldNode, Expression initExpr) {
    final ClassNode type = fieldNode.getType();
    fieldNode.setType(SOFT_REF);
    createSoftGetter(fieldNode, initExpr, type);
    createSoftSetter(fieldNode, type);
}
 
Example 18
Source File: Verifier.java    From groovy with Apache License 2.0 4 votes vote down vote up
protected void addInitialization(ClassNode node, ConstructorNode constructorNode) {
    Statement firstStatement = constructorNode.getFirstStatement();
    // if some transformation decided to generate constructor then it probably knows who it does
    if (firstStatement instanceof BytecodeSequence)
        return;

    ConstructorCallExpression first = getFirstIfSpecialConstructorCall(firstStatement);

    // in case of this(...) let the other constructor do the init
    if (first != null && (first.isThisCall())) return;

    List<Statement> statements = new ArrayList<Statement>();
    List<Statement> staticStatements = new ArrayList<Statement>();
    final boolean isEnum = node.isEnum();
    List<Statement> initStmtsAfterEnumValuesInit = new ArrayList<Statement>();
    Set<String> explicitStaticPropsInEnum = new HashSet<String>();
    if (isEnum) {
        for (PropertyNode propNode : node.getProperties()) {
            if (!propNode.isSynthetic() && propNode.getField().isStatic()) {
                explicitStaticPropsInEnum.add(propNode.getField().getName());
            }
        }
        for (FieldNode fieldNode : node.getFields()) {
            if (!fieldNode.isSynthetic() && fieldNode.isStatic() && fieldNode.getType() != node) {
                explicitStaticPropsInEnum.add(fieldNode.getName());
            }
        }
    }

    if (!Traits.isTrait(node)) {
        for (FieldNode fn : node.getFields()) {
            addFieldInitialization(statements, staticStatements, fn, isEnum,
                    initStmtsAfterEnumValuesInit, explicitStaticPropsInEnum);
        }
    }

    statements.addAll(node.getObjectInitializerStatements());

    BlockStatement block = getCodeAsBlock(constructorNode);
    List<Statement> otherStatements = block.getStatements();
    if (!otherStatements.isEmpty()) {
        if (first != null) {
            // it is super(..) since this(..) is already covered
            otherStatements.remove(0);
            statements.add(0, firstStatement);
        }
        Statement stmtThis$0 = getImplicitThis$0StmtIfInnerClass(otherStatements);
        if (stmtThis$0 != null) {
            // since there can be field init statements that depend on method/property dispatching
            // that uses this$0, it needs to bubble up before the super call itself (GROOVY-4471)
            statements.add(0, stmtThis$0);
        }
        statements.addAll(otherStatements);
    }
    BlockStatement newBlock = new BlockStatement(statements, block.getVariableScope());
    newBlock.setSourcePosition(block);
    constructorNode.setCode(newBlock);


    if (!staticStatements.isEmpty()) {
        if (isEnum) {
            /*
             * GROOVY-3161: initialize statements for explicitly declared static fields
             * inside an enum should come after enum values are initialized
             */
            staticStatements.removeAll(initStmtsAfterEnumValuesInit);
            node.addStaticInitializerStatements(staticStatements, true);
            if (!initStmtsAfterEnumValuesInit.isEmpty()) {
                node.positionStmtsAfterEnumInitStmts(initStmtsAfterEnumValuesInit);
            }
        } else {
            node.addStaticInitializerStatements(staticStatements, true);
        }
    }
}
 
Example 19
Source File: AutoCloneASTTransformation.java    From groovy with Apache License 2.0 4 votes vote down vote up
private static void createCloneCopyConstructor(ClassNode cNode, List<FieldNode> list, List<String> excludes) {
    if (cNode.getDeclaredConstructors().isEmpty()) {
        // add no-arg constructor
        BlockStatement noArgBody = new BlockStatement();
        noArgBody.addStatement(EmptyStatement.INSTANCE);
        addGeneratedConstructor(cNode, ACC_PUBLIC, Parameter.EMPTY_ARRAY, ClassNode.EMPTY_ARRAY, noArgBody);
    }
    boolean hasThisCons = false;
    for (ConstructorNode consNode : cNode.getDeclaredConstructors()) {
        Parameter[] parameters = consNode.getParameters();
        if (parameters.length == 1 && parameters[0].getType().equals(cNode)) {
            hasThisCons = true;
        }
    }
    if (!hasThisCons) {
        BlockStatement initBody = new BlockStatement();
        Parameter initParam = param(GenericsUtils.nonGeneric(cNode), "other");
        final Expression other = varX(initParam);
        boolean hasParent = cNode.getSuperClass() != ClassHelper.OBJECT_TYPE;
        if (hasParent) {
            initBody.addStatement(stmt(ctorX(ClassNode.SUPER, other)));
        }
        for (FieldNode fieldNode : list) {
            String name = fieldNode.getName();
            if (excludes != null && excludes.contains(name)) continue;
            ClassNode fieldType = fieldNode.getType();
            Expression direct = propX(other, name);
            Expression to = propX(varX("this"), 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)) {
                initBody.addStatement(assignCloned);
            } else if (!possiblyCloneable(fieldType)) {
                initBody.addStatement(assignDirect);
            } else {
                initBody.addStatement(ifElseS(isInstanceOfX(direct, CLONEABLE_TYPE), assignClonedDynamic, assignDirect));
            }
        }
        addGeneratedConstructor(cNode, ACC_PROTECTED, params(initParam), ClassNode.EMPTY_ARRAY, initBody);
    }
    ClassNode[] exceptions = {make(CloneNotSupportedException.class)};
    addGeneratedMethod(cNode, "clone", ACC_PUBLIC, GenericsUtils.nonGeneric(cNode), Parameter.EMPTY_ARRAY, exceptions, block(stmt(ctorX(cNode, args(varX("this"))))));
}
 
Example 20
Source File: JavaStubGenerator.java    From groovy with Apache License 2.0 4 votes vote down vote up
private void printField(PrintWriter out, FieldNode fieldNode, boolean isInterface) {
    if ((fieldNode.getModifiers() & Opcodes.ACC_PRIVATE) != 0) return;
    printAnnotations(out, fieldNode);
    if (!isInterface) {
        printModifiers(out, fieldNode.getModifiers());
    }

    ClassNode type = fieldNode.getType();
    printType(out, type);

    out.print(" ");
    out.print(fieldNode.getName());
    if (isInterface || (fieldNode.getModifiers() & Opcodes.ACC_FINAL) != 0) {
        out.print(" = ");
        Expression valueExpr = fieldNode.getInitialValueExpression();
        if (valueExpr instanceof ConstantExpression) {
            valueExpr = Verifier.transformToPrimitiveConstantIfPossible((ConstantExpression) valueExpr);
        }
        if (valueExpr instanceof ConstantExpression
                && fieldNode.isStatic() && fieldNode.isFinal()
                && ClassHelper.isStaticConstantInitializerType(valueExpr.getType())
                && valueExpr.getType().equals(fieldNode.getType())) {
            // GROOVY-5150 : Initialize value with a dummy constant so that Java cross compiles correctly
            if (ClassHelper.STRING_TYPE.equals(valueExpr.getType())) {
                out.print(formatString(valueExpr.getText()));
            } else if (ClassHelper.char_TYPE.equals(valueExpr.getType())) {
                out.print("'"+valueExpr.getText()+"'");
            } else {
                ClassNode constantType = valueExpr.getType();
                out.print('(');
                printType(out, type);
                out.print(") ");
                out.print(valueExpr.getText());
                if (ClassHelper.Long_TYPE.equals(ClassHelper.getWrapper(constantType))) out.print('L');
            }
        } else if (ClassHelper.isPrimitiveType(type)) {
            String val = type == ClassHelper.boolean_TYPE ? "false" : "0";
            out.print("new " + ClassHelper.getWrapper(type) + "((" + type + ")" + val + ")");
        } else {
            out.print("null");
        }
    }
    out.println(";");
}