Search in sources :

Example 66 with Class

use of com.redhat.ceylon.model.typechecker.model.Class in project ceylon-compiler by ceylon.

the class ClassTransformer method makeDelegateToCompanion.

/**
     * Generates a method which delegates to the companion instance $Foo$impl
     */
private MethodDefinitionBuilder makeDelegateToCompanion(Interface iface, Reference typedMember, Type currentType, final long mods, final java.util.List<TypeParameter> typeParameters, final java.util.List<java.util.List<Type>> producedTypeParameterBounds, final Type methodType, final String methodName, final java.util.List<Parameter> parameters, boolean typeErased, final String targetMethodName, DelegateType delegateType, boolean includeBody) {
    final MethodDefinitionBuilder concreteWrapper = MethodDefinitionBuilder.systemMethod(gen(), methodName);
    concreteWrapper.modifiers(mods);
    concreteWrapper.ignoreModelAnnotations();
    if ((mods & PRIVATE) == 0) {
        concreteWrapper.isOverride(true);
    }
    if (typeParameters != null) {
        concreteWrapper.reifiedTypeParametersFromModel(typeParameters);
    }
    Iterator<java.util.List<Type>> iterator = producedTypeParameterBounds.iterator();
    if (typeParameters != null) {
        for (TypeParameter tp : typeParameters) {
            concreteWrapper.typeParameter(tp, iterator.next());
        }
    }
    boolean explicitReturn = false;
    Declaration member = typedMember.getDeclaration();
    Type returnType = null;
    if (!isAnything(methodType) || ((member instanceof Function || member instanceof Value) && !Decl.isUnboxedVoid(member)) || (member instanceof Function && Strategy.useBoxedVoid((Function) member))) {
        explicitReturn = true;
        if (CodegenUtil.isHashAttribute(member)) {
            // delegates for hash attributes are int
            concreteWrapper.resultType(null, make().Type(syms().intType));
            returnType = typedMember.getType();
        } else if (typedMember instanceof TypedReference) {
            TypedReference typedRef = (TypedReference) typedMember;
            if (delegateType == DelegateType.OTHER) {
                // This is very much like for method refinement: if the supertype is erased -> go raw.
                // Except for some reason we only need to do it with multiple inheritance with different type
                // arguments, so let's not go overboard
                int flags = 0;
                if (CodegenUtil.hasTypeErased((TypedDeclaration) member.getRefinedDeclaration()) || CodegenUtil.hasTypeErased((TypedDeclaration) member) && isInheritedTwiceWithDifferentTypeArguments(currentType, iface)) {
                    flags |= AbstractTransformer.JT_RAW;
                }
                concreteWrapper.resultTypeNonWidening(currentType, typedRef, typedMember.getType(), flags);
                // FIXME: this is redundant with what we computed in the previous line in concreteWrapper.resultTypeNonWidening
                TypedReference nonWideningTypedRef = gen().nonWideningTypeDecl(typedRef, currentType);
                returnType = gen().nonWideningType(typedRef, nonWideningTypedRef);
            } else {
                // for default value
                NonWideningParam nonWideningParam = concreteWrapper.getNonWideningParam(typedRef, currentType.getDeclaration() instanceof Class ? WideningRules.FOR_MIXIN : WideningRules.NONE);
                returnType = nonWideningParam.nonWideningType;
                if (member instanceof Function)
                    returnType = typeFact().getCallableType(returnType);
                concreteWrapper.resultType(null, makeJavaType(returnType, nonWideningParam.flags));
            }
        } else {
            concreteWrapper.resultType(null, makeJavaType((Type) typedMember));
            returnType = (Type) typedMember;
        }
    }
    ListBuffer<JCExpression> arguments = ListBuffer.<JCExpression>lb();
    if (typeParameters != null) {
        for (TypeParameter tp : typeParameters) {
            arguments.add(naming.makeUnquotedIdent(naming.getTypeArgumentDescriptorName(tp)));
        }
    }
    if (typedMember.getDeclaration() instanceof Constructor && !Decl.isDefaultConstructor((Constructor) typedMember.getDeclaration())) {
        concreteWrapper.parameter(makeConstructorNameParameter((Constructor) typedMember.getDeclaration()));
        arguments.add(naming.makeUnquotedIdent(Unfix.$name$));
    }
    for (Parameter param : parameters) {
        final TypedReference typedParameter = typedMember.getTypedParameter(param);
        concreteWrapper.parameter(param, typedParameter, null, FINAL, WideningRules.FOR_MIXIN);
        arguments.add(naming.makeName(param.getModel(), Naming.NA_MEMBER | Naming.NA_ALIASED));
    }
    if (includeBody) {
        JCExpression qualifierThis = makeUnquotedIdent(getCompanionFieldName(iface));
        // our impl accessor to get the expected bounds of the qualifying type
        if (explicitReturn) {
            Type javaType = getBestSatisfiedType(currentType, iface);
            Type ceylonType = typedMember.getQualifyingType();
            // don't even bother if the impl accessor is turned to raw because casting it to raw doesn't help
            if (!isTurnedToRaw(ceylonType) && // if it's exactly the same we don't need any cast
            !javaType.isExactly(ceylonType))
                // this will add the proper cast to the impl accessor
                qualifierThis = expressionGen().applyErasureAndBoxing(qualifierThis, currentType, false, true, BoxingStrategy.BOXED, ceylonType, ExpressionTransformer.EXPR_WANTS_COMPANION);
        }
        JCExpression expr = make().Apply(// TODO Type args
        null, makeSelect(qualifierThis, (targetMethodName != null) ? targetMethodName : methodName), arguments.toList());
        if (isUnimplementedMemberClass(currentType, typedMember)) {
            concreteWrapper.body(makeThrowUnresolvedCompilationError(// TODO encapsulate the error message
            "formal member '" + typedMember.getDeclaration().getName() + "' of '" + iface.getName() + "' not implemented in class hierarchy"));
            current().broken();
        } else if (!explicitReturn) {
            concreteWrapper.body(gen().make().Exec(expr));
        } else {
            // deal with erasure and stuff
            BoxingStrategy boxingStrategy;
            boolean exprBoxed;
            if (member instanceof TypedDeclaration) {
                TypedDeclaration typedDecl = (TypedDeclaration) member;
                exprBoxed = !CodegenUtil.isUnBoxed(typedDecl);
                boxingStrategy = CodegenUtil.getBoxingStrategy(typedDecl);
            } else {
                // must be a class or interface
                exprBoxed = true;
                boxingStrategy = BoxingStrategy.UNBOXED;
            }
            // to force an additional cast
            if (isTurnedToRaw(typedMember.getQualifyingType()) || // in invariant locations
            needsRawCastForMixinSuperCall(iface, methodType) || needsCastForErasedInstantiator(iface, methodName, member))
                typeErased = true;
            expr = gen().expressionGen().applyErasureAndBoxing(expr, methodType, typeErased, exprBoxed, boxingStrategy, returnType, 0);
            concreteWrapper.body(gen().make().Return(expr));
        }
    }
    return concreteWrapper;
}
Also used : TypedDeclaration(com.redhat.ceylon.model.typechecker.model.TypedDeclaration) TypeParameter(com.redhat.ceylon.model.typechecker.model.TypeParameter) NonWideningParam(com.redhat.ceylon.compiler.java.codegen.MethodDefinitionBuilder.NonWideningParam) TypedReference(com.redhat.ceylon.model.typechecker.model.TypedReference) ThrowerCatchallConstructor(com.redhat.ceylon.compiler.java.codegen.recovery.ThrowerCatchallConstructor) Constructor(com.redhat.ceylon.model.typechecker.model.Constructor) Function(com.redhat.ceylon.model.typechecker.model.Function) Type(com.redhat.ceylon.model.typechecker.model.Type) JCExpression(com.sun.tools.javac.tree.JCTree.JCExpression) FunctionOrValue(com.redhat.ceylon.model.typechecker.model.FunctionOrValue) JavaBeanValue(com.redhat.ceylon.model.loader.model.JavaBeanValue) Value(com.redhat.ceylon.model.typechecker.model.Value) TypeParameter(com.redhat.ceylon.model.typechecker.model.TypeParameter) Parameter(com.redhat.ceylon.model.typechecker.model.Parameter) ArrayList(java.util.ArrayList) AnnotationList(com.redhat.ceylon.compiler.typechecker.tree.Tree.AnnotationList) List(com.sun.tools.javac.util.List) ParameterList(com.redhat.ceylon.model.typechecker.model.ParameterList) Class(com.redhat.ceylon.model.typechecker.model.Class) JCNewClass(com.sun.tools.javac.tree.JCTree.JCNewClass) TypedDeclaration(com.redhat.ceylon.model.typechecker.model.TypedDeclaration) Declaration(com.redhat.ceylon.model.typechecker.model.Declaration) TypeDeclaration(com.redhat.ceylon.model.typechecker.model.TypeDeclaration) MethodDeclaration(com.redhat.ceylon.compiler.typechecker.tree.Tree.MethodDeclaration) AttributeDeclaration(com.redhat.ceylon.compiler.typechecker.tree.Tree.AttributeDeclaration)

