예제 #1
0
 @Override
 public boolean isVisible(
     @NotNull ReceiverValue receiver,
     @NotNull DeclarationDescriptorWithVisibility what,
     @NotNull DeclarationDescriptor from) {
   DeclarationDescriptor parent = what;
   while (parent != null) {
     parent = parent.getContainingDeclaration();
     if ((parent instanceof ClassDescriptor && !DescriptorUtils.isCompanionObject(parent))
         || parent instanceof PackageFragmentDescriptor) {
       break;
     }
   }
   if (parent == null) {
     return false;
   }
   DeclarationDescriptor fromParent = from;
   while (fromParent != null) {
     if (parent == fromParent) {
       return true;
     }
     if (fromParent instanceof PackageFragmentDescriptor) {
       return parent instanceof PackageFragmentDescriptor
           && ((PackageFragmentDescriptor) parent)
               .getFqName()
               .equals(((PackageFragmentDescriptor) fromParent).getFqName())
           && DescriptorUtils.areInSameModule(fromParent, parent);
     }
     fromParent = fromParent.getContainingDeclaration();
   }
   return false;
 }
예제 #2
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);
              }
            }
          }
        }
      }
    }
  }
예제 #3
0
  public static CodegenContext getContext(DeclarationDescriptor descriptor, GenerationState state) {
    if (descriptor instanceof PackageFragmentDescriptor) {
      return new PackageContext(
          (PackageFragmentDescriptor) descriptor, state.getRootContext(), null);
    }

    CodegenContext parent = getContext(descriptor.getContainingDeclaration(), state);

    if (descriptor instanceof ClassDescriptor) {
      OwnerKind kind =
          DescriptorUtils.isInterface(descriptor)
              ? OwnerKind.DEFAULT_IMPLS
              : OwnerKind.IMPLEMENTATION;
      return parent.intoClass((ClassDescriptor) descriptor, kind, state);
    } else if (descriptor instanceof ScriptDescriptor) {
      ClassDescriptor classDescriptorForScript =
          state.getBindingContext().get(CLASS_FOR_SCRIPT, (ScriptDescriptor) descriptor);
      assert classDescriptorForScript != null : "Can't find class for script: " + descriptor;
      List<ScriptDescriptor> earlierScripts = state.getEarlierScriptsForReplInterpreter();
      return parent.intoScript(
          (ScriptDescriptor) descriptor,
          earlierScripts == null ? Collections.emptyList() : earlierScripts,
          classDescriptorForScript);
    } else if (descriptor instanceof FunctionDescriptor) {
      return parent.intoFunction((FunctionDescriptor) descriptor);
    }

    throw new IllegalStateException("Couldn't build context for " + descriptorName(descriptor));
  }
예제 #4
0
 @NotNull
 public ClassDescriptor getMutableMapEntry() {
   ClassDescriptor classDescriptor =
       DescriptorUtils.getInnerClassByName(getMutableMap(), "MutableEntry");
   assert classDescriptor != null : "Can't find MutableMap.MutableEntry";
   return classDescriptor;
 }
