Example #1
0
 public static int getDeprecatedAccessFlag(@NotNull MemberDescriptor descriptor) {
   if (descriptor instanceof PropertyAccessorDescriptor) {
     return KotlinBuiltIns.getInstance().isDeprecated(descriptor)
         ? ACC_DEPRECATED
         : getDeprecatedAccessFlag(
             ((PropertyAccessorDescriptor) descriptor).getCorrespondingProperty());
   } else if (KotlinBuiltIns.getInstance().isDeprecated(descriptor)) {
     return ACC_DEPRECATED;
   }
   return 0;
 }
Example #2
0
  /* TYPE PARAMETERS */
  private void renderTypeParameter(
      @NotNull TypeParameterDescriptor typeParameter,
      @NotNull StringBuilder builder,
      boolean topLevel) {
    if (topLevel) {
      builder.append(lt());
    }

    if (verbose) {
      builder.append("/*").append(typeParameter.getIndex()).append("*/ ");
    }

    if (typeParameter.isReified()) {
      builder.append(renderKeyword("reified")).append(" ");
    }
    String variance = typeParameter.getVariance().toString();
    if (!variance.isEmpty()) {
      builder.append(renderKeyword(variance)).append(" ");
    }
    renderName(typeParameter, builder);
    int upperBoundsCount = typeParameter.getUpperBounds().size();
    if ((upperBoundsCount > 1 && !topLevel) || upperBoundsCount == 1) {
      JetType upperBound = typeParameter.getUpperBounds().iterator().next();
      if (!KotlinBuiltIns.getInstance().getDefaultBound().equals(upperBound) || alwaysRenderAny) {
        builder.append(" : ").append(renderType(upperBound));
      }
    } else if (topLevel) {
      boolean first = true;
      for (JetType upperBound : typeParameter.getUpperBounds()) {
        if (upperBound.equals(KotlinBuiltIns.getInstance().getDefaultBound())) {
          continue;
        }
        if (first) {
          builder.append(" : ");
        } else {
          builder.append(" & ");
        }
        builder.append(renderType(upperBound));
        first = false;
      }
    } else {
      // rendered with "where"
    }

    if (topLevel) {
      builder.append(">");
    }
  }
Example #3
0
  /* FUNCTIONS */
  private void renderFunction(
      @NotNull FunctionDescriptor function, @NotNull StringBuilder builder) {
    if (!startFromName) {
      renderAnnotations(function, builder);
      renderVisibility(function.getVisibility(), builder);
      renderModalityForCallable(function, builder);
      renderOverride(function, builder);
      renderMemberKind(function, builder);

      builder.append(renderKeyword("fun")).append(" ");
      renderTypeParameters(function.getTypeParameters(), builder, true);

      ReceiverParameterDescriptor receiver = function.getReceiverParameter();
      if (receiver != null) {
        builder.append(escape(renderType(receiver.getType()))).append(".");
      }
    }

    renderName(function, builder);
    renderValueParameters(function, builder);
    JetType returnType = function.getReturnType();
    if (unitReturnType || !KotlinBuiltIns.getInstance().isUnit(returnType)) {
      builder.append(": ").append(returnType == null ? "[NULL]" : escape(renderType(returnType)));
    }
    renderWhereSuffix(function.getTypeParameters(), builder);
  }
  public static void registerClassNameForScript(
      BindingTrace bindingTrace,
      @NotNull ScriptDescriptor scriptDescriptor,
      @NotNull JvmClassName className) {
    bindingTrace.record(SCRIPT_NAMES, className);

    ClassDescriptorImpl classDescriptor =
        new ClassDescriptorImpl(
            scriptDescriptor,
            Collections.<AnnotationDescriptor>emptyList(),
            Modality.FINAL,
            Name.special("<script-" + className + ">"));
    classDescriptor.initialize(
        false,
        Collections.<TypeParameterDescriptor>emptyList(),
        Collections.singletonList(KotlinBuiltIns.getInstance().getAnyType()),
        JetScope.EMPTY,
        Collections.<ConstructorDescriptor>emptySet(),
        null,
        false);

    recordClosure(bindingTrace, null, classDescriptor, null, className, false);

    assert PsiCodegenPredictor.checkPredictedClassNameForFun(
        bindingTrace.getBindingContext(), scriptDescriptor, classDescriptor);
    bindingTrace.record(CLASS_FOR_SCRIPT, scriptDescriptor, classDescriptor);
  }