Example 67 with Class

use of com.redhat.ceylon.model.typechecker.model.Class in project ceylon-compiler by ceylon.

the class ClassTransformer method refineClass.

private Class refineClass(Scope container, Reference pr, ClassOrInterface classModel, Class formalClass, Unit unit) {
    Class refined = new Class();
    refined.setActual(true);
    refined.setShared(formalClass.isShared());
    refined.setContainer(container);
    refined.setExtendedType(formalClass.getType());
    refined.setDeprecated(formalClass.isDeprecated());
    refined.setName(formalClass.getName());
    refined.setRefinedDeclaration(formalClass.getRefinedDeclaration());
    refined.setScope(container);
    //refined.setType(pr.getType());
    refined.setUnit(unit);
    for (ParameterList formalPl : formalClass.getParameterLists()) {
        ParameterList refinedPl = new ParameterList();
        for (Parameter formalP : formalPl.getParameters()) {
            Parameter refinedP = new Parameter();
            refinedP.setAtLeastOne(formalP.isAtLeastOne());
            refinedP.setDeclaration(refined);
            refinedP.setDefaulted(formalP.isDefaulted());
            refinedP.setDeclaredAnything(formalP.isDeclaredAnything());
            refinedP.setHidden(formalP.isHidden());
            refinedP.setSequenced(formalP.isSequenced());
            refinedP.setName(formalP.getName());
            final TypedReference typedParameter = pr.getTypedParameter(formalP);
            FunctionOrValue paramModel;
            if (formalP.getModel() instanceof Value) {
                Value paramValueModel = refineValue((Value) formalP.getModel(), typedParameter, refined, classModel.getUnit());
                paramValueModel.setInitializerParameter(refinedP);
                paramModel = paramValueModel;
            } else {
                Function paramFunctionModel = refineMethod(refined, typedParameter, classModel, (Function) formalP.getModel(), unit);
                paramFunctionModel.setInitializerParameter(refinedP);
                paramModel = paramFunctionModel;
            }
            refinedP.setModel(paramModel);
            refinedPl.getParameters().add(refinedP);
        }
        refined.addParameterList(refinedPl);
    }
    return refined;
}
Also used : Function(com.redhat.ceylon.model.typechecker.model.Function) TypedReference(com.redhat.ceylon.model.typechecker.model.TypedReference) FunctionOrValue(com.redhat.ceylon.model.typechecker.model.FunctionOrValue) JavaBeanValue(com.redhat.ceylon.model.loader.model.JavaBeanValue) Value(com.redhat.ceylon.model.typechecker.model.Value) ParameterList(com.redhat.ceylon.model.typechecker.model.ParameterList) TypeParameter(com.redhat.ceylon.model.typechecker.model.TypeParameter) Parameter(com.redhat.ceylon.model.typechecker.model.Parameter) Class(com.redhat.ceylon.model.typechecker.model.Class) JCNewClass(com.sun.tools.javac.tree.JCTree.JCNewClass) FunctionOrValue(com.redhat.ceylon.model.typechecker.model.FunctionOrValue)

