Ejemplo n.º 1
0
 @NotNull
 public static SimpleFunctionDescriptor createEnumValueOfMethod(
     @NotNull ClassDescriptor enumClass) {
   SimpleFunctionDescriptorImpl valueOf =
       SimpleFunctionDescriptorImpl.create(
           enumClass,
           Annotations.Companion.getEMPTY(),
           DescriptorUtils.ENUM_VALUE_OF,
           CallableMemberDescriptor.Kind.SYNTHESIZED,
           enumClass.getSource());
   ValueParameterDescriptor parameterDescriptor =
       new ValueParameterDescriptorImpl(
           valueOf,
           null,
           0,
           Annotations.Companion.getEMPTY(),
           Name.identifier("value"),
           getBuiltIns(enumClass).getStringType(),
           /* declaresDefaultValue = */ false,
           /* isCrossinline = */ false,
           /* isNoinline = */ false,
           null,
           enumClass.getSource());
   return valueOf.initialize(
       null,
       null,
       Collections.<TypeParameterDescriptor>emptyList(),
       Collections.singletonList(parameterDescriptor),
       enumClass.getDefaultType(),
       Modality.FINAL,
       Visibilities.PUBLIC);
 }
 private static List<ClassDescriptor> getSupertypes(ClassDescriptor classDescriptor) {
   List<JetType> supertypes =
       Lists.newArrayList(TypeUtils.getAllSupertypes(classDescriptor.getDefaultType()));
   Collections.sort(
       supertypes,
       new Comparator<JetType>() {
         @Override
         public int compare(JetType o1, JetType o2) {
           if (o1.equals(o2)) {
             return 0;
           }
           if (JetTypeChecker.DEFAULT.isSubtypeOf(o1, o2)) {
             return -1;
           }
           if (JetTypeChecker.DEFAULT.isSubtypeOf(o2, o1)) {
             return 1;
           }
           return o1.toString().compareTo(o2.toString());
         }
       });
   List<ClassDescriptor> supertypesDescriptors = Lists.newArrayList();
   for (JetType supertype : supertypes) {
     supertypesDescriptors.add(DescriptorUtils.getClassDescriptorForType(supertype));
   }
   return supertypesDescriptors;
 }
Ejemplo n.º 3
0
  @NotNull
  public static PropertyDescriptor createEnumValuesProperty(@NotNull ClassDescriptor enumClass) {
    PropertyDescriptorImpl values =
        PropertyDescriptorImpl.create(
            enumClass,
            Annotations.Companion.getEMPTY(),
            Modality.FINAL,
            Visibilities.PUBLIC, /* isVar */
            false,
            DescriptorUtils.ENUM_VALUES,
            CallableMemberDescriptor.Kind.SYNTHESIZED,
            enumClass.getSource(),
            /* lateInit = */ false,
            /* isConst = */ false);

    KotlinType type =
        getBuiltIns(enumClass).getArrayType(Variance.INVARIANT, enumClass.getDefaultType());

    PropertyGetterDescriptorImpl getter =
        createDefaultGetter(values, Annotations.Companion.getEMPTY());

    values.initialize(getter, null);
    getter.initialize(type);
    values.setType(type, Collections.<TypeParameterDescriptor>emptyList(), null, (KotlinType) null);

    return values;
  }
Ejemplo n.º 4
0
  @Override
  protected void generateBody() {
    List<KtObjectDeclaration> companions = new ArrayList<KtObjectDeclaration>();
    if (kind != OwnerKind.DEFAULT_IMPLS) {
      // generate nested classes first and only then generate class body. It necessary to access to
      // nested CodegenContexts
      for (KtDeclaration declaration : myClass.getDeclarations()) {
        if (shouldProcessFirst(declaration)) {
          // Generate companions after class body generation (need to record all synthetic
          // accessors)
          if (declaration instanceof KtObjectDeclaration
              && ((KtObjectDeclaration) declaration).isCompanion()) {
            companions.add((KtObjectDeclaration) declaration);
            CodegenUtilKt.populateCompanionBackingFieldNamesToOuterContextIfNeeded(
                (KtObjectDeclaration) declaration, context, state);
          } else {
            generateDeclaration(declaration);
          }
        }
      }
    }

    for (KtDeclaration declaration : myClass.getDeclarations()) {
      if (!shouldProcessFirst(declaration)) {
        generateDeclaration(declaration);
      }
    }

    generatePrimaryConstructorProperties();
    generateConstructors();
    generateDefaultImplsIfNeeded();

    for (KtObjectDeclaration companion : companions) {
      generateDeclaration(companion);
    }

    if (!DescriptorUtils.isInterface(descriptor)) {
      for (DeclarationDescriptor memberDescriptor :
          DescriptorUtils.getAllDescriptors(descriptor.getDefaultType().getMemberScope())) {
        if (memberDescriptor instanceof CallableMemberDescriptor) {
          CallableMemberDescriptor member = (CallableMemberDescriptor) memberDescriptor;
          if (!member.getKind().isReal() && ImplKt.findInterfaceImplementation(member) == null) {
            if (member instanceof FunctionDescriptor) {
              functionCodegen.generateBridges((FunctionDescriptor) member);
            } else if (member instanceof PropertyDescriptor) {
              PropertyGetterDescriptor getter = ((PropertyDescriptor) member).getGetter();
              if (getter != null) {
                functionCodegen.generateBridges(getter);
              }
              PropertySetterDescriptor setter = ((PropertyDescriptor) member).getSetter();
              if (setter != null) {
                functionCodegen.generateBridges(setter);
              }
            }
          }
        }
      }
    }
  }