Example #5
0
  public ReplInterpreter(
      @NotNull Disposable disposable, @NotNull CompilerConfiguration configuration) {
    jetCoreEnvironment = JetCoreEnvironment.createForProduction(disposable, configuration);
    Project project = jetCoreEnvironment.getProject();
    trace = new BindingTraceContext();
    module = AnalyzerFacadeForJVM.createJavaModule("<repl>");
    TopDownAnalysisParameters topDownAnalysisParameters =
        TopDownAnalysisParameters.createForLocalDeclarations(
            new LockBasedStorageManager(),
            new ExceptionTracker(), // dummy
            Predicates.<PsiFile>alwaysTrue());
    injector =
        new InjectorForTopDownAnalyzerForJvm(
            project, topDownAnalysisParameters, trace, module, MemberFilter.ALWAYS_TRUE);
    topDownAnalysisContext = new TopDownAnalysisContext(topDownAnalysisParameters);
    module.addFragmentProvider(SOURCES, injector.getTopDownAnalyzer().getPackageFragmentProvider());
    module.addFragmentProvider(
        BUILT_INS, KotlinBuiltIns.getInstance().getBuiltInsModule().getPackageFragmentProvider());
    module.addFragmentProvider(
        BINARIES, injector.getJavaDescriptorResolver().getPackageFragmentProvider());

    List<URL> classpath = Lists.newArrayList();

    for (File file : configuration.getList(JVMConfigurationKeys.CLASSPATH_KEY)) {
      try {
        classpath.add(file.toURI().toURL());
      } catch (MalformedURLException e) {
        throw UtilsPackage.rethrow(e);
      }
    }

    classLoader = new ReplClassLoader(new URLClassLoader(classpath.toArray(new URL[0])));
  }
Example #6
0
  public void addDefaultUpperBound() {
    checkUninitialized();

    if (upperBounds.isEmpty()) {
      doAddUpperBound(KotlinBuiltIns.getInstance().getDefaultBound());
    }
  }
Example #7
0
    public ErrorClassDescriptor(@Nullable String name) {
      super(
          getErrorModule(),
          Name.special(name == null ? "<ERROR CLASS>" : "<ERROR CLASS: " + name + ">"),
          Modality.OPEN,
          Collections.<JetType>emptyList(),
          SourceElement.NO_SOURCE);

      ConstructorDescriptorImpl errorConstructor =
          ConstructorDescriptorImpl.create(this, Annotations.EMPTY, true, SourceElement.NO_SOURCE);
      errorConstructor.initialize(
          Collections.<TypeParameterDescriptor>emptyList(),
          Collections.<ValueParameterDescriptor>emptyList(),
          Visibilities.INTERNAL);
      JetScope memberScope = createErrorScope(getName().asString());
      errorConstructor.setReturnType(
          new ErrorTypeImpl(
              TypeConstructorImpl.createForClass(
                  this,
                  Annotations.EMPTY,
                  false,
                  getName().asString(),
                  Collections.<TypeParameterDescriptorImpl>emptyList(),
                  Collections.singleton(KotlinBuiltIns.getInstance().getAnyType())),
              memberScope));

      initialize(
          memberScope,
          Collections.<ConstructorDescriptor>singleton(errorConstructor),
          errorConstructor);
    }
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);
  }
  @Nullable
  private static InsertHandler<LookupElement> getInsertHandler(
      @NotNull DeclarationDescriptor descriptor) {
    if (descriptor instanceof FunctionDescriptor) {
      FunctionDescriptor functionDescriptor = (FunctionDescriptor) descriptor;

      if (functionDescriptor.getValueParameters().isEmpty()) {
        return EMPTY_FUNCTION_HANDLER;
      }

      if (functionDescriptor.getValueParameters().size() == 1
          && KotlinBuiltIns.getInstance()
              .isFunctionOrExtensionFunctionType(
                  functionDescriptor.getValueParameters().get(0).getType())) {
        return PARAMS_BRACES_FUNCTION_HANDLER;
      }

      return PARAMS_PARENTHESIS_FUNCTION_HANDLER;
    }

    if (descriptor instanceof ClassDescriptor) {
      return JetClassInsertHandler.INSTANCE;
    }

    return null;
  }