Example 68 with Class

use of com.redhat.ceylon.model.typechecker.model.Class in project ceylon-compiler by ceylon.

the class ClassTransformer method makeParamDefaultValueMethod.

/**
     * Creates a (possibly abstract) method for retrieving the value for a 
     * defaulted parameter
     * @param typeParameterList 
     */
MethodDefinitionBuilder makeParamDefaultValueMethod(boolean noBody, Declaration container, Tree.ParameterList params, Tree.Parameter currentParam) {
    at(currentParam);
    Parameter parameter = currentParam.getParameterModel();
    if (!Strategy.hasDefaultParameterValueMethod(parameter)) {
        throw new BugException();
    }
    MethodDefinitionBuilder methodBuilder = MethodDefinitionBuilder.systemMethod(this, Naming.getDefaultedParamMethodName(container, parameter));
    methodBuilder.ignoreModelAnnotations();
    if (container != null && Decl.isAnnotationConstructor(container)) {
        AnnotationInvocation ac = (AnnotationInvocation) ((Function) container).getAnnotationConstructor();
        for (AnnotationConstructorParameter acp : ac.getConstructorParameters()) {
            if (acp.getParameter().equals(parameter) && acp.getDefaultArgument() != null) {
                methodBuilder.userAnnotations(acp.getDefaultArgument().makeDpmAnnotations(expressionGen()));
            }
        }
    }
    int modifiers = 0;
    if (noBody) {
        modifiers |= PUBLIC | ABSTRACT;
    } else if (container == null || !(container instanceof Class && Strategy.defaultParameterMethodStatic(container))) {
        // initializers can override parameter defaults
        modifiers |= FINAL;
    }
    if (container != null && container.isShared()) {
        modifiers |= PUBLIC;
    } else if (container == null || (!container.isToplevel() && !noBody)) {
        modifiers |= PRIVATE;
    }
    boolean staticMethod = Strategy.defaultParameterMethodStatic(container);
    if (staticMethod) {
        // static default parameter methods should be consistently public so that if non-shared class Top and
        // shared class Bottom which extends Top both have the same default param name, we don't get an error
        // if the Bottom class tries to "hide" a static public method with a private one
        modifiers &= ~PRIVATE;
        modifiers |= STATIC | PUBLIC;
    }
    methodBuilder.modifiers(modifiers);
    if (container instanceof Constructor) {
        copyTypeParameters((Class) container.getContainer(), methodBuilder);
        methodBuilder.reifiedTypeParameters(((Class) container.getContainer()).getTypeParameters());
    } else if (container instanceof Generic) {
        // make sure reified type parameters are accepted
        copyTypeParameters((Generic) container, methodBuilder);
        methodBuilder.reifiedTypeParameters(((Generic) container).getTypeParameters());
    }
    WideningRules wideningRules = !staticMethod && container instanceof Class ? WideningRules.CAN_WIDEN : WideningRules.NONE;
    // Add any of the preceding parameters as parameters to the method
    for (Tree.Parameter p : params.getParameters()) {
        if (p.equals(currentParam)) {
            break;
        }
        at(p);
        methodBuilder.parameter(p.getParameterModel(), null, 0, wideningRules);
    }
    // The method's return type is the same as the parameter's type
    NonWideningParam nonWideningParam = methodBuilder.getNonWideningParam(currentParam.getParameterModel().getModel(), wideningRules);
    methodBuilder.resultType(nonWideningParam.nonWideningDecl, nonWideningParam.nonWideningType, nonWideningParam.flags);
    // The implementation of the method
    if (noBody) {
        methodBuilder.noBody();
    } else {
        HasErrorException error = errors().getFirstExpressionErrorAndMarkBrokenness(Decl.getDefaultArgument(currentParam).getExpression());
        if (error != null) {
            methodBuilder.body(this.makeThrowUnresolvedCompilationError(error));
        } else {
            java.util.List<TypeParameter> copiedTypeParameters = null;
            if (container instanceof Generic) {
                copiedTypeParameters = ((Generic) container).getTypeParameters();
                if (copiedTypeParameters != null)
                    addTypeParameterSubstitution(copiedTypeParameters);
            }
            try {
                JCExpression expr = expressionGen().transform(currentParam);
                JCBlock body = at(currentParam).Block(0, List.<JCStatement>of(at(currentParam).Return(expr)));
                methodBuilder.block(body);
            } finally {
                if (copiedTypeParameters != null)
                    popTypeParameterSubstitution();
            }
        }
    }
    return methodBuilder;
}
Also used : TypeParameter(com.redhat.ceylon.model.typechecker.model.TypeParameter) JCBlock(com.sun.tools.javac.tree.JCTree.JCBlock) NonWideningParam(com.redhat.ceylon.compiler.java.codegen.MethodDefinitionBuilder.NonWideningParam) ThrowerCatchallConstructor(com.redhat.ceylon.compiler.java.codegen.recovery.ThrowerCatchallConstructor) Constructor(com.redhat.ceylon.model.typechecker.model.Constructor) Generic(com.redhat.ceylon.model.typechecker.model.Generic) WideningRules(com.redhat.ceylon.compiler.java.codegen.MethodDefinitionBuilder.WideningRules) JCExpression(com.sun.tools.javac.tree.JCTree.JCExpression) HasErrorException(com.redhat.ceylon.compiler.java.codegen.recovery.HasErrorException) TypeParameter(com.redhat.ceylon.model.typechecker.model.TypeParameter) Parameter(com.redhat.ceylon.model.typechecker.model.Parameter) JCPrimitiveTypeTree(com.sun.tools.javac.tree.JCTree.JCPrimitiveTypeTree) JCTree(com.sun.tools.javac.tree.JCTree) Tree(com.redhat.ceylon.compiler.typechecker.tree.Tree) Class(com.redhat.ceylon.model.typechecker.model.Class) JCNewClass(com.sun.tools.javac.tree.JCTree.JCNewClass)

