Example #1
0
 @Override
 protected boolean isVisible(
     @NotNull DeclarationDescriptorWithVisibility what,
     @NotNull DeclarationDescriptor from) {
   ModuleDescriptor parentModule =
       DescriptorUtils.getParentOfType(what, ModuleDescriptor.class, false);
   ModuleDescriptor fromModule =
       DescriptorUtils.getParentOfType(from, ModuleDescriptor.class, false);
   assert parentModule != null && fromModule != null;
   return parentModule.equals(fromModule);
 }
  @NotNull
  private static Multimap<FqName, Pair<FunctionDescriptor, PsiMethod>>
      getSuperclassToFunctionsMultimap(
          @NotNull PsiMethodWrapper method,
          @NotNull BindingContext bindingContext,
          @NotNull ClassDescriptor containingClass) {
    Multimap<FqName, Pair<FunctionDescriptor, PsiMethod>> result = HashMultimap.create();

    Name functionName = Name.identifier(method.getName());
    int parameterCount = method.getParameters().size();

    for (JetType supertype : TypeUtils.getAllSupertypes(containingClass.getDefaultType())) {
      ClassifierDescriptor klass = supertype.getConstructor().getDeclarationDescriptor();
      assert klass != null;
      FqName fqName = DescriptorUtils.getFQName(klass).toSafe();

      for (FunctionDescriptor fun :
          klass.getDefaultType().getMemberScope().getFunctions(functionName)) {
        if (fun.getKind().isReal() && fun.getValueParameters().size() == parameterCount) {
          PsiElement declaration = BindingContextUtils.descriptorToDeclaration(bindingContext, fun);
          if (declaration instanceof PsiMethod) {
            result.put(fqName, Pair.create(fun, (PsiMethod) declaration));
          } // else declaration is null or JetNamedFunction: both cases are processed later
        }
      }
    }
    return result;
  }
Example #3
0
  private String renderDefaultType(JetType type, boolean shortNamesOnly) {
    StringBuilder sb = new StringBuilder();
    ClassifierDescriptor cd = type.getConstructor().getDeclarationDescriptor();

    Object typeNameObject;

    if (cd == null || cd instanceof TypeParameterDescriptor) {
      typeNameObject = type.getConstructor();
    } else {
      if (shortNamesOnly) {
        // for nested classes qualified name should be used
        typeNameObject = cd.getName();
        DeclarationDescriptor parent = cd.getContainingDeclaration();
        while (parent instanceof ClassDescriptor) {
          typeNameObject = parent.getName() + "." + typeNameObject;
          parent = parent.getContainingDeclaration();
        }
      } else {
        typeNameObject = DescriptorUtils.getFQName(cd);
      }
    }

    sb.append(typeNameObject);
    if (!type.getArguments().isEmpty()) {
      sb.append("<");
      appendTypeProjections(sb, type.getArguments(), shortNamesOnly);
      sb.append(">");
    }
    if (type.isNullable()) {
      sb.append("?");
    }
    return sb.toString();
  }
Example #4
0
 @Override
 protected boolean isVisible(
     @NotNull DeclarationDescriptorWithVisibility what,
     @NotNull DeclarationDescriptor from) {
   if (what instanceof CallableMemberDescriptor
       && ((CallableMemberDescriptor) what).getKind()
           == CallableMemberDescriptor.Kind.FAKE_OVERRIDE) {
     return false;
   }
   DeclarationDescriptor parent = what;
   while (parent != null) {
     parent = parent.getContainingDeclaration();
     if ((parent instanceof ClassDescriptor && !DescriptorUtils.isClassObject(parent))
         || parent instanceof NamespaceDescriptor) {
       break;
     }
   }
   DeclarationDescriptor fromParent = from;
   while (fromParent != null) {
     if (parent == fromParent) {
       return true;
     }
     fromParent = fromParent.getContainingDeclaration();
   }
   return false;
 }