Example #10
0
  /* CLASSES */
  private void renderClass(@NotNull ClassDescriptor klass, @NotNull StringBuilder builder) {
    if (!startFromName) {
      renderAnnotations(klass, builder);
      renderVisibility(klass.getVisibility(), builder);
      if (!(klass.getKind() == ClassKind.TRAIT && klass.getModality() == Modality.ABSTRACT
          || klass.getKind().isObject() && klass.getModality() == Modality.FINAL)) {
        renderModality(klass.getModality(), builder);
      }
      renderInner(klass.isInner(), builder);
      builder.append(renderKeyword(getClassKindPrefix(klass)));
    }

    if (klass.getKind() != ClassKind.CLASS_OBJECT || verbose) {
      builder.append(" ");
      renderName(klass, builder);
    }

    List<TypeParameterDescriptor> typeParameters = klass.getTypeConstructor().getParameters();
    renderTypeParameters(typeParameters, builder, false);

    if (!klass.getKind().isObject() && classWithPrimaryConstructor) {
      ConstructorDescriptor primaryConstructor = klass.getUnsubstitutedPrimaryConstructor();
      if (primaryConstructor != null) {
        renderValueParameters(primaryConstructor, builder);
      }
    }

    if (!klass.equals(KotlinBuiltIns.getInstance().getNothing())) {
      Collection<JetType> supertypes = klass.getTypeConstructor().getSupertypes();
      if (supertypes.isEmpty()
          || !alwaysRenderAny
              && supertypes.size() == 1
              && KotlinBuiltIns.getInstance().isAny(supertypes.iterator().next())) {
      } else {
        builder.append(" : ");
        for (Iterator<JetType> iterator = supertypes.iterator(); iterator.hasNext(); ) {
          JetType supertype = iterator.next();
          builder.append(renderType(supertype));
          if (iterator.hasNext()) {
            builder.append(", ");
          }
        }
      }
    }

    renderWhereSuffix(typeParameters, builder);
  }
  @NotNull
  public TypeInfoForCall getQualifiedExpressionExtendedTypeInfo(
      @NotNull JetQualifiedExpression expression,
      @NotNull ResolutionContext context,
      @NotNull ResolveMode resolveMode) {
    // TODO : functions as values
    JetExpression selectorExpression = expression.getSelectorExpression();
    JetExpression receiverExpression = expression.getReceiverExpression();
    JetTypeInfo receiverTypeInfo =
        expressionTypingServices.getTypeInfoWithNamespaces(
            receiverExpression,
            context.scope,
            NO_EXPECTED_TYPE,
            context.dataFlowInfo,
            context.trace);
    JetType receiverType = receiverTypeInfo.getType();
    if (selectorExpression == null) return TypeInfoForCall.create(null, context.dataFlowInfo);
    if (receiverType == null)
      receiverType = ErrorUtils.createErrorType("Type for " + expression.getText());

    context = context.replaceDataFlowInfo(receiverTypeInfo.getDataFlowInfo());

    if (selectorExpression instanceof JetSimpleNameExpression) {
      ConstantUtils.propagateConstantValues(
          expression, context.trace, (JetSimpleNameExpression) selectorExpression);
    }

    TypeInfoForCall selectorReturnTypeInfo =
        getSelectorReturnTypeInfo(
            new ExpressionReceiver(receiverExpression, receiverType),
            expression.getOperationTokenNode(),
            selectorExpression,
            context,
            resolveMode);
    JetType selectorReturnType = selectorReturnTypeInfo.getType();

    // TODO move further
    if (!(receiverType instanceof NamespaceType)
        && expression.getOperationSign() == JetTokens.SAFE_ACCESS) {
      if (selectorReturnType != null
          && !selectorReturnType.isNullable()
          && !KotlinBuiltIns.getInstance().isUnit(selectorReturnType)) {
        if (receiverType.isNullable()) {
          selectorReturnType = TypeUtils.makeNullable(selectorReturnType);
        }
      }
    }

    // TODO : this is suspicious: remove this code?
    if (selectorReturnType != null) {
      context.trace.record(BindingContext.EXPRESSION_TYPE, selectorExpression, selectorReturnType);
    }
    JetTypeInfo typeInfo =
        JetTypeInfo.create(selectorReturnType, selectorReturnTypeInfo.getDataFlowInfo());
    if (resolveMode == ResolveMode.TOP_LEVEL_CALL) {
      DataFlowUtils.checkType(typeInfo.getType(), expression, context, typeInfo.getDataFlowInfo());
    }
    return TypeInfoForCall.create(typeInfo, selectorReturnTypeInfo);
  }
  public static void initializeFromFunctionType(
      @NotNull FunctionDescriptorImpl functionDescriptor,
      @NotNull JetType functionType,
      @Nullable ReceiverParameterDescriptor expectedThisObject,
      @NotNull Modality modality,
      @NotNull Visibility visibility) {

    assert KotlinBuiltIns.getInstance().isFunctionOrExtensionFunctionType(functionType);
    functionDescriptor.initialize(
        KotlinBuiltIns.getInstance().getReceiverType(functionType),
        expectedThisObject,
        Collections.<TypeParameterDescriptorImpl>emptyList(),
        KotlinBuiltIns.getInstance().getValueParameters(functionDescriptor, functionType),
        KotlinBuiltIns.getInstance().getReturnTypeFromFunctionType(functionType),
        modality,
        visibility);
  }
  @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);
  }
 @NotNull
 private JetType computeUpperBoundsAsType() {
   Set<JetType> upperBounds = getUpperBounds();
   assert !upperBounds.isEmpty() : "Upper bound list is empty in " + getName();
   JetType upperBoundsAsType = TypeUtils.intersect(JetTypeChecker.DEFAULT, upperBounds);
   return upperBoundsAsType != null
       ? upperBoundsAsType
       : KotlinBuiltIns.getInstance().getNothingType();
 }
  private JavaDescriptorResolver.ValueParameterDescriptors
      modifyValueParametersAccordingToSuperMethods(
          @NotNull
              JavaDescriptorResolver.ValueParameterDescriptors
                  parameters // descriptors built by parameters resolver
          ) {
    // we are not processing receiver type specifically:
    // if this function comes from Kotlin, then we don't need to do it, if it doesn't, then it can't
    // have receiver

    List<ValueParameterDescriptor> resultParameters = Lists.newArrayList();

    for (ValueParameterDescriptor originalParam : parameters.getDescriptors()) {
      final int index = originalParam.getIndex();
      List<TypeAndVariance> typesFromSuperMethods =
          ContainerUtil.map(
              superFunctions,
              new Function<FunctionDescriptor, TypeAndVariance>() {
                @Override
                public TypeAndVariance fun(FunctionDescriptor superFunction) {
                  return new TypeAndVariance(
                      superFunction.getValueParameters().get(index).getType(), INVARIANT);
                }
              });

      VarargCheckResult varargCheckResult = checkVarargInSuperFunctions(originalParam);

      JetType altType =
          modifyTypeAccordingToSuperMethods(
              varargCheckResult.parameterType,
              typesFromSuperMethods,
              MEMBER_SIGNATURE_CONTRAVARIANT);

      resultParameters.add(
          new ValueParameterDescriptorImpl(
              originalParam.getContainingDeclaration(),
              index,
              originalParam.getAnnotations(),
              originalParam.getName(),
              altType,
              originalParam.declaresDefaultValue(),
              varargCheckResult.isVararg
                  ? KotlinBuiltIns.getInstance().getArrayElementType(altType)
                  : null));
    }

    JetType originalReceiverType = parameters.getReceiverType();
    if (originalReceiverType != null) {
      JetType substituted =
          SignaturesUtil.createSubstitutorForFunctionTypeParameters(autoTypeParameterToModified)
              .substitute(originalReceiverType, INVARIANT);
      assert substituted != null;
      return new JavaDescriptorResolver.ValueParameterDescriptors(substituted, resultParameters);
    } else {
      return new JavaDescriptorResolver.ValueParameterDescriptors(null, resultParameters);
    }
  }