Example 69 with Class

use of com.redhat.ceylon.model.typechecker.model.Class in project ceylon-compiler by ceylon.

the class ClassTransformer method concreteMembersFromSuperinterfaces.

/**
     * Generates companion fields ($Foo$impl) and methods
     */
private void concreteMembersFromSuperinterfaces(final Class model, ClassDefinitionBuilder classBuilder, Type satisfiedType, Set<Interface> satisfiedInterfaces) {
    satisfiedType = satisfiedType.resolveAliases();
    Interface iface = (Interface) satisfiedType.getDeclaration();
    if (satisfiedInterfaces.contains(iface) || iface.getType().isExactly(typeFact().getIdentifiableDeclaration().getType())) {
        return;
    }
    // then don't instantiate it...
    if (hasImpl(iface)) {
        // ... otherwise for each satisfied interface, 
        // instantiate an instance of the 
        // companion class in the constructor and assign it to a
        // $Interface$impl field
        transformInstantiateCompanions(classBuilder, model, iface, satisfiedType);
    }
    if (!Decl.isCeylon(iface)) {
        // let's not try to implement CMI for Java interfaces
        return;
    }
    // For each super interface
    for (Declaration member : iface.getMembers()) {
        if (member instanceof Class) {
            Class klass = (Class) member;
            final Type typedMember = satisfiedType.getTypeMember(klass, Collections.<Type>emptyList());
            if (Strategy.generateInstantiator(member) && !klass.hasConstructors() && !model.isFormal() && needsCompanionDelegate(model, typedMember) && model.getDirectMember(member.getName(), null, false) == null) {
                // instantiator method implementation
                generateInstantiatorDelegate(classBuilder, satisfiedType, iface, klass, null, model.getType(), !member.isFormal());
            }
            if (klass.hasConstructors()) {
                for (Declaration m : klass.getMembers()) {
                    if (m instanceof Constructor && Strategy.generateInstantiator(m)) {
                        Constructor ctor = (Constructor) m;
                        generateInstantiatorDelegate(classBuilder, satisfiedType, iface, klass, ctor, model.getType(), true);
                    }
                }
            }
        }
        // type aliases are on the $impl class
        if (member instanceof TypeAlias)
            continue;
        if (Strategy.onlyOnCompanion(member)) {
            // (they're just private methods on the $impl)
            continue;
        }
        if (member instanceof Function) {
            Function method = (Function) member;
            final TypedReference typedMember = satisfiedType.getTypedMember(method, Collections.<Type>emptyList());
            Declaration sub = (Declaration) model.getMember(method.getName(), getSignatureIfRequired(typedMember), false, true);
            if (sub instanceof Function) /* && !sub.isAbstraction()*/
            {
                Function subMethod = (Function) sub;
                if (subMethod.getParameterLists().isEmpty()) {
                    continue;
                }
                java.util.List<java.util.List<Type>> producedTypeParameterBounds = producedTypeParameterBounds(typedMember, subMethod);
                //                    final TypedReference refinedTypedMember = model.getType().getTypedMember(subMethod, Collections.<Type>emptyList());
                final java.util.List<TypeParameter> typeParameters = subMethod.getTypeParameters();
                final java.util.List<Parameter> parameters = subMethod.getFirstParameterList().getParameters();
                boolean hasOverloads = false;
                if (!satisfiedInterfaces.contains((Interface) method.getContainer())) {
                    for (Parameter param : parameters) {
                        if (Strategy.hasDefaultParameterValueMethod(param) && CodegenUtil.getTopmostRefinedDeclaration(param.getModel()).getContainer().equals(member)) {
                            final TypedReference typedParameter = typedMember.getTypedParameter(param);
                            // If that method has a defaulted parameter, 
                            // we need to generate a default value method
                            // which also delegates to the $impl
                            final MethodDefinitionBuilder defaultValueDelegate = makeDelegateToCompanion(iface, typedParameter, model.getType(), PUBLIC | FINAL, typeParameters, producedTypeParameterBounds, typedParameter.getFullType(), Naming.getDefaultedParamMethodName(method, param), parameters.subList(0, parameters.indexOf(param)), param.getModel().getTypeErased(), null, DelegateType.FOR_DEFAULT_VALUE);
                            classBuilder.method(defaultValueDelegate);
                        }
                        if (Strategy.hasDefaultParameterOverload(param)) {
                            if ((method.isDefault() || method.isShared() && !method.isFormal()) && Decl.equal(method, subMethod)) {
                                MethodDefinitionBuilder overload = new DefaultedArgumentMethodTyped(new DaoThis((Tree.AnyMethod) null, null), MethodDefinitionBuilder.method(this, subMethod), typedMember, true).makeOverload(subMethod.getFirstParameterList(), param, typeParameters);
                                classBuilder.method(overload);
                            }
                            hasOverloads = true;
                        }
                    }
                }
                // delegating to the $impl instance
                if (needsCompanionDelegate(model, typedMember)) {
                    final MethodDefinitionBuilder concreteMemberDelegate = makeDelegateToCompanion(iface, typedMember, model.getType(), PUBLIC | (method.isDefault() ? 0 : FINAL), typeParameters, producedTypeParameterBounds, typedMember.getType(), naming.selector(method), method.getFirstParameterList().getParameters(), ((Function) member).getTypeErased(), null, DelegateType.OTHER);
                    classBuilder.method(concreteMemberDelegate);
                }
                if (hasOverloads && (method.isDefault() || method.isShared() && !method.isFormal()) && Decl.equal(method, subMethod)) {
                    final MethodDefinitionBuilder canonicalMethod = makeDelegateToCompanion(iface, typedMember, model.getType(), PRIVATE, subMethod.getTypeParameters(), producedTypeParameterBounds, typedMember.getType(), Naming.selector(method, Naming.NA_CANONICAL_METHOD), method.getFirstParameterList().getParameters(), ((Function) member).getTypeErased(), naming.selector(method), DelegateType.OTHER);
                    classBuilder.method(canonicalMethod);
                }
            }
        } else if (member instanceof Value || member instanceof Setter) {
            TypedDeclaration attr = (TypedDeclaration) member;
            final TypedReference typedMember = satisfiedType.getTypedMember(attr, null);
            if (needsCompanionDelegate(model, typedMember)) {
                Setter setter = (member instanceof Setter) ? (Setter) member : null;
                if (member instanceof Value) {
                    if (member instanceof JavaBeanValue) {
                        setter = ((Value) member).getSetter();
                    }
                    final MethodDefinitionBuilder getterDelegate = makeDelegateToCompanion(iface, typedMember, model.getType(), PUBLIC | (attr.isDefault() ? 0 : FINAL), Collections.<TypeParameter>emptyList(), Collections.<java.util.List<Type>>emptyList(), typedMember.getType(), Naming.getGetterName(attr), Collections.<Parameter>emptyList(), attr.getTypeErased(), null, DelegateType.OTHER);
                    classBuilder.method(getterDelegate);
                }
                if (setter != null) {
                    final MethodDefinitionBuilder setterDelegate = makeDelegateToCompanion(iface, satisfiedType.getTypedMember(setter, null), model.getType(), PUBLIC | (setter.getGetter().isDefault() ? 0 : FINAL), Collections.<TypeParameter>emptyList(), Collections.<java.util.List<Type>>emptyList(), typeFact().getAnythingType(), Naming.getSetterName(attr), Collections.<Parameter>singletonList(setter.getParameter()), setter.getTypeErased(), null, DelegateType.OTHER);
                    classBuilder.method(setterDelegate);
                }
                if (Decl.isValue(member) && ((Value) attr).isVariable()) {
                    // $impl to delegate to
                    throw new BugException("assertion failed: " + member.getQualifiedNameString() + " was unexpectedly a variable value");
                }
            }
        } else {
            Reference typedMember = member instanceof TypeDeclaration ? satisfiedType.getTypeMember((TypeDeclaration) member, Collections.<Type>emptyList()) : satisfiedType.getTypedMember((TypedDeclaration) member, Collections.<Type>emptyList());
            if (needsCompanionDelegate(model, typedMember)) {
                throw new BugException("unhandled concrete interface member " + member.getQualifiedNameString() + " " + member.getClass());
            }
        }
    }
    // Add $impl instances for the whole interface hierarchy
    satisfiedInterfaces.add(iface);
    for (Type sat : iface.getSatisfiedTypes()) {
        sat = model.getType().getSupertype(sat.getDeclaration());
        concreteMembersFromSuperinterfaces(model, classBuilder, sat, satisfiedInterfaces);
    }
}
Also used : TypeParameter(com.redhat.ceylon.model.typechecker.model.TypeParameter) TypedReference(com.redhat.ceylon.model.typechecker.model.TypedReference) Function(com.redhat.ceylon.model.typechecker.model.Function) JCPrimitiveTypeTree(com.sun.tools.javac.tree.JCTree.JCPrimitiveTypeTree) JCTree(com.sun.tools.javac.tree.JCTree) Tree(com.redhat.ceylon.compiler.typechecker.tree.Tree) ArrayList(java.util.ArrayList) AnnotationList(com.redhat.ceylon.compiler.typechecker.tree.Tree.AnnotationList) List(com.sun.tools.javac.util.List) ParameterList(com.redhat.ceylon.model.typechecker.model.ParameterList) TypedDeclaration(com.redhat.ceylon.model.typechecker.model.TypedDeclaration) Declaration(com.redhat.ceylon.model.typechecker.model.Declaration) TypeDeclaration(com.redhat.ceylon.model.typechecker.model.TypeDeclaration) MethodDeclaration(com.redhat.ceylon.compiler.typechecker.tree.Tree.MethodDeclaration) AttributeDeclaration(com.redhat.ceylon.compiler.typechecker.tree.Tree.AttributeDeclaration) TypedDeclaration(com.redhat.ceylon.model.typechecker.model.TypedDeclaration) ThrowerCatchallConstructor(com.redhat.ceylon.compiler.java.codegen.recovery.ThrowerCatchallConstructor) Constructor(com.redhat.ceylon.model.typechecker.model.Constructor) Reference(com.redhat.ceylon.model.typechecker.model.Reference) TypedReference(com.redhat.ceylon.model.typechecker.model.TypedReference) TypeAlias(com.redhat.ceylon.model.typechecker.model.TypeAlias) Type(com.redhat.ceylon.model.typechecker.model.Type) FunctionOrValue(com.redhat.ceylon.model.typechecker.model.FunctionOrValue) JavaBeanValue(com.redhat.ceylon.model.loader.model.JavaBeanValue) Value(com.redhat.ceylon.model.typechecker.model.Value) Setter(com.redhat.ceylon.model.typechecker.model.Setter) TypeParameter(com.redhat.ceylon.model.typechecker.model.TypeParameter) Parameter(com.redhat.ceylon.model.typechecker.model.Parameter) Class(com.redhat.ceylon.model.typechecker.model.Class) JCNewClass(com.sun.tools.javac.tree.JCTree.JCNewClass) JavaBeanValue(com.redhat.ceylon.model.loader.model.JavaBeanValue) TypeDeclaration(com.redhat.ceylon.model.typechecker.model.TypeDeclaration) ClassOrInterface(com.redhat.ceylon.model.typechecker.model.ClassOrInterface) LazyInterface(com.redhat.ceylon.model.loader.model.LazyInterface) Interface(com.redhat.ceylon.model.typechecker.model.Interface)