예제 #5
0
  // Note: headers of member classes' members are not resolved
  public void resolveMemberHeaders() {
    ForceResolveUtil.forceResolveAllContents(getAnnotations());
    ForceResolveUtil.forceResolveAllContents(getDanglingAnnotations());

    getCompanionObjectDescriptor();

    getDescriptorsForExtraCompanionObjects();

    getConstructors();
    getContainingDeclaration();
    getThisAsReceiverParameter();
    getKind();
    getModality();
    getName();
    getOriginal();
    getScopeForClassHeaderResolution();
    getScopeForMemberDeclarationResolution();
    DescriptorUtils.getAllDescriptors(getUnsubstitutedMemberScope());
    getScopeForInitializerResolution();
    getUnsubstitutedInnerClassesScope();
    getTypeConstructor().getSupertypes();
    for (TypeParameterDescriptor typeParameterDescriptor : getTypeConstructor().getParameters()) {
      typeParameterDescriptor.getUpperBounds();
    }
    getUnsubstitutedPrimaryConstructor();
    getVisibility();
  }
 private static boolean isFromBuiltinModule(@NotNull DeclarationDescriptor originalDescriptor) {
   // TODO This is optimization only
   // It should be rewritten by checking declarationDescriptor.getSource(), when the latter returns
   // something non-trivial for builtins.
   return KotlinBuiltIns.getInstance().getBuiltInsModule()
       == DescriptorUtils.getContainingModule(originalDescriptor);
 }
  public boolean isMain(@NotNull JetNamedFunction function) {
    if (!"main".equals(function.getName())) return false;

    FunctionDescriptor functionDescriptor = getFunctionDescriptor.fun(function);
    List<ValueParameterDescriptor> parameters = functionDescriptor.getValueParameters();
    if (parameters.size() != 1) return false;

    ValueParameterDescriptor parameter = parameters.get(0);
    JetType parameterType = parameter.getType();
    if (!KotlinBuiltIns.isArray(parameterType)) return false;

    List<TypeProjection> typeArguments = parameterType.getArguments();
    if (typeArguments.size() != 1) return false;

    JetType typeArgument = typeArguments.get(0).getType();
    if (!JetTypeChecker.DEFAULT.equalTypes(
        typeArgument, getBuiltIns(functionDescriptor).getStringType())) return false;

    if (DescriptorUtils.isTopLevelDeclaration(functionDescriptor)) return true;

    DeclarationDescriptor containingDeclaration = functionDescriptor.getContainingDeclaration();
    return containingDeclaration instanceof ClassDescriptor
        && ((ClassDescriptor) containingDeclaration).getKind().isSingleton()
        && AnnotationsPackage.hasPlatformStaticAnnotation(functionDescriptor);
  }
예제 #8
0
 @NotNull
 public ClassDescriptor getMapEntry() {
   ClassDescriptor classDescriptor =
       DescriptorUtils.getInnerClassByName(getMap(), "Entry", NoLookupLocation.FROM_BUILTINS);
   assert classDescriptor != null : "Can't find Map.Entry";
   return classDescriptor;
 }
 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;
 }
예제 #10
0
  /**
   * This method tries to resolve descriptors ambiguity between class descriptor and package
   * descriptor for the same class. It's ok choose class for expression reference resolution.
   *
   * @return <code>true</code> if method has successfully resolved ambiguity
   */
  private static boolean resolveClassPackageAmbiguity(
      @NotNull Collection<DeclarationDescriptor> filteredDescriptors,
      @NotNull JetSimpleNameExpression referenceExpression,
      @NotNull JetScope resolutionScope,
      @NotNull BindingTrace trace,
      @NotNull JetScope scopeToCheckVisibility) {
    if (filteredDescriptors.size() == 2) {
      PackageViewDescriptor packageView = null;
      ClassDescriptor classDescriptor = null;

      for (DeclarationDescriptor filteredDescriptor : filteredDescriptors) {
        if (filteredDescriptor instanceof PackageViewDescriptor) {
          packageView = (PackageViewDescriptor) filteredDescriptor;
        } else if (filteredDescriptor instanceof ClassDescriptor) {
          classDescriptor = (ClassDescriptor) filteredDescriptor;
        }
      }

      if (packageView != null && classDescriptor != null) {
        if (packageView.getFqName().equalsTo(DescriptorUtils.getFqName(classDescriptor))) {
          trace.record(BindingContext.REFERENCE_TARGET, referenceExpression, classDescriptor);
          trace.record(BindingContext.RESOLUTION_SCOPE, referenceExpression, resolutionScope);
          checkVisibility(classDescriptor, trace, referenceExpression, scopeToCheckVisibility);
          return true;
        }
      }
    }

    return false;
  }
  private static Collection<DeclarationDescriptor> getAllStandardDescriptors() {
    final List<DeclarationDescriptor> descriptors = new ArrayList<DeclarationDescriptor>();

    PackageFragmentDescriptor builtinsPackageFragment =
        DefaultBuiltIns.getInstance().getBuiltInsPackageFragment();

    for (DeclarationDescriptor packageMember :
        DescriptorUtils.getAllDescriptors(builtinsPackageFragment.getMemberScope())) {
      packageMember.acceptVoid(
          new DeclarationDescriptorVisitorEmptyBodies<Void, Void>() {
            @Override
            public Void visitClassDescriptor(ClassDescriptor descriptor, Void data) {
              descriptors.add(descriptor);
              for (DeclarationDescriptor classMember :
                  DescriptorUtils.getAllDescriptors(descriptor.getDefaultType().getMemberScope())) {
                classMember.acceptVoid(this);
              }
              return null;
            }

            @Override
            public Void visitDeclarationDescriptor(DeclarationDescriptor descriptor, Void data) {
              descriptors.add(descriptor);
              return null;
            }
          });
    }

    return descriptors;
  }