Ejemplo n.º 5
0
  private static void addResultsForClass(
      @NotNull @Mutable Set<LookupResult> results,
      @NotNull JetSimpleNameExpression selector,
      @NotNull LookupMode lookupMode,
      @NotNull ClassDescriptor descriptor) {
    JetScope scope =
        lookupMode == LookupMode.ONLY_CLASSES_AND_PACKAGES
            ? descriptor.getUnsubstitutedInnerClassesScope()
            : descriptor.getDefaultType().getMemberScope();
    results.add(lookupSimpleNameReference(selector, scope, lookupMode, false));

    results.add(lookupSimpleNameReference(selector, descriptor.getStaticScope(), lookupMode, true));
  }
Ejemplo n.º 6
0
 @NotNull
 public static FunctionDescriptor getErasedInvokeFunction(
     @NotNull FunctionDescriptor elementDescriptor) {
   int arity = elementDescriptor.getValueParameters().size();
   ClassDescriptor elementClass =
       elementDescriptor.getExtensionReceiverParameter() == null
           ? getBuiltIns(elementDescriptor).getFunction(arity)
           : getBuiltIns(elementDescriptor).getExtensionFunction(arity);
   return elementClass
       .getDefaultType()
       .getMemberScope()
       .getFunctions(OperatorConventions.INVOKE)
       .iterator()
       .next();
 }
Ejemplo n.º 7
0
  @NotNull
  public Collection<KotlinType> getSupertypesForClosure(@NotNull FunctionDescriptor descriptor) {
    ReceiverParameterDescriptor receiverParameter = descriptor.getExtensionReceiverParameter();

    //noinspection ConstantConditions
    KotlinType functionType =
        DescriptorUtilsKt.getBuiltIns(descriptor)
            .getFunctionType(
                Annotations.Companion.getEMPTY(),
                receiverParameter == null ? null : receiverParameter.getType(),
                ExpressionTypingUtils.getValueParametersTypes(descriptor.getValueParameters()),
                descriptor.getReturnType());

    return Arrays.asList(lambda.getDefaultType(), functionType);
  }
  private static List<FunctionDescriptor> generateFunctionsToAdd(JetNamedFunction functionElement) {
    FunctionDescriptor functionDescriptor =
        (FunctionDescriptor) ResolvePackage.resolveToDescriptor(functionElement);

    DeclarationDescriptor containingDeclaration = functionDescriptor.getContainingDeclaration();
    if (!(containingDeclaration instanceof ClassDescriptor)) return Collections.emptyList();

    List<FunctionDescriptor> functions = Lists.newArrayList();
    ClassDescriptor classDescriptor = (ClassDescriptor) containingDeclaration;
    // TODO: filter out impossible supertypes (for example when argument's type isn't visible in a
    // superclass).
    for (ClassDescriptor supertypeDescriptor : getSupertypes(classDescriptor)) {
      if (KotlinBuiltIns.isAnyOrNullableAny(supertypeDescriptor.getDefaultType())) continue;
      functions.add(generateFunctionSignatureForType(functionDescriptor, supertypeDescriptor));
    }
    return functions;
  }