Example 70 with Class

use of com.redhat.ceylon.model.typechecker.model.Class in project ceylon-compiler by ceylon.

the class ClassTransformer method transformAnnotationClassConstructor.

/**
     * Generates a constructor for an annotation class which takes the 
     * annotation type as parameter.
     * @param classBuilder
     */
private void transformAnnotationClassConstructor(Tree.AnyClass def, ClassDefinitionBuilder classBuilder) {
    Class klass = def.getDeclarationModel();
    MethodDefinitionBuilder annoCtor = classBuilder.addConstructor();
    annoCtor.ignoreModelAnnotations();
    // constructors are never final
    annoCtor.modifiers(transformClassDeclFlags(klass) & ~FINAL);
    ParameterDefinitionBuilder pdb = ParameterDefinitionBuilder.systemParameter(this, "anno");
    pdb.type(makeJavaType(klass.getType(), JT_ANNOTATION), null);
    annoCtor.parameter(pdb);
    // It's up to the caller to invoke value() on the Java annotation for a sequenced
    // annotation
    ListBuffer<JCExpression> args = ListBuffer.lb();
    for (Tree.Parameter parameter : def.getParameterList().getParameters()) {
        at(parameter);
        Parameter parameterModel = parameter.getParameterModel();
        JCExpression annoAttr = make().Apply(null, naming.makeQuotedQualIdent(naming.makeUnquotedIdent("anno"), parameter.getParameterModel().getName()), List.<JCExpression>nil());
        Type parameterType = parameterModel.getType();
        JCExpression argExpr;
        if (typeFact().isIterableType(parameterType) && !isCeylonString(parameterType)) {
            // Convert from array to Sequential
            Type iteratedType = typeFact().getIteratedType(parameterType);
            boolean nonEmpty = typeFact().isNonemptyIterableType(parameterType);
            if (isCeylonBasicType(iteratedType)) {
                argExpr = utilInvocation().sequentialWrapperBoxed(annoAttr);
            } else if (Decl.isAnnotationClass(iteratedType.getDeclaration())) {
                // Can't use Util.sequentialAnnotation becase we need to 'box'
                // the Java annotations in their Ceylon annotation class
                argExpr = make().Apply(null, naming.makeUnquotedIdent(naming.getAnnotationSequenceMethodName()), List.of(annoAttr));
                ListBuffer<JCStatement> stmts = ListBuffer.lb();
                SyntheticName array = naming.synthetic(Unfix.$array$);
                SyntheticName sb = naming.synthetic(Unfix.$sb$);
                SyntheticName index = naming.synthetic(Unfix.$index$);
                SyntheticName element = naming.synthetic(Unfix.$element$);
                stmts.append(makeVar(FINAL, sb, make().TypeArray(make().Type(syms().objectType)), make().NewArray(make().Type(syms().objectType), List.of(naming.makeQualIdent(array.makeIdent(), "length")), null)));
                stmts.append(makeVar(index, make().Type(syms().intType), make().Literal(0)));
                stmts.append(make().ForeachLoop(makeVar(element, makeJavaType(iteratedType, JT_ANNOTATION), null), array.makeIdent(), make().Exec(make().Assign(make().Indexed(sb.makeIdent(), make().Unary(JCTree.POSTINC, index.makeIdent())), instantiateAnnotationClass(iteratedType, element.makeIdent())))));
                stmts.append(make().Return(make().NewClass(null, null, make().QualIdent(syms().ceylonTupleType.tsym), List.of(makeReifiedTypeArgument(iteratedType), sb.makeIdent(), makeEmpty(), make().Literal(false)), null)));
                classBuilder.method(MethodDefinitionBuilder.systemMethod(this, naming.getAnnotationSequenceMethodName()).ignoreModelAnnotations().modifiers(PRIVATE | STATIC).resultType(null, makeJavaType(typeFact().getSequentialType(iteratedType))).parameter(ParameterDefinitionBuilder.systemParameter(this, array.getName()).type(make().TypeArray(makeJavaType(iteratedType, JT_ANNOTATION)), null)).body(stmts.toList()));
            } else if (isCeylonMetamodelDeclaration(iteratedType)) {
                argExpr = makeMetamodelInvocation("parseMetamodelReferences", List.<JCExpression>of(makeReifiedTypeArgument(iteratedType), annoAttr), List.<JCExpression>of(makeJavaType(iteratedType, JT_TYPE_ARGUMENT)));
            } else if (Decl.isEnumeratedTypeWithAnonCases(iteratedType)) {
                argExpr = makeMetamodelInvocation("parseEnumerationReferences", List.<JCExpression>of(makeReifiedTypeArgument(iteratedType), annoAttr), List.<JCExpression>of(makeJavaType(iteratedType, JT_TYPE_ARGUMENT)));
            } else {
                argExpr = makeErroneous(parameter, "compiler bug");
            }
            if (nonEmpty) {
                argExpr = make().TypeCast(makeJavaType(parameterType), argExpr);
            }
        } else if (Decl.isAnnotationClass(parameterType.getDeclaration())) {
            argExpr = instantiateAnnotationClass(parameterType, annoAttr);
        } else if (isCeylonMetamodelDeclaration(parameterType)) {
            argExpr = makeMetamodelInvocation("parseMetamodelReference", List.<JCExpression>of(annoAttr), List.<JCExpression>of(makeJavaType(parameterType, JT_TYPE_ARGUMENT)));
        } else if (Decl.isEnumeratedTypeWithAnonCases(parameterType)) {
            argExpr = makeMetamodelInvocation("parseEnumerationReference", List.<JCExpression>of(annoAttr), null);
        } else {
            argExpr = annoAttr;
            argExpr = expressionGen().applyErasureAndBoxing(annoAttr, parameterType.withoutUnderlyingType(), false, BoxingStrategy.UNBOXED, parameterType);
        }
        args.add(argExpr);
    }
    annoCtor.body(at(def).Exec(make().Apply(null, naming.makeThis(), args.toList())));
}
Also used : Type(com.redhat.ceylon.model.typechecker.model.Type) JCExpression(com.sun.tools.javac.tree.JCTree.JCExpression) ListBuffer(com.sun.tools.javac.util.ListBuffer) JCPrimitiveTypeTree(com.sun.tools.javac.tree.JCTree.JCPrimitiveTypeTree) JCTree(com.sun.tools.javac.tree.JCTree) Tree(com.redhat.ceylon.compiler.typechecker.tree.Tree) TypeParameter(com.redhat.ceylon.model.typechecker.model.TypeParameter) Parameter(com.redhat.ceylon.model.typechecker.model.Parameter) SyntheticName(com.redhat.ceylon.compiler.java.codegen.Naming.SyntheticName) Class(com.redhat.ceylon.model.typechecker.model.Class) JCNewClass(com.sun.tools.javac.tree.JCTree.JCNewClass)