예제 #12
0
  private static boolean isTypeConstructorFqNameInSet(
      @NotNull JetType type, @NotNull Set<FqNameUnsafe> classes) {
    ClassifierDescriptor declarationDescriptor = type.getConstructor().getDeclarationDescriptor();

    if (declarationDescriptor == null) return false;

    FqNameUnsafe fqName = DescriptorUtils.getFqName(declarationDescriptor);
    return classes.contains(fqName);
  }
예제 #13
0
 private static Collection<DeclarationDescriptor> getAllVariables(LexicalScope scope) {
   Collection<DeclarationDescriptor> result = ContainerUtil.newArrayList();
   result.addAll(
       ScopeUtilsKt.collectDescriptorsFiltered(
           scope, DescriptorKindFilter.VARIABLES, MemberScope.Companion.getALL_NAME_FILTER()));
   for (ReceiverParameterDescriptor implicitReceiver :
       ScopeUtilsKt.getImplicitReceiversHierarchy(scope)) {
     result.addAll(DescriptorUtils.getAllDescriptors(implicitReceiver.getType().getMemberScope()));
   }
   return result;
 }
예제 #14
0
  private boolean isDefinedInInlineFunction(
      @NotNull DeclarationDescriptorWithVisibility startDescriptor) {
    DeclarationDescriptorWithVisibility parent = startDescriptor;

    while (parent != null) {
      if (parent.getContainingDeclaration() == descriptor) return true;

      parent = DescriptorUtils.getParentOfType(parent, DeclarationDescriptorWithVisibility.class);
    }

    return false;
  }
예제 #15
0
  @NotNull
  public static Pair<FunctionDescriptor, PsiElement> getContainingFunctionSkipFunctionLiterals(
      @Nullable DeclarationDescriptor startDescriptor, boolean strict) {
    FunctionDescriptor containingFunctionDescriptor =
        DescriptorUtils.getParentOfType(startDescriptor, FunctionDescriptor.class, strict);
    PsiElement containingFunction =
        containingFunctionDescriptor != null
            ? DescriptorToSourceUtils.getSourceFromDescriptor(containingFunctionDescriptor)
            : null;
    while (containingFunction instanceof JetFunctionLiteral) {
      containingFunctionDescriptor =
          DescriptorUtils.getParentOfType(containingFunctionDescriptor, FunctionDescriptor.class);
      containingFunction =
          containingFunctionDescriptor != null
              ? DescriptorToSourceUtils.getSourceFromDescriptor(containingFunctionDescriptor)
              : null;
    }

    return new Pair<FunctionDescriptor, PsiElement>(
        containingFunctionDescriptor, containingFunction);
  }
예제 #16
0
  @NotNull
  private static InnerModifierCheckResult checkIllegalInner(
      @NotNull DeclarationDescriptor descriptor) {
    if (!(descriptor instanceof ClassDescriptor)) return InnerModifierCheckResult.ILLEGAL_POSITION;
    ClassDescriptor classDescriptor = (ClassDescriptor) descriptor;

    if (classDescriptor.getKind() != ClassKind.CLASS)
      return InnerModifierCheckResult.ILLEGAL_POSITION;

    DeclarationDescriptor containingDeclaration = classDescriptor.getContainingDeclaration();
    if (!(containingDeclaration instanceof ClassDescriptor))
      return InnerModifierCheckResult.ILLEGAL_POSITION;

    if (DescriptorUtils.isTrait(containingDeclaration)) {
      return InnerModifierCheckResult.IN_TRAIT;
    } else if (DescriptorUtils.isObject(containingDeclaration)) {
      return InnerModifierCheckResult.IN_OBJECT;
    } else {
      return InnerModifierCheckResult.ALLOWED;
    }
  }