Example #16
0
  @Nullable
  public static Name getNameIfStandardType(@NotNull JetType type) {
    ClassifierDescriptor descriptor = type.getConstructor().getDeclarationDescriptor();
    if (descriptor != null
        && descriptor.getContainingDeclaration()
            == KotlinBuiltIns.getInstance().getBuiltInsPackageFragment()) {
      return descriptor.getName();
    }

    return null;
  }
Example #17
0
  public static boolean isVoidType(@Nullable JetTypeReference typeReference) {
    if (typeReference == null) {
      return false;
    }

    return KotlinBuiltIns.getInstance()
        .getUnit()
        .getName()
        .asString()
        .equals(typeReference.getText());
  }
  @NotNull
  private static JetType computeReturnType(
      @NotNull JetFunctionLiteralExpression expression,
      @NotNull ExpressionTypingContext context,
      @NotNull SimpleFunctionDescriptorImpl functionDescriptor,
      boolean functionTypeExpected) {
    JetType expectedReturnType =
        functionTypeExpected
            ? KotlinBuiltIns.getInstance().getReturnTypeFromFunctionType(context.expectedType)
            : null;
    JetType returnType =
        computeUnsafeReturnType(expression, context, functionDescriptor, expectedReturnType);

    if (!expression.getFunctionLiteral().hasDeclaredReturnType() && functionTypeExpected) {
      if (KotlinBuiltIns.getInstance().isUnit(expectedReturnType)) {
        return KotlinBuiltIns.getInstance().getUnitType();
      }
    }
    return returnType == null ? CANT_INFER_LAMBDA_PARAM_TYPE : returnType;
  }