Ejemplo n.º 9
0
  private void checkSupertypesForConsistency(@NotNull ClassDescriptor classDescriptor) {
    Multimap<TypeConstructor, TypeProjection> multimap =
        SubstitutionUtils.buildDeepSubstitutionMultimap(classDescriptor.getDefaultType());
    for (Map.Entry<TypeConstructor, Collection<TypeProjection>> entry :
        multimap.asMap().entrySet()) {
      Collection<TypeProjection> projections = entry.getValue();
      if (projections.size() > 1) {
        TypeConstructor typeConstructor = entry.getKey();
        DeclarationDescriptor declarationDescriptor = typeConstructor.getDeclarationDescriptor();
        assert declarationDescriptor instanceof TypeParameterDescriptor : declarationDescriptor;
        TypeParameterDescriptor typeParameterDescriptor =
            (TypeParameterDescriptor) declarationDescriptor;

        // Immediate arguments of supertypes cannot be projected
        Set<JetType> conflictingTypes = Sets.newLinkedHashSet();
        for (TypeProjection projection : projections) {
          conflictingTypes.add(projection.getType());
        }
        removeDuplicateTypes(conflictingTypes);
        if (conflictingTypes.size() > 1) {
          DeclarationDescriptor containingDeclaration =
              typeParameterDescriptor.getContainingDeclaration();
          assert containingDeclaration instanceof ClassDescriptor : containingDeclaration;
          JetClassOrObject psiElement =
              (JetClassOrObject) DescriptorToSourceUtils.getSourceFromDescriptor(classDescriptor);
          assert psiElement != null;
          JetDelegationSpecifierList delegationSpecifierList =
              psiElement.getDelegationSpecifierList();
          assert delegationSpecifierList != null;
          //
          // trace.getErrorHandler().genericError(delegationSpecifierList.getNode(), "Type parameter
          // " + typeParameterDescriptor.getName() + " of " + containingDeclaration.getName() + "
          // has inconsistent values: " + conflictingTypes);
          trace.report(
              INCONSISTENT_TYPE_PARAMETER_VALUES.on(
                  delegationSpecifierList,
                  typeParameterDescriptor,
                  (ClassDescriptor) containingDeclaration,
                  conflictingTypes));
        }
      }
    }
  }
Ejemplo n.º 10
0
 // TODO: should be internal
 @Nullable
 public static ClassDescriptor getInnerClassByName(
     @NotNull ClassDescriptor classDescriptor,
     @NotNull String innerClassName,
     @NotNull LookupLocation location) {
   ClassifierDescriptor classifier =
       classDescriptor
           .getDefaultType()
           .getMemberScope()
           .getContributedClassifier(Name.identifier(innerClassName), location);
   assert classifier instanceof ClassDescriptor
       : "Inner class "
           + innerClassName
           + " in "
           + classDescriptor
           + " should be instance of ClassDescriptor, but was: "
           + (classifier == null ? "null" : classifier.getClass());
   return (ClassDescriptor) classifier;
 }
Ejemplo n.º 11
0
 @NotNull
 public static SimpleFunctionDescriptor createEnumValuesMethod(
     @NotNull ClassDescriptor enumClass) {
   SimpleFunctionDescriptorImpl values =
       SimpleFunctionDescriptorImpl.create(
           enumClass,
           Annotations.Companion.getEMPTY(),
           DescriptorUtils.ENUM_VALUES,
           CallableMemberDescriptor.Kind.SYNTHESIZED,
           enumClass.getSource());
   return values.initialize(
       null,
       null,
       Collections.<TypeParameterDescriptor>emptyList(),
       Collections.<ValueParameterDescriptor>emptyList(),
       getBuiltIns(enumClass).getArrayType(Variance.INVARIANT, enumClass.getDefaultType()),
       Modality.FINAL,
       Visibilities.PUBLIC);
 }