예제 #17
0
        @Override
        public boolean isVisible(
            @NotNull ReceiverValue receiver,
            @NotNull DeclarationDescriptorWithVisibility what,
            @NotNull DeclarationDescriptor from) {
          ClassDescriptor classDescriptor =
              DescriptorUtils.getParentOfType(what, ClassDescriptor.class);
          if (DescriptorUtils.isCompanionObject(classDescriptor)) {
            classDescriptor =
                DescriptorUtils.getParentOfType(classDescriptor, ClassDescriptor.class);
          }
          if (classDescriptor == null) return false;

          ClassDescriptor fromClass =
              DescriptorUtils.getParentOfType(from, ClassDescriptor.class, false);
          if (fromClass == null) return false;
          if (DescriptorUtils.isSubclass(fromClass, classDescriptor)) {
            return true;
          }
          return isVisible(receiver, what, fromClass.getContainingDeclaration());
        }
예제 #18
0
 @Nullable
 public static DeclarationDescriptorWithVisibility findInvisibleMember(
     @NotNull ReceiverValue receiver,
     @NotNull DeclarationDescriptorWithVisibility what,
     @NotNull DeclarationDescriptor from) {
   DeclarationDescriptorWithVisibility parent = what;
   while (parent != null && parent.getVisibility() != LOCAL) {
     if (!parent.getVisibility().isVisible(receiver, parent, from)) {
       return parent;
     }
     parent = DescriptorUtils.getParentOfType(parent, DeclarationDescriptorWithVisibility.class);
   }
   return null;
 }
예제 #19
0
 @NotNull
 @Override
 public Collection<CallableMemberDescriptor> getDeclaredCallableMembers() {
   //noinspection unchecked
   return (Collection)
       CollectionsKt.filter(
           DescriptorUtils.getAllDescriptors(unsubstitutedMemberScope),
           new Function1<DeclarationDescriptor, Boolean>() {
             @Override
             public Boolean invoke(DeclarationDescriptor descriptor) {
               return descriptor instanceof CallableMemberDescriptor
                   && ((CallableMemberDescriptor) descriptor).getKind()
                       != CallableMemberDescriptor.Kind.FAKE_OVERRIDE;
             }
           });
 }
예제 #20
0
        @Override
        public boolean isVisible(
            @NotNull ReceiverValue thisObject,
            @NotNull DeclarationDescriptorWithVisibility what,
            @NotNull DeclarationDescriptor from) {
          if (PRIVATE.isVisible(thisObject, what, from)) {
            DeclarationDescriptor classDescriptor =
                DescriptorUtils.getParentOfType(what, ClassDescriptor.class);

            if (classDescriptor != null && thisObject instanceof ClassReceiver) {
              return ((ClassReceiver) thisObject).getDeclarationDescriptor().getOriginal()
                  == classDescriptor.getOriginal();
            }
          }
          return false;
        }
예제 #21
0
  public ClosureCodegen(
      @NotNull GenerationState state,
      @NotNull JetElement element,
      @Nullable SamType samType,
      @NotNull ClosureContext context,
      @NotNull KotlinSyntheticClass.Kind syntheticClassKind,
      @NotNull FunctionGenerationStrategy strategy,
      @NotNull MemberCodegen<?> parentCodegen,
      @NotNull ClassBuilder classBuilder) {
    super(state, parentCodegen, context, element, classBuilder);

    this.funDescriptor = context.getFunctionDescriptor();
    this.classDescriptor = context.getContextDescriptor();
    this.samType = samType;
    this.syntheticClassKind = syntheticClassKind;
    this.strategy = strategy;

    if (samType == null) {
      this.superInterfaceTypes = new ArrayList<JetType>();

      JetType superClassType = null;
      for (JetType supertype : classDescriptor.getTypeConstructor().getSupertypes()) {
        ClassifierDescriptor classifier = supertype.getConstructor().getDeclarationDescriptor();
        if (DescriptorUtils.isTrait(classifier)) {
          superInterfaceTypes.add(supertype);
        } else {
          assert superClassType == null
              : "Closure class can't have more than one superclass: " + funDescriptor;
          superClassType = supertype;
        }
      }
      assert superClassType != null : "Closure class should have a superclass: " + funDescriptor;

      this.superClassType = superClassType;
    } else {
      this.superInterfaceTypes = Collections.singletonList(samType.getType());
      this.superClassType = getBuiltIns(funDescriptor).getAnyType();
    }

    this.closure = bindingContext.get(CLOSURE, classDescriptor);
    assert closure != null : "Closure must be calculated for class: " + classDescriptor;

    this.asmType = typeMapper.mapClass(classDescriptor);

    visibilityFlag = AsmUtil.getVisibilityAccessFlagForAnonymous(classDescriptor);
  }