Example #5
0
 @NotNull
 @Override
 public Collection<? extends JetType> getSupertypes() {
   if (supertypes == null) {
     if (resolveSession.isClassSpecial(DescriptorUtils.getFQName(LazyClassDescriptor.this))) {
       this.supertypes = Collections.emptyList();
     } else {
       JetClassOrObject classOrObject =
           declarationProvider.getOwnerInfo().getCorrespondingClassOrObject();
       if (classOrObject == null) {
         this.supertypes = Collections.emptyList();
       } else {
         List<JetType> allSupertypes =
             resolveSession
                 .getInjector()
                 .getDescriptorResolver()
                 .resolveSupertypes(
                     getScopeForClassHeaderResolution(),
                     LazyClassDescriptor.this,
                     classOrObject,
                     resolveSession.getTrace());
         List<JetType> validSupertypes =
             Lists.newArrayList(Collections2.filter(allSupertypes, VALID_SUPERTYPE));
         this.supertypes = validSupertypes;
         findAndDisconnectLoopsInTypeHierarchy(validSupertypes);
       }
     }
   }
   return supertypes;
 }
Example #6
0
 @Override
 public ClassifierDescriptor getClassifier(@NotNull Name name) {
   // TODO: creating an FqName every time may be a performance problem
   Name actualName =
       resolveSession.resolveClassifierAlias(DescriptorUtils.getFqNameSafe(thisDescriptor), name);
   return super.getClassifier(actualName);
 }
 private static String getDescriptorString(@NotNull DeclarationDescriptor descriptor) {
   if (descriptor instanceof ClassDescriptor) {
     return DescriptorUtils.getFqName(descriptor).asString();
   } else if (descriptor instanceof ConstructorDescriptor) {
     DeclarationDescriptor containingDeclaration = descriptor.getContainingDeclaration();
     assert containingDeclaration != null;
     return "constructor for " + containingDeclaration.getName();
   } else if (descriptor instanceof PropertyGetterDescriptor) {
     return "getter for "
         + ((PropertyGetterDescriptor) descriptor).getCorrespondingProperty().getName();
   } else if (descriptor instanceof PropertySetterDescriptor) {
     return "setter for "
         + ((PropertySetterDescriptor) descriptor).getCorrespondingProperty().getName();
   } else if (descriptor instanceof PropertyDescriptor) {
     if (((PropertyDescriptor) descriptor).isVar()) {
       return "var " + descriptor.getName();
     }
     return "val " + descriptor.getName();
   } else if (descriptor instanceof FunctionDescriptor) {
     return "fun "
         + descriptor.getName()
         + DescriptorRenderer.FQ_NAMES_IN_TYPES.renderFunctionParameters(
             (FunctionDescriptor) descriptor);
   }
   return DescriptorRenderer.FQ_NAMES_IN_TYPES.render(descriptor);
 }
Example #8
0
  @NotNull
  public Collection<JetType> getSupertypesForClosure(@NotNull FunctionDescriptor descriptor) {
    ReceiverParameterDescriptor receiverParameter = descriptor.getReceiverParameter();

    List<TypeProjection> typeArguments = new ArrayList<TypeProjection>(2);

    ClassDescriptor classDescriptor;
    if (receiverParameter != null) {
      classDescriptor = extensionFunctionImpl;
      typeArguments.add(new TypeProjectionImpl(receiverParameter.getType()));
    } else {
      classDescriptor = functionImpl;
    }

    //noinspection ConstantConditions
    typeArguments.add(new TypeProjectionImpl(descriptor.getReturnType()));

    JetType functionImplType =
        new JetTypeImpl(
            classDescriptor.getDefaultType().getAnnotations(),
            classDescriptor.getTypeConstructor(),
            false,
            typeArguments,
            classDescriptor.getMemberScope(typeArguments));

    JetType functionType =
        KotlinBuiltIns.getInstance()
            .getFunctionType(
                Annotations.EMPTY,
                receiverParameter == null ? null : receiverParameter.getType(),
                DescriptorUtils.getValueParametersTypes(descriptor.getValueParameters()),
                descriptor.getReturnType());

    return Arrays.asList(functionImplType, functionType);
  }