Example #19
0
 @NotNull
 private static TypeConstructor createErrorTypeConstructorWithCustomDebugName(
     @NotNull String debugName) {
   return TypeConstructorImpl.createForClass(
       ERROR_CLASS,
       Annotations.EMPTY,
       false,
       debugName,
       Collections.<TypeParameterDescriptorImpl>emptyList(),
       Collections.singleton(KotlinBuiltIns.getInstance().getAnyType()));
 }
Example #20
0
 private static JetType createErrorTypeWithCustomDebugName(
     JetScope memberScope, String debugName) {
   return new ErrorTypeImpl(
       new TypeConstructorImpl(
           ERROR_CLASS,
           Collections.<AnnotationDescriptor>emptyList(),
           false,
           debugName,
           Collections.<TypeParameterDescriptorImpl>emptyList(),
           Collections.singleton(KotlinBuiltIns.getInstance().getAnyType())),
       memberScope);
 }
Example #21
0
  @NotNull
  private String renderFunctionType(@NotNull JetType type) {
    StringBuilder sb = new StringBuilder();

    JetType receiverType = KotlinBuiltIns.getInstance().getReceiverType(type);
    if (receiverType != null) {
      sb.append(renderType(receiverType));
      sb.append(".");
    }

    sb.append("(");
    appendTypeProjections(
        KotlinBuiltIns.getInstance().getParameterTypeProjectionsFromFunctionType(type), sb);
    sb.append(") " + arrow() + " ");
    sb.append(renderType(KotlinBuiltIns.getInstance().getReturnTypeFromFunctionType(type)));

    if (type.isNullable()) {
      return "(" + sb + ")?";
    }
    return sb.toString();
  }
 private void addBaseClass(
     @NotNull PsiClassWrapper psiClass,
     @NotNull ClassPsiDeclarationProvider classData,
     @NotNull ClassDescriptor classDescriptor,
     @NotNull List<JetType> result) {
   if (classData.getDeclarationOrigin() == KOTLIN
       || DescriptorResolverUtils.OBJECT_FQ_NAME.equalsTo(psiClass.getQualifiedName())
       // TODO: annotations
       || classDescriptor.getKind() == ClassKind.ANNOTATION_CLASS) {
     result.add(KotlinBuiltIns.getInstance().getAnyType());
   } else {
     ClassDescriptor object = resolveJavaLangObject();
     if (object != null) {
       result.add(object.getDefaultType());
     } else {
       // TODO: hack here
       result.add(KotlinBuiltIns.getInstance().getAnyType());
       // throw new IllegalStateException("Could not resolve java.lang.Object");
     }
   }
 }
  @NotNull
  private VarargCheckResult checkVarargInSuperFunctions(
      @NotNull ValueParameterDescriptor originalParam) {
    boolean someSupersVararg = false;
    boolean someSupersNotVararg = false;
    for (FunctionDescriptor superFunction : superFunctions) {
      if (superFunction.getValueParameters().get(originalParam.getIndex()).getVarargElementType()
          != null) {
        someSupersVararg = true;
      } else {
        someSupersNotVararg = true;
      }
    }

    JetType originalVarargElementType = originalParam.getVarargElementType();
    JetType originalType = originalParam.getType();

    if (someSupersVararg && someSupersNotVararg) {
      reportError("Incompatible super methods: some have vararg parameter, some have not");
      return new VarargCheckResult(originalType, originalVarargElementType != null);
    }

    KotlinBuiltIns builtIns = KotlinBuiltIns.getInstance();
    if (someSupersVararg && originalVarargElementType == null) {
      // convert to vararg

      assert isArrayType(originalType);

      if (builtIns.isPrimitiveArray(originalType)) {
        // replace IntArray? with IntArray
        return new VarargCheckResult(TypeUtils.makeNotNullable(originalType), true);
      }

      // replace Array<out Foo>? with Array<Foo>
      JetType varargElementType = builtIns.getArrayElementType(originalType);
      return new VarargCheckResult(builtIns.getArrayType(INVARIANT, varargElementType), true);
    } else if (someSupersNotVararg && originalVarargElementType != null) {
      // convert to non-vararg

      assert isArrayType(originalType);

      if (builtIns.isPrimitiveArray(originalType)) {
        // replace IntArray with IntArray?
        return new VarargCheckResult(TypeUtils.makeNullable(originalType), false);
      }

      // replace Array<Foo> with Array<out Foo>?
      return new VarargCheckResult(
          TypeUtils.makeNullable(
              builtIns.getArrayType(Variance.OUT_VARIANCE, originalVarargElementType)),
          false);
    }

    return new VarargCheckResult(originalType, originalVarargElementType != null);
  }
  public static FunctionDescriptor getInvokeFunction(@NotNull JetType functionType) {
    assert KotlinBuiltIns.getInstance().isFunctionOrExtensionFunctionType(functionType);

    ClassifierDescriptor classDescriptorForFunction =
        functionType.getConstructor().getDeclarationDescriptor();
    assert classDescriptorForFunction instanceof ClassDescriptor;
    Collection<FunctionDescriptor> invokeFunctions =
        ((ClassDescriptor) classDescriptorForFunction)
            .getMemberScope(functionType.getArguments())
            .getFunctions(Name.identifier("invoke"));
    assert invokeFunctions.size() == 1;
    return invokeFunctions.iterator().next();
  }