예제 #22
0
  private void generateBridge(@NotNull Method bridge, @NotNull Method delegate) {
    if (bridge.equals(delegate)) return;

    MethodVisitor mv =
        v.newMethod(
            OtherOrigin(element, funDescriptor),
            ACC_PUBLIC | ACC_BRIDGE,
            bridge.getName(),
            bridge.getDescriptor(),
            null,
            ArrayUtil.EMPTY_STRING_ARRAY);

    if (state.getClassBuilderMode() != ClassBuilderMode.FULL) return;

    mv.visitCode();

    InstructionAdapter iv = new InstructionAdapter(mv);
    ImplementationBodyCodegen.markLineNumberForSyntheticFunction(
        DescriptorUtils.getParentOfType(funDescriptor, ClassDescriptor.class), iv);

    iv.load(0, asmType);

    ReceiverParameterDescriptor receiver = funDescriptor.getExtensionReceiverParameter();
    int count = 1;
    if (receiver != null) {
      StackValue.local(count, bridge.getArgumentTypes()[count - 1])
          .put(typeMapper.mapType(receiver.getType()), iv);
      count++;
    }

    List<ValueParameterDescriptor> params = funDescriptor.getValueParameters();
    for (ValueParameterDescriptor param : params) {
      StackValue.local(count, bridge.getArgumentTypes()[count - 1])
          .put(typeMapper.mapType(param.getType()), iv);
      count++;
    }

    iv.invokevirtual(
        asmType.getInternalName(), delegate.getName(), delegate.getDescriptor(), false);
    StackValue.onStack(delegate.getReturnType()).put(bridge.getReturnType(), iv);

    iv.areturn(bridge.getReturnType());

    FunctionCodegen.endVisit(mv, "bridge", element);
  }
 // TODO: navigate to inner classes
 @Nullable
 private static ClassId getContainerClassId(@NotNull DeclarationDescriptor referencedDescriptor) {
   ClassOrPackageFragmentDescriptor containerDescriptor =
       DescriptorUtils.getParentOfType(
           referencedDescriptor, ClassOrPackageFragmentDescriptor.class, false);
   if (containerDescriptor instanceof PackageFragmentDescriptor) {
     return getPackageClassId(((PackageFragmentDescriptor) containerDescriptor).getFqName());
   }
   if (containerDescriptor instanceof ClassDescriptor) {
     if (containerDescriptor.getContainingDeclaration() instanceof ClassDescriptor
         || ExpressionTypingUtils.isLocal(
             containerDescriptor.getContainingDeclaration(), containerDescriptor)) {
       return getContainerClassId(containerDescriptor.getContainingDeclaration());
     }
     return getClassId((ClassDescriptor) containerDescriptor);
   }
   return null;
 }
예제 #24
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));
          }
        }
      }
    }
  }
예제 #25
0
 @Nullable
 private LazyClassDescriptor computeCompanionObjectDescriptor(
     @Nullable KtObjectDeclaration companionObject) {
   KtClassLikeInfo companionObjectInfo = getCompanionObjectInfo(companionObject);
   if (!(companionObjectInfo instanceof KtClassOrObjectInfo)) {
     return null;
   }
   Name name = ((KtClassOrObjectInfo) companionObjectInfo).getName();
   assert name != null;
   getUnsubstitutedMemberScope()
       .getContributedClassifier(name, NoLookupLocation.WHEN_GET_COMPANION_OBJECT);
   ClassDescriptor companionObjectDescriptor =
       c.getTrace().get(BindingContext.CLASS, companionObject);
   if (companionObjectDescriptor instanceof LazyClassDescriptor) {
     assert DescriptorUtils.isCompanionObject(companionObjectDescriptor)
         : "Not a companion object: " + companionObjectDescriptor;
     return (LazyClassDescriptor) companionObjectDescriptor;
   } else {
     return null;
   }
 }