Example #9
0
        @Override
        protected boolean isVisible(
            @NotNull DeclarationDescriptorWithVisibility what,
            @NotNull DeclarationDescriptor from) {
          ClassDescriptor classDescriptor =
              DescriptorUtils.getParentOfType(what, 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 false;
        }
Example #10
0
                  @Override
                  public Collection<JetType> invoke() {
                    if (resolveSession.isClassSpecial(
                        DescriptorUtils.getFQName(LazyClassDescriptor.this))) {
                      return Collections.emptyList();
                    } else {
                      JetClassOrObject classOrObject =
                          declarationProvider.getOwnerInfo().getCorrespondingClassOrObject();
                      if (classOrObject == null) {
                        return Collections.emptyList();
                      } else {
                        List<JetType> allSupertypes =
                            resolveSession
                                .getInjector()
                                .getDescriptorResolver()
                                .resolveSupertypes(
                                    getScopeForClassHeaderResolution(),
                                    LazyClassDescriptor.this,
                                    classOrObject,
                                    resolveSession.getTrace());

                        return Lists.newArrayList(
                            Collections2.filter(allSupertypes, VALID_SUPERTYPE));
                      }
                    }
                  }
Example #11
0
 /*
    Use this method to get visibility flag for class to define it in byte code (v.defineClass method).
    For other cases use getVisibilityAccessFlag(MemberDescriptor descriptor)
    Classes in byte code should be public or package private
 */
 public static int getVisibilityAccessFlagForClass(ClassDescriptor descriptor) {
   if (DescriptorUtils.isTopLevelDeclaration(descriptor)
       || descriptor.getVisibility() == Visibilities.PUBLIC
       || descriptor.getVisibility() == Visibilities.INTERNAL) {
     return ACC_PUBLIC;
   }
   return NO_FLAG_PACKAGE_PRIVATE;
 }
  @Override
  public JetTypeInfo visitFunctionLiteralExpression(
      @NotNull JetFunctionLiteralExpression expression, ExpressionTypingContext context) {
    JetBlockExpression bodyExpression = expression.getFunctionLiteral().getBodyExpression();
    if (bodyExpression == null) return null;

    Name callerName = getCallerName(expression);
    if (callerName != null) {
      context.labelResolver.enterLabeledElement(new LabelName(callerName.asString()), expression);
    }

    JetType expectedType = context.expectedType;
    boolean functionTypeExpected =
        !noExpectedType(expectedType)
            && KotlinBuiltIns.getInstance().isFunctionOrExtensionFunctionType(expectedType);

    AnonymousFunctionDescriptor functionDescriptor =
        createFunctionDescriptor(expression, context, functionTypeExpected);
    JetType safeReturnType =
        computeReturnType(expression, context, functionDescriptor, functionTypeExpected);
    functionDescriptor.setReturnType(safeReturnType);

    JetType receiver =
        DescriptorUtils.getReceiverParameterType(functionDescriptor.getReceiverParameter());
    List<JetType> valueParametersTypes =
        DescriptorUtils.getValueParametersTypes(functionDescriptor.getValueParameters());
    JetType resultType =
        KotlinBuiltIns.getInstance()
            .getFunctionType(
                Collections.<AnnotationDescriptor>emptyList(),
                receiver,
                valueParametersTypes,
                safeReturnType);
    if (!noExpectedType(expectedType)
        && KotlinBuiltIns.getInstance().isFunctionOrExtensionFunctionType(expectedType)) {
      // all checks were done before
      return JetTypeInfo.create(resultType, context.dataFlowInfo);
    }

    if (callerName != null) {
      context.labelResolver.exitLabeledElement(expression);
    }

    return DataFlowUtils.checkType(resultType, expression, context, context.dataFlowInfo);
  }
Example #13
0
 @Override
 @NotNull
 public Collection<ClassDescriptor> mapPlatformClass(@NotNull ClassDescriptor classDescriptor) {
   FqNameUnsafe className = DescriptorUtils.getFQName(classDescriptor);
   if (!className.isSafe()) {
     return Collections.emptyList();
   }
   return mapPlatformClass(className.toSafe());
 }
Example #14
0
 private void generateRemoveInIterator() {
   // generates stub 'remove' function for subclasses of Iterator to be compatible with
   // java.util.Iterator
   if (DescriptorUtils.isIteratorWithoutRemoveImpl(descriptor)) {
     MethodVisitor mv = v.getVisitor().visitMethod(ACC_PUBLIC, "remove", "()V", null, null);
     genMethodThrow(
         mv,
         "java/lang/UnsupportedOperationException",
         "Mutating method called on a Kotlin Iterator");
   }
 }
  @Nullable
  public static JavaPackageFragmentDescriptor getPackageForCorrespondingJavaClass(
      @NotNull JavaClassDescriptor javaClass) {
    PackageFragmentDescriptor packageFragment =
        DescriptorUtils.getParentOfType(javaClass, PackageFragmentDescriptor.class);
    assert packageFragment instanceof JavaPackageFragmentDescriptor
        : "java class " + javaClass + " is under non-java fragment: " + packageFragment;

    JavaPackageFragmentProvider provider =
        ((JavaPackageFragmentDescriptor) packageFragment).getProvider();
    return provider.getPackageFragment(getFqNameSafe(javaClass));
  }
Example #16
0
 @NotNull
 private CallTranslator finish() {
   if (resolvedCall == null) {
     assert descriptor != null;
     resolvedCall =
         ResolvedCallImpl.create(
             ResolutionCandidate.create(
                 descriptor,
                 DescriptorUtils.safeGetValue(descriptor.getExpectedThisObject()),
                 DescriptorUtils.safeGetValue(descriptor.getReceiverParameter()),
                 ExplicitReceiverKind.THIS_OBJECT,
                 false),
             TemporaryBindingTrace.create(
                 new BindingTraceContext(), "trace to resolve call (in js)"));
   }
   if (descriptor == null) {
     descriptor = resolvedCall.getCandidateDescriptor().getOriginal();
   }
   assert resolvedCall != null;
   return new CallTranslator(receiver, callee, args, resolvedCall, descriptor, callType, context);
 }
Example #17
0
  private void renderAnnotations(@NotNull Annotated annotated, @NotNull StringBuilder builder) {
    if (!modifiers.contains(Modifier.ANNOTATIONS)) return;
    for (AnnotationDescriptor annotation : annotated.getAnnotations()) {
      ClassDescriptor annotationClass =
          (ClassDescriptor) annotation.getType().getConstructor().getDeclarationDescriptor();
      assert annotationClass != null;

      if (!excludedAnnotationClasses.contains(
          DescriptorUtils.getFQName(annotationClass).toSafe())) {
        builder.append(renderType(annotation.getType()));
        if (verbose) {
          builder
              .append("(")
              .append(
                  StringUtil.join(DescriptorUtils.getSortedValueArguments(annotation, this), ", "))
              .append(")");
        }
        builder.append(" ");
      }
    }
  }
 public AccessorForPropertyDescriptor(
     @NotNull PropertyDescriptor pd,
     @NotNull DeclarationDescriptor containingDeclaration,
     int index) {
   this(
       pd,
       pd.getType(),
       DescriptorUtils.getReceiverParameterType(pd.getReceiverParameter()),
       pd.getExpectedThisObject(),
       containingDeclaration,
       index);
 }
Example #19
0
 private void renderModalityForCallable(
     @NotNull CallableMemberDescriptor callable, @NotNull StringBuilder builder) {
   if (!DescriptorUtils.isTopLevelDeclaration(callable)
       || callable.getModality() != Modality.FINAL) {
     if (overridesSomething(callable)
         && overrideRenderingPolicy == OverrideRenderingPolicy.RENDER_OVERRIDE
         && callable.getModality() == Modality.OPEN) {
       return;
     }
     renderModality(callable.getModality(), builder);
   }
 }
 @Override
 public void extendNamespaceScope(
     @NotNull BindingTrace trace,
     @NotNull NamespaceDescriptor namespaceDescriptor,
     @NotNull WritableScope namespaceMemberScope) {
   namespaceMemberScope.importScope(
       javaSemanticServices
           .getDescriptorResolver()
           .createJavaPackageScope(
               DescriptorUtils.getFQName(namespaceDescriptor).toSafe(), namespaceDescriptor));
   delegateConfiguration.extendNamespaceScope(trace, namespaceDescriptor, namespaceMemberScope);
 }
Example #21
0
 public static <D extends CallableDescriptor> void splitLexicallyLocalDescriptors(
     @NotNull Collection<ResolutionCandidate<D>> allDescriptors,
     @NotNull DeclarationDescriptor containerOfTheCurrentLocality,
     @NotNull Collection<ResolutionCandidate<D>> local,
     @NotNull Collection<ResolutionCandidate<D>> nonlocal) {
   for (ResolutionCandidate<D> resolvedCall : allDescriptors) {
     if (DescriptorUtils.isLocal(containerOfTheCurrentLocality, resolvedCall.getDescriptor())) {
       local.add(resolvedCall);
     } else {
       nonlocal.add(resolvedCall);
     }
   }
 }
Example #22
0
 @Override
 @NotNull
 public Collection<ClassDescriptor> mapPlatformClassesInside(
     @NotNull DeclarationDescriptor containingDeclaration) {
   FqNameUnsafe fqName = DescriptorUtils.getFQName(containingDeclaration);
   if (!fqName.isSafe()) {
     return Collections.emptyList();
   }
   Collection<ClassDescriptor> result = packagesWithMappedClasses.get(fqName.toSafe());
   return result == null
       ? Collections.<ClassDescriptor>emptySet()
       : Collections.unmodifiableCollection(result);
 }
Example #23
0
  @NotNull
  public static JvmClassName byClassDescriptor(@NotNull ClassifierDescriptor classDescriptor) {
    DeclarationDescriptor descriptor = classDescriptor;

    List<String> innerClassNames = Lists.newArrayList();
    while (descriptor.getContainingDeclaration() instanceof ClassDescriptor) {
      innerClassNames.add(descriptor.getName().getName());
      descriptor = descriptor.getContainingDeclaration();
      assert descriptor != null;
    }

    return byFqNameAndInnerClassList(
        DescriptorUtils.getFQName(descriptor).toSafe(), innerClassNames);
  }
  @NotNull
  private static List<ValueParameterDescriptor> createValueParameterDescriptors(
      @NotNull ExpressionTypingContext context,
      @NotNull JetFunctionLiteral functionLiteral,
      @NotNull FunctionDescriptorImpl functionDescriptor,
      boolean functionTypeExpected) {
    List<ValueParameterDescriptor> valueParameterDescriptors = Lists.newArrayList();
    List<JetParameter> declaredValueParameters = functionLiteral.getValueParameters();

    List<ValueParameterDescriptor> expectedValueParameters =
        (functionTypeExpected)
            ? KotlinBuiltIns.getInstance()
                .getValueParameters(functionDescriptor, context.expectedType)
            : null;

    JetParameterList valueParameterList = functionLiteral.getValueParameterList();
    boolean hasDeclaredValueParameters = valueParameterList != null;
    if (functionTypeExpected
        && !hasDeclaredValueParameters
        && expectedValueParameters.size() == 1) {
      ValueParameterDescriptor valueParameterDescriptor = expectedValueParameters.get(0);
      ValueParameterDescriptor it =
          new ValueParameterDescriptorImpl(
              functionDescriptor,
              0,
              Collections.<AnnotationDescriptor>emptyList(),
              Name.identifier("it"),
              valueParameterDescriptor.getType(),
              valueParameterDescriptor.hasDefaultValue(),
              valueParameterDescriptor.getVarargElementType());
      valueParameterDescriptors.add(it);
      context.trace.record(AUTO_CREATED_IT, it);
    } else {
      if (expectedValueParameters != null
          && declaredValueParameters.size() != expectedValueParameters.size()) {
        List<JetType> expectedParameterTypes =
            DescriptorUtils.getValueParametersTypes(expectedValueParameters);
        context.trace.report(
            EXPECTED_PARAMETERS_NUMBER_MISMATCH.on(
                functionLiteral, expectedParameterTypes.size(), expectedParameterTypes));
      }
      for (int i = 0; i < declaredValueParameters.size(); i++) {
        ValueParameterDescriptor valueParameterDescriptor =
            createValueParameterDescriptor(
                context, functionDescriptor, declaredValueParameters, expectedValueParameters, i);
        valueParameterDescriptors.add(valueParameterDescriptor);
      }
    }
    return valueParameterDescriptors;
  }
Example #25
0
  /* METHODS FOR ALL KINDS OF DESCRIPTORS */
  private void appendDefinedIn(
      @NotNull DeclarationDescriptor descriptor, @NotNull StringBuilder builder) {
    if (descriptor instanceof ModuleDescriptor) {
      builder.append(" is a module");
      return;
    }
    builder.append(" ").append(renderMessage("defined in")).append(" ");

    DeclarationDescriptor containingDeclaration = descriptor.getContainingDeclaration();
    if (containingDeclaration != null) {
      FqNameUnsafe fqName = DescriptorUtils.getFQName(containingDeclaration);
      builder.append(FqName.ROOT.equalsTo(fqName) ? "root package" : renderFqName(fqName));
    }
  }
Example #26
0
 public static boolean isVisible(
     DeclarationDescriptorWithVisibility what, DeclarationDescriptor from) {
   DeclarationDescriptorWithVisibility parent = what;
   while (parent != null) {
     if (parent.getVisibility() == LOCAL) {
       return true;
     }
     if (!parent.getVisibility().isVisible(parent, from)) {
       return false;
     }
     parent = DescriptorUtils.getParentOfType(parent, DeclarationDescriptorWithVisibility.class);
   }
   return true;
 }
Example #27
0
 @NotNull
 @Override
 public String render(@NotNull Collection<ClassDescriptor> descriptors) {
   StringBuilder sb = new StringBuilder();
   int index = 0;
   for (ClassDescriptor descriptor : descriptors) {
     sb.append(DescriptorUtils.getFQName(descriptor).getFqName());
     index++;
     if (index <= descriptors.size() - 2) {
       sb.append(", ");
     } else if (index == descriptors.size() - 1) {
       sb.append(" or ");
     }
   }
   return sb.toString();
 }
Example #28
0
 @Override
 public ClassifierDescriptor getClassifier(@NotNull String name) {
   ClassDescriptor classDescriptor =
       semanticServices
           .getDescriptorResolver()
           .resolveClass(
               getQualifiedName(packageFQN, name), DescriptorSearchRule.IGNORE_IF_FOUND_IN_KOTLIN);
   if (classDescriptor == null || DescriptorUtils.isObject(classDescriptor)) {
     // TODO: this is a big hack against several things that I barely understand myself and cannot
     // explain
     // 1. We should not return objects from this method, and maybe JDR.resolveClass should not
     // return too
     // 2. JDR should not return classes being analyzed
     return null;
   }
   return classDescriptor;
 }
    @NotNull
    private MutableClassDescriptor createSyntheticClassObject(
        @NotNull ClassDescriptor classDescriptor) {
      MutableClassDescriptor classObject =
          new MutableClassDescriptor(
              classDescriptor,
              outerScope,
              ClassKind.CLASS_OBJECT,
              false,
              getClassObjectName(classDescriptor.getName()));

      classObject.setModality(Modality.FINAL);
      classObject.setVisibility(DescriptorUtils.getSyntheticClassObjectVisibility());
      classObject.setTypeParameterDescriptors(Collections.<TypeParameterDescriptor>emptyList());
      createPrimaryConstructorForObject(null, classObject);
      return classObject;
    }
Example #30
0
 @Nullable
 private JetClassLikeInfo getClassObjectInfo(JetClassObject classObject) {
   if (classObject != null) {
     if (!DescriptorUtils.inStaticContext(this)) {
       return null;
     }
     JetObjectDeclaration objectDeclaration = classObject.getObjectDeclaration();
     if (objectDeclaration != null) {
       return JetClassInfoUtil.createClassLikeInfo(objectDeclaration);
     }
   } else {
     if (getKind() == ClassKind.ENUM_CLASS) {
       // Enum classes always have class objects, and enum constants are their members
       return onlyEnumEntries(originalClassInfo);
     }
   }
   return null;
 }