Example #25
0
  @NotNull
  public static JetType createCorrespondingExtensionFunctionType(
      @NotNull JetType functionType, @NotNull JetType receiverType) {
    assert KotlinBuiltIns.getInstance().isFunctionType(functionType);

    List<TypeProjection> typeArguments = functionType.getArguments();
    assert !typeArguments.isEmpty();

    List<JetType> arguments = Lists.newArrayList();
    // excluding the last type argument of the function type, which is the return type
    int index = 0;
    int lastIndex = typeArguments.size() - 1;
    for (TypeProjection typeArgument : typeArguments) {
      if (index < lastIndex) {
        arguments.add(typeArgument.getType());
      }
      index++;
    }
    JetType returnType = typeArguments.get(lastIndex).getType();
    return KotlinBuiltIns.getInstance()
        .getFunctionType(functionType.getAnnotations(), receiverType, arguments, returnType);
  }
Example #26
0
 public static boolean isDeprecated(@NotNull JetModifierListOwner owner) {
   JetModifierList modifierList = owner.getModifierList();
   if (modifierList != null) {
     List<JetAnnotationEntry> annotationEntries = modifierList.getAnnotationEntries();
     for (JetAnnotationEntry annotation : annotationEntries) {
       Name shortName = getShortName(annotation);
       if (KotlinBuiltIns.getInstance().getDeprecatedAnnotation().getName().equals(shortName)) {
         return true;
       }
     }
   }
   return false;
 }
Example #27
0
  @Override
  public void setUp() throws Exception {
    super.setUp();

    builtIns = KotlinBuiltIns.getInstance();

    InjectorForTests injector =
        new InjectorForTests(getProject(), JetTestUtils.createEmptyModule());
    typeResolver = injector.getTypeResolver();
    expressionTypingServices = injector.getExpressionTypingServices();

    scopeWithImports = getDeclarationsScope("compiler/testData/type-checker-test.kt");
  }
Example #28
0
 private String renderTypeWithoutEscape(@NotNull JetType type) {
   if (type == CANT_INFER_LAMBDA_PARAM_TYPE || type == CANT_INFER_TYPE_PARAMETER) {
     return "???";
   }
   if (type.isError()) {
     return type.toString();
   }
   if (KotlinBuiltIns.getInstance().isFunctionOrExtensionFunctionType(type)
       && prettyFunctionTypes) {
     return renderFunctionType(type);
   }
   return renderDefaultType(type);
 }
Example #29
0
 @Nullable
 public static JetType getPrimitiveRangeElementType(JetType rangeType) {
   ClassifierDescriptor declarationDescriptor =
       rangeType.getConstructor().getDeclarationDescriptor();
   assert declarationDescriptor != null;
   if (declarationDescriptor
       != KotlinBuiltIns.getInstance()
           .getBuiltInsScope()
           .getClassifier(declarationDescriptor.getName())) {
     // Must be a standard library class
     return null;
   }
   return RANGE_TO_ELEMENT_TYPE.get(declarationDescriptor.getName().getName());
 }
  @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;
  }