예제 #26
0
  @NotNull
  public static List<FieldInfo> calculateConstructorParameters(
      @NotNull JetTypeMapper typeMapper,
      @NotNull CalculatedClosure closure,
      @NotNull Type ownerType) {
    BindingContext bindingContext = typeMapper.getBindingContext();
    List<FieldInfo> args = Lists.newArrayList();
    ClassDescriptor captureThis = closure.getCaptureThis();
    if (captureThis != null) {
      Type type = typeMapper.mapType(captureThis);
      args.add(FieldInfo.createForHiddenField(ownerType, type, CAPTURED_THIS_FIELD));
    }
    JetType captureReceiverType = closure.getCaptureReceiverType();
    if (captureReceiverType != null) {
      args.add(
          FieldInfo.createForHiddenField(
              ownerType, typeMapper.mapType(captureReceiverType), CAPTURED_RECEIVER_FIELD));
    }

    for (DeclarationDescriptor descriptor : closure.getCaptureVariables().keySet()) {
      if (descriptor instanceof VariableDescriptor && !(descriptor instanceof PropertyDescriptor)) {
        Type sharedVarType = typeMapper.getSharedVarType(descriptor);

        Type type =
            sharedVarType != null
                ? sharedVarType
                : typeMapper.mapType((VariableDescriptor) descriptor);
        args.add(
            FieldInfo.createForHiddenField(ownerType, type, "$" + descriptor.getName().asString()));
      } else if (DescriptorUtils.isLocalFunction(descriptor)) {
        Type classType = asmTypeForAnonymousClass(bindingContext, (FunctionDescriptor) descriptor);
        args.add(
            FieldInfo.createForHiddenField(
                ownerType, classType, "$" + descriptor.getName().asString()));
      } else if (descriptor instanceof FunctionDescriptor) {
        assert captureReceiverType != null;
      }
    }
    return args;
  }
예제 #27
0
 // TODO: navigate to inner classes
 @Nullable
 public static ClassId getContainerClassId(@NotNull DeclarationDescriptor referencedDescriptor) {
   ClassOrPackageFragmentDescriptor containerDescriptor =
       DescriptorUtils.getParentOfType(
           referencedDescriptor, ClassOrPackageFragmentDescriptor.class, false);
   if (containerDescriptor instanceof PackageFragmentDescriptor) {
     return PackageClassUtils.getPackageClassId(getFqName(containerDescriptor).toSafe());
   }
   if (containerDescriptor instanceof ClassDescriptor) {
     ClassId classId = DescriptorUtilPackage.getClassId((ClassDescriptor) containerDescriptor);
     if (isInterface(containerDescriptor)) {
       FqName relativeClassName = classId.getRelativeClassName();
       // TODO test nested trait fun inlining
       classId =
           new ClassId(
               classId.getPackageFqName(),
               Name.identifier(
                   relativeClassName.shortName().asString() + JvmAbi.DEFAULT_IMPLS_SUFFIX));
     }
     return classId;
   }
   return null;
 }
예제 #28
0
  /** @return whether f overrides g */
  public static <D extends CallableDescriptor> boolean overrides(@NotNull D f, @NotNull D g) {
    // In a multi-module project different "copies" of the same class may be present in different
    // libraries,
    // that's why we use structural equivalence for members (DescriptorEquivalenceForOverrides).

    // This first check cover the case of duplicate classes in different modules:
    // when B is defined in modules m1 and m2, and C (indirectly) inherits from both versions,
    // we'll be getting sets of members that do not override each other, but are structurally
    // equivalent.
    // As other code relies on no equal descriptors passed here, we guard against f == g, but this
    // may not be necessary
    // Note that this is needed for the usage of this function in the IDE code
    if (!f.equals(g)
        && DescriptorEquivalenceForOverrides.INSTANCE.areEquivalent(
            f.getOriginal(), g.getOriginal())) return true;

    CallableDescriptor originalG = g.getOriginal();
    for (D overriddenFunction : DescriptorUtils.getAllOverriddenDescriptors(f)) {
      if (DescriptorEquivalenceForOverrides.INSTANCE.areEquivalent(originalG, overriddenFunction))
        return true;
    }
    return false;
  }
예제 #29
0
 @Nullable
 @Override
 protected ClassDescriptor classForInnerClassRecord() {
   return DescriptorUtils.isTopLevelDeclaration(descriptor) ? null : descriptor;
 }
 private String nameForAssertions() {
   return getName() + " declared in " + DescriptorUtils.getFqName(getContainingDeclaration());
 }