Ejemplo n.º 12
0
  private void checkEnumEntry(
      @NotNull JetEnumEntry enumEntry, @NotNull ClassDescriptor classDescriptor) {
    DeclarationDescriptor declaration = classDescriptor.getContainingDeclaration();
    assert DescriptorUtils.isEnumClass(declaration)
        : "Enum entry should be declared in enum class: " + classDescriptor;
    ClassDescriptor enumClass = (ClassDescriptor) declaration;

    if (enumEntryUsesDeprecatedSuperConstructor(enumEntry)) {
      trace.report(
          Errors.ENUM_ENTRY_USES_DEPRECATED_SUPER_CONSTRUCTOR.on(enumEntry, classDescriptor));
    }
    String neededDelimiter = enumEntryExpectedDelimiter(enumEntry);
    if (!neededDelimiter.isEmpty()) {
      trace.report(
          Errors.ENUM_ENTRY_USES_DEPRECATED_OR_NO_DELIMITER.on(
              enumEntry, classDescriptor, neededDelimiter));
    }
    if (enumEntryAfterEnumMember(enumEntry)) {
      trace.report(Errors.ENUM_ENTRY_AFTER_ENUM_MEMBER.on(enumEntry, classDescriptor));
    }

    List<JetDelegationSpecifier> delegationSpecifiers = enumEntry.getDelegationSpecifiers();
    ConstructorDescriptor constructor = enumClass.getUnsubstitutedPrimaryConstructor();
    if ((constructor == null || !constructor.getValueParameters().isEmpty())
        && delegationSpecifiers.isEmpty()) {
      trace.report(ENUM_ENTRY_SHOULD_BE_INITIALIZED.on(enumEntry, enumClass));
    }

    for (JetDelegationSpecifier delegationSpecifier : delegationSpecifiers) {
      JetTypeReference typeReference = delegationSpecifier.getTypeReference();
      if (typeReference != null) {
        JetType type = trace.getBindingContext().get(TYPE, typeReference);
        if (type != null) {
          JetType enumType = enumClass.getDefaultType();
          if (!type.getConstructor().equals(enumType.getConstructor())) {
            trace.report(ENUM_ENTRY_ILLEGAL_TYPE.on(typeReference, enumClass));
          }
        }
      }
    }
  }
Ejemplo n.º 13
0
  @NotNull
  public static KotlinType substituteProjectionsForParameters(
      @NotNull ClassDescriptor clazz, @NotNull List<TypeProjection> projections) {
    List<TypeParameterDescriptor> clazzTypeParameters = clazz.getTypeConstructor().getParameters();
    if (clazzTypeParameters.size() != projections.size()) {
      throw new IllegalArgumentException(
          "type parameter counts do not match: " + clazz + ", " + projections);
    }

    Map<TypeConstructor, TypeProjection> substitutions =
        org.jetbrains.kotlin.utils.CollectionsKt.newHashMapWithExpectedSize(
            clazzTypeParameters.size());

    for (int i = 0; i < clazzTypeParameters.size(); ++i) {
      TypeConstructor typeConstructor = clazzTypeParameters.get(i).getTypeConstructor();
      substitutions.put(typeConstructor, projections.get(i));
    }

    return TypeSubstitutor.create(substitutions)
        .substitute(clazz.getDefaultType(), Variance.INVARIANT);
  }
Ejemplo n.º 14
0
  @NotNull
  public Collection<KotlinType> getSupertypesForFunctionReference(
      @NotNull FunctionDescriptor descriptor) {
    ReceiverParameterDescriptor extensionReceiver = descriptor.getExtensionReceiverParameter();
    ReceiverParameterDescriptor dispatchReceiver = descriptor.getDispatchReceiverParameter();

    KotlinType receiverType =
        extensionReceiver != null
            ? extensionReceiver.getType()
            : dispatchReceiver != null ? dispatchReceiver.getType() : null;

    //noinspection ConstantConditions
    KotlinType functionType =
        DescriptorUtilsKt.getBuiltIns(descriptor)
            .getFunctionType(
                Annotations.Companion.getEMPTY(),
                receiverType,
                ExpressionTypingUtils.getValueParametersTypes(descriptor.getValueParameters()),
                descriptor.getReturnType());

    return Arrays.asList(functionReference.getDefaultType(), functionType);
  }
Ejemplo n.º 15
0
  @NotNull
  public static SimpleFunctionDescriptor createEnumValuesMethod(
      @NotNull ClassDescriptor enumClass) {
    AnnotationsImpl annotations =
        AnnotationsImpl.createWithNoTarget(
            AnnotationUtilKt.createDeprecatedAnnotation(
                getBuiltIns(enumClass), "Use 'values' property instead", "this.values"));

    SimpleFunctionDescriptorImpl values =
        SimpleFunctionDescriptorImpl.create(
            enumClass,
            annotations,
            DescriptorUtils.ENUM_VALUES,
            CallableMemberDescriptor.Kind.SYNTHESIZED,
            enumClass.getSource());
    return values.initialize(
        null,
        null,
        Collections.<TypeParameterDescriptor>emptyList(),
        Collections.<ValueParameterDescriptor>emptyList(),
        getBuiltIns(enumClass).getArrayType(Variance.INVARIANT, enumClass.getDefaultType()),
        Modality.FINAL,
        Visibilities.PUBLIC);
  }
Ejemplo n.º 16
0
 public static boolean isSubclass(
     @NotNull ClassDescriptor subClass, @NotNull ClassDescriptor superClass) {
   return isSubtypeOfClass(subClass.getDefaultType(), superClass.getOriginal());
 }