Aggregations

Class (com.redhat.ceylon.model.typechecker.model.Class)81 TypeDeclaration (com.redhat.ceylon.model.typechecker.model.TypeDeclaration)52 Type (com.redhat.ceylon.model.typechecker.model.Type)45 JCNewClass (com.sun.tools.javac.tree.JCTree.JCNewClass)37 Declaration (com.redhat.ceylon.model.typechecker.model.Declaration)28 TypedDeclaration (com.redhat.ceylon.model.typechecker.model.TypedDeclaration)26 Function (com.redhat.ceylon.model.typechecker.model.Function)23 IntersectionType (com.redhat.ceylon.model.typechecker.model.IntersectionType)22 UnionType (com.redhat.ceylon.model.typechecker.model.UnionType)22 JCExpression (com.sun.tools.javac.tree.JCTree.JCExpression)22 TypeParser (com.redhat.ceylon.model.loader.TypeParser)21 Test (org.junit.Test)21 ClassOrInterface (com.redhat.ceylon.model.typechecker.model.ClassOrInterface)20 Tree (com.redhat.ceylon.compiler.typechecker.tree.Tree)19 TypeParameter (com.redhat.ceylon.model.typechecker.model.TypeParameter)19 Value (com.redhat.ceylon.model.typechecker.model.Value)19 JCTree (com.sun.tools.javac.tree.JCTree)19 FunctionOrValue (com.redhat.ceylon.model.typechecker.model.FunctionOrValue)17 Interface (com.redhat.ceylon.model.typechecker.model.Interface)17 Parameter (com.redhat.ceylon.model.typechecker.model.Parameter)14