Пример #1
0
  public static void genNotNullAssertionsForParameters(
      @NotNull InstructionAdapter v,
      @NotNull GenerationState state,
      @NotNull FunctionDescriptor descriptor,
      @NotNull FrameMap frameMap) {
    if (!state.isGenerateNotNullParamAssertions()) return;

    // Private method is not accessible from other classes, no assertions needed
    if (getVisibilityAccessFlag(descriptor) == ACC_PRIVATE) return;

    for (ValueParameterDescriptor parameter : descriptor.getValueParameters()) {
      JetType type = parameter.getReturnType();
      if (type == null || isNullableType(type)) continue;

      int index = frameMap.getIndex(parameter);
      Type asmType = state.getTypeMapper().mapReturnType(type);
      if (asmType.getSort() == Type.OBJECT || asmType.getSort() == Type.ARRAY) {
        v.load(index, asmType);
        v.visitLdcInsn(descriptor.getName().asString());
        v.invokestatic(
            "jet/runtime/Intrinsics",
            "checkParameterIsNotNull",
            "(Ljava/lang/Object;Ljava/lang/String;)V");
      }
    }
  }
 private static String renderParameter(
     ValueParameterDescriptor descriptor, boolean named, BindingContext bindingContext) {
   StringBuilder builder = new StringBuilder();
   if (named) builder.append("[");
   if (descriptor.getVarargElementType() != null) {
     builder.append("vararg ");
   }
   builder
       .append(descriptor.getName())
       .append(": ")
       .append(DescriptorRenderer.TEXT.renderType(getActualParameterType(descriptor)));
   if (descriptor.hasDefaultValue()) {
     PsiElement element = BindingContextUtils.descriptorToDeclaration(bindingContext, descriptor);
     String defaultExpression = "?";
     if (element instanceof JetParameter) {
       JetParameter parameter = (JetParameter) element;
       JetExpression defaultValue = parameter.getDefaultValue();
       if (defaultValue != null) {
         if (defaultValue instanceof JetConstantExpression) {
           JetConstantExpression constantExpression = (JetConstantExpression) defaultValue;
           defaultExpression = constantExpression.getText();
           if (defaultExpression.length() > 10) {
             if (defaultExpression.startsWith("\"")) defaultExpression = "\"...\"";
             else if (defaultExpression.startsWith("\'")) defaultExpression = "\'...\'";
             else defaultExpression = defaultExpression.substring(0, 7) + "...";
           }
         }
       }
     }
     builder.append(" = ").append(defaultExpression);
   }
   if (named) builder.append("]");
   return builder.toString();
 }
 @Nullable
 public static List<ValueParameterDescriptor> getSubstitutedValueParameters(
     FunctionDescriptor substitutedDescriptor,
     @NotNull FunctionDescriptor functionDescriptor,
     @NotNull TypeSubstitutor substitutor) {
   List<ValueParameterDescriptor> result = new ArrayList<ValueParameterDescriptor>();
   List<ValueParameterDescriptor> unsubstitutedValueParameters =
       functionDescriptor.getValueParameters();
   for (int i = 0, unsubstitutedValueParametersSize = unsubstitutedValueParameters.size();
       i < unsubstitutedValueParametersSize;
       i++) {
     ValueParameterDescriptor unsubstitutedValueParameter = unsubstitutedValueParameters.get(i);
     // TODO : Lazy?
     JetType substitutedType =
         substitutor.substitute(unsubstitutedValueParameter.getType(), Variance.IN_VARIANCE);
     JetType varargElementType = unsubstitutedValueParameter.getVarargElementType();
     JetType substituteVarargElementType =
         varargElementType == null
             ? null
             : substitutor.substitute(varargElementType, Variance.IN_VARIANCE);
     if (substitutedType == null) return null;
     result.add(
         new ValueParameterDescriptorImpl(
             substitutedDescriptor,
             unsubstitutedValueParameter,
             unsubstitutedValueParameter.getAnnotations(),
             unsubstitutedValueParameter.isVar(),
             substitutedType,
             substituteVarargElementType));
   }
   return result;
 }
  @NotNull
  public static SimpleFunctionDescriptor createSamAdapterFunction(
      @NotNull SimpleFunctionDescriptor original) {
    SimpleFunctionDescriptorImpl result =
        new SimpleFunctionDescriptorImpl(
            original.getContainingDeclaration(),
            original.getAnnotations(),
            original.getName(),
            CallableMemberDescriptor.Kind.SYNTHESIZED);

    TypeParameters typeParameters =
        recreateAndInitializeTypeParameters(original.getTypeParameters(), result);

    JetType returnTypeUnsubstituted = original.getReturnType();
    assert returnTypeUnsubstituted != null : original;
    JetType returnType =
        typeParameters.substitutor.substitute(returnTypeUnsubstituted, Variance.OUT_VARIANCE);
    assert returnType != null
        : "couldn't substitute type: "
            + returnType
            + ", substitutor = "
            + typeParameters.substitutor;

    List<ValueParameterDescriptor> valueParameters = Lists.newArrayList();
    for (ValueParameterDescriptor originalParam : original.getValueParameters()) {
      JetType originalType = originalParam.getType();
      JetType newTypeUnsubstituted =
          isSamType(originalType) ? getFunctionTypeForSamType(originalType) : originalType;
      JetType newType =
          typeParameters.substitutor.substitute(newTypeUnsubstituted, Variance.IN_VARIANCE);
      assert newType != null
          : "couldn't substitute type: "
              + newTypeUnsubstituted
              + ", substitutor = "
              + typeParameters.substitutor;

      ValueParameterDescriptor newParam =
          new ValueParameterDescriptorImpl(
              result,
              originalParam.getIndex(),
              originalParam.getAnnotations(),
              originalParam.getName(),
              newType,
              false,
              null);
      valueParameters.add(newParam);
    }

    result.initialize(
        null,
        original.getExpectedThisObject(),
        typeParameters.descriptors,
        valueParameters,
        returnType,
        original.getModality(),
        original.getVisibility(),
        false);

    return result;
  }
Пример #5
0
  private void processPrimaryConstructor(
      @NotNull TopDownAnalysisContext c,
      @NotNull MutableClassDescriptor classDescriptor,
      @NotNull JetClass klass) {
    // TODO : not all the parameters are real properties
    JetScope memberScope = classDescriptor.getScopeForClassHeaderResolution();
    ConstructorDescriptor constructorDescriptor =
        descriptorResolver.resolvePrimaryConstructorDescriptor(
            memberScope, classDescriptor, klass, trace);
    if (constructorDescriptor != null) {
      List<ValueParameterDescriptor> valueParameterDescriptors =
          constructorDescriptor.getValueParameters();
      List<JetParameter> primaryConstructorParameters = klass.getPrimaryConstructorParameters();
      assert valueParameterDescriptors.size() == primaryConstructorParameters.size();
      List<ValueParameterDescriptor> notProperties = new ArrayList<ValueParameterDescriptor>();
      for (ValueParameterDescriptor valueParameterDescriptor : valueParameterDescriptors) {
        JetParameter parameter =
            primaryConstructorParameters.get(valueParameterDescriptor.getIndex());
        if (parameter.getValOrVarNode() != null) {
          PropertyDescriptor propertyDescriptor =
              descriptorResolver.resolvePrimaryConstructorParameterToAProperty(
                  classDescriptor, valueParameterDescriptor, memberScope, parameter, trace);
          classDescriptor.getBuilder().addPropertyDescriptor(propertyDescriptor);
          c.getPrimaryConstructorParameterProperties().put(parameter, propertyDescriptor);
        } else {
          notProperties.add(valueParameterDescriptor);
        }
      }

      if (classDescriptor.getKind() != ClassKind.TRAIT) {
        classDescriptor.setPrimaryConstructor(constructorDescriptor);
        classDescriptor.addConstructorParametersToInitializersScope(notProperties);
      }
    }
  }
  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);
  }
 public static boolean isSamAdapterNecessary(@NotNull SimpleFunctionDescriptor fun) {
   for (ValueParameterDescriptor param : fun.getValueParameters()) {
     if (isSamType(param.getType())) {
       return true;
     }
   }
   return false;
 }
Пример #8
0
  @NotNull
  private static FunctionDescriptor standardFunction(
      ClassDescriptor classDescriptor, String name, Project project, KotlinType... parameterTypes) {
    ModuleDescriptorImpl emptyModule = KotlinTestUtils.createEmptyModule();
    ContainerForTests container = InjectionKt.createContainerForTests(project, emptyModule);
    emptyModule.setDependencies(emptyModule);
    emptyModule.initialize(PackageFragmentProvider.Empty.INSTANCE);

    LexicalScopeImpl lexicalScope =
        new LexicalScopeImpl(
            ImportingScope.Empty.INSTANCE,
            classDescriptor,
            false,
            classDescriptor.getThisAsReceiverParameter(),
            LexicalScopeKind.SYNTHETIC);

    ExpressionTypingContext context =
        ExpressionTypingContext.newContext(
            new BindingTraceContext(),
            lexicalScope,
            DataFlowInfoFactory.EMPTY,
            TypeUtils.NO_EXPECTED_TYPE);

    OverloadResolutionResults<FunctionDescriptor> functions =
        container
            .getFakeCallResolver()
            .resolveFakeCall(
                context,
                null,
                Name.identifier(name),
                null,
                null,
                FakeCallKind.OTHER,
                parameterTypes);

    for (ResolvedCall<? extends FunctionDescriptor> resolvedCall : functions.getResultingCalls()) {
      List<ValueParameterDescriptor> unsubstitutedValueParameters =
          resolvedCall.getResultingDescriptor().getValueParameters();
      for (int i = 0, unsubstitutedValueParametersSize = unsubstitutedValueParameters.size();
          i < unsubstitutedValueParametersSize;
          i++) {
        ValueParameterDescriptor unsubstitutedValueParameter = unsubstitutedValueParameters.get(i);
        if (unsubstitutedValueParameter.getType().equals(parameterTypes[i])) {
          return resolvedCall.getResultingDescriptor();
        }
      }
    }
    throw new IllegalArgumentException(
        "Not found: kotlin::"
            + classDescriptor.getName()
            + "."
            + name
            + "("
            + Arrays.toString(parameterTypes)
            + ")");
  }
Пример #9
0
  @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);
  }
  private List<ValueParameterDescriptor> createValueParameterDescriptors(
      ExpressionTypingContext context,
      JetFunctionLiteral functionLiteral,
      FunctionDescriptorImpl functionDescriptor,
      boolean functionTypeExpected) {
    List<ValueParameterDescriptor> valueParameterDescriptors = Lists.newArrayList();
    List<JetParameter> declaredValueParameters = functionLiteral.getValueParameters();

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

    boolean hasDeclaredValueParameters = functionLiteral.getValueParameterList() != null;
    if (functionTypeExpected
        && !hasDeclaredValueParameters
        && expectedValueParameters.size() == 1) {
      ValueParameterDescriptor valueParameterDescriptor = expectedValueParameters.get(0);
      ValueParameterDescriptor it =
          new ValueParameterDescriptorImpl(
              functionDescriptor,
              0,
              Collections.<AnnotationDescriptor>emptyList(),
              "it",
              false,
              valueParameterDescriptor.getOutType(),
              valueParameterDescriptor.hasDefaultValue(),
              valueParameterDescriptor.getVarargElementType());
      valueParameterDescriptors.add(it);
      context.trace.record(AUTO_CREATED_IT, it);
    } else {
      for (int i = 0; i < declaredValueParameters.size(); i++) {
        JetParameter declaredParameter = declaredValueParameters.get(i);
        JetTypeReference typeReference = declaredParameter.getTypeReference();

        JetType type;
        if (typeReference != null) {
          type = context.getTypeResolver().resolveType(context.scope, typeReference);
        } else {
          if (expectedValueParameters != null && i < expectedValueParameters.size()) {
            type = expectedValueParameters.get(i).getOutType();
          } else {
            context.trace.report(CANNOT_INFER_PARAMETER_TYPE.on(declaredParameter));
            type = ErrorUtils.createErrorType("Cannot be inferred");
          }
        }
        ValueParameterDescriptor valueParameterDescriptor =
            context
                .getDescriptorResolver()
                .resolveValueParameterDescriptor(functionDescriptor, declaredParameter, i, type);
        valueParameterDescriptors.add(valueParameterDescriptor);
      }
    }
    return valueParameterDescriptors;
  }
Пример #11
0
  private void generateParameterAnnotations(
      @NotNull FunctionDescriptor functionDescriptor,
      @NotNull MethodVisitor mv,
      @NotNull JvmMethodSignature jvmSignature) {
    Iterator<ValueParameterDescriptor> iterator =
        functionDescriptor.getValueParameters().iterator();
    List<JvmMethodParameterSignature> kotlinParameterTypes = jvmSignature.getValueParameters();

    for (int i = 0; i < kotlinParameterTypes.size(); i++) {
      JvmMethodParameterSignature parameterSignature = kotlinParameterTypes.get(i);
      JvmMethodParameterKind kind = parameterSignature.getKind();
      if (kind.isSkippedInGenericSignature()) {
        markEnumOrInnerConstructorParameterAsSynthetic(mv, i);
        continue;
      }

      if (kind == JvmMethodParameterKind.VALUE) {
        ValueParameterDescriptor parameter = iterator.next();
        if (parameter.getIndex() != i) {
          v.getSerializationBindings().put(INDEX_FOR_VALUE_PARAMETER, parameter, i);
        }
        AnnotationCodegen annotationCodegen = AnnotationCodegen.forParameter(i, mv, typeMapper);

        if (functionDescriptor instanceof PropertySetterDescriptor) {
          PropertyDescriptor propertyDescriptor =
              ((PropertySetterDescriptor) functionDescriptor).getCorrespondingProperty();
          Annotated targetedAnnotations =
              new AnnotatedWithOnlyTargetedAnnotations(propertyDescriptor);
          annotationCodegen.genAnnotations(
              targetedAnnotations, parameterSignature.getAsmType(), SETTER_PARAMETER);
        }

        if (functionDescriptor instanceof ConstructorDescriptor) {
          annotationCodegen.genAnnotations(
              parameter, parameterSignature.getAsmType(), CONSTRUCTOR_PARAMETER);
        } else {
          annotationCodegen.genAnnotations(parameter, parameterSignature.getAsmType());
        }
      } else if (kind == JvmMethodParameterKind.RECEIVER) {
        ReceiverParameterDescriptor receiver =
            ((functionDescriptor instanceof PropertyAccessorDescriptor)
                    ? ((PropertyAccessorDescriptor) functionDescriptor).getCorrespondingProperty()
                    : functionDescriptor)
                .getExtensionReceiverParameter();
        if (receiver != null) {
          AnnotationCodegen annotationCodegen = AnnotationCodegen.forParameter(i, mv, typeMapper);
          Annotated targetedAnnotations =
              new AnnotatedWithOnlyTargetedAnnotations(receiver.getType());
          annotationCodegen.genAnnotations(
              targetedAnnotations, parameterSignature.getAsmType(), RECEIVER);
        }
      }
    }
  }
 @NotNull
 private List<ValueParameterDescriptor> copyValueParameters(
     @NotNull FunctionDescriptor descriptor) {
   List<ValueParameterDescriptor> valueParameters = descriptor.getValueParameters();
   List<ValueParameterDescriptor> result =
       new ArrayList<ValueParameterDescriptor>(valueParameters.size());
   for (ValueParameterDescriptor valueParameter : valueParameters) {
     result.add(valueParameter.copy(this, valueParameter.getName()));
   }
   return result;
 }
Пример #13
0
 protected void renderValueParameter(
     ValueParameterDescriptor parameterDescriptor, boolean isLast, StringBuilder builder) {
   if (parameterDescriptor.getIndex() == 0) {
     builder.append("(");
   }
   parameterDescriptor.accept(subVisitor, builder);
   if (!isLast) {
     builder.append(", ");
   } else {
     builder.append(")");
   }
 }
Пример #14
0
 private static boolean isDefaultNeeded(FunctionDescriptor functionDescriptor) {
   boolean needed = false;
   if (functionDescriptor != null) {
     for (ValueParameterDescriptor parameterDescriptor : functionDescriptor.getValueParameters()) {
       if (parameterDescriptor.declaresDefaultValue()) {
         needed = true;
         break;
       }
     }
   }
   return needed;
 }
Пример #15
0
  public static void bindOverride(
      CallableMemberDescriptor fromCurrent, CallableMemberDescriptor fromSupertype) {
    fromCurrent.addOverriddenDescriptor(fromSupertype);

    for (ValueParameterDescriptor parameterFromCurrent : fromCurrent.getValueParameters()) {
      assert parameterFromCurrent.getIndex() < fromSupertype.getValueParameters().size()
          : "An override relation between functions implies that they have the same number of value parameters";
      ValueParameterDescriptor parameterFromSupertype =
          fromSupertype.getValueParameters().get(parameterFromCurrent.getIndex());
      parameterFromCurrent.addOverriddenDescriptor(parameterFromSupertype);
    }
  }
 public ValueParameterDescriptorImpl(
     @NotNull DeclarationDescriptor containingDeclaration,
     @NotNull ValueParameterDescriptor original,
     @NotNull List<AnnotationDescriptor> annotations,
     @NotNull JetType outType,
     @Nullable JetType varargElementType) {
   super(containingDeclaration, annotations, original.getName(), outType);
   this.original = original;
   this.index = original.getIndex();
   this.declaresDefaultValue = original.declaresDefaultValue();
   this.varargElementType = varargElementType;
 }
Пример #17
0
 static List<KotlinType> compiledValueParameters(CallableDescriptor callableDescriptor) {
   ReceiverParameterDescriptor receiverParameter =
       callableDescriptor.getExtensionReceiverParameter();
   List<KotlinType> parameters = new ArrayList<KotlinType>();
   if (receiverParameter != null) {
     parameters.add(receiverParameter.getType());
   }
   for (ValueParameterDescriptor valueParameterDescriptor :
       callableDescriptor.getValueParameters()) {
     parameters.add(valueParameterDescriptor.getType());
   }
   return parameters;
 }
Пример #18
0
  @Nullable
  public static ValueParameterDescriptor getAnnotationParameterByName(
      @NotNull Name name, @NotNull ClassDescriptor annotationClass) {
    Collection<ConstructorDescriptor> constructors = annotationClass.getConstructors();
    assert constructors.size() == 1 : "Annotation class descriptor must have only one constructor";

    for (ValueParameterDescriptor parameter : constructors.iterator().next().getValueParameters()) {
      if (parameter.getName().equals(name)) {
        return parameter;
      }
    }

    return null;
  }
  @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;
  }
 private void computeDefaultValuePresence() {
   if (hasDefaultValue != null) return;
   overriddenDescriptorsLocked = true;
   if (declaresDefaultValue) {
     hasDefaultValue = true;
   } else {
     for (ValueParameterDescriptor descriptor : overriddenDescriptors) {
       if (descriptor.hasDefaultValue()) {
         hasDefaultValue = true;
         return;
       }
     }
     hasDefaultValue = false;
   }
 }
 @NotNull
 private static JetType getFunctionTypeForSamType(@NotNull JetType samType) {
   FunctionDescriptor function = getAbstractMethodOfSamType(samType);
   JetType returnType = function.getReturnType();
   assert returnType != null : "function is not initialized: " + function;
   List<JetType> parameterTypes = Lists.newArrayList();
   for (ValueParameterDescriptor parameter : function.getValueParameters()) {
     parameterTypes.add(parameter.getType());
   }
   JetType functionType =
       KotlinBuiltIns.getInstance()
           .getFunctionType(
               Collections.<AnnotationDescriptor>emptyList(), null, parameterTypes, returnType);
   return TypeUtils.makeNullableAsSpecified(functionType, samType.isNullable());
 }
Пример #22
0
 private void checkDefaultParameterValues(
     List<JetParameter> valueParameters,
     List<ValueParameterDescriptor> valueParameterDescriptors,
     JetScope declaringScope) {
   for (int i = 0; i < valueParameters.size(); i++) {
     ValueParameterDescriptor valueParameterDescriptor = valueParameterDescriptors.get(i);
     if (valueParameterDescriptor.hasDefaultValue()) {
       JetParameter jetParameter = valueParameters.get(i);
       JetExpression defaultValue = jetParameter.getDefaultValue();
       if (defaultValue != null) {
         expressionTypingServices.getType(
             declaringScope, defaultValue, valueParameterDescriptor.getType(), trace);
       }
     }
   }
 }
Пример #23
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);
  }
 private static String renderParameter(ValueParameterDescriptor parameter, boolean named) {
   StringBuilder builder = new StringBuilder();
   if (named) builder.append("[");
   if (parameter.getVarargElementType() != null) {
     builder.append("vararg ");
   }
   builder
       .append(parameter.getName())
       .append(": ")
       .append(
           DescriptorRenderer.SHORT_NAMES_IN_TYPES.renderType(getActualParameterType(parameter)));
   if (DescriptorUtilPackage.hasDefaultValue(parameter)) {
     PsiElement parameterDeclaration = DescriptorToSourceUtils.descriptorToDeclaration(parameter);
     builder.append(" = ").append(getDefaultExpressionString(parameterDeclaration));
   }
   if (named) builder.append("]");
   return builder.toString();
 }
Пример #25
0
  private static void generateLocalVariableTable(
      @NotNull MethodVisitor mv,
      @NotNull JvmMethodSignature jvmMethodSignature,
      @NotNull FunctionDescriptor functionDescriptor,
      @Nullable Type thisType,
      @NotNull Label methodBegin,
      @NotNull Label methodEnd,
      @NotNull OwnerKind ownerKind) {
    Iterator<ValueParameterDescriptor> valueParameters =
        functionDescriptor.getValueParameters().iterator();
    List<JvmMethodParameterSignature> params = jvmMethodSignature.getValueParameters();
    int shift = 0;

    boolean isStatic = AsmUtil.isStaticMethod(ownerKind, functionDescriptor);
    if (!isStatic) {
      // add this
      if (thisType != null) {
        mv.visitLocalVariable(
            "this", thisType.getDescriptor(), null, methodBegin, methodEnd, shift);
      } else {
        // TODO: provide thisType for callable reference
      }
      shift++;
    }

    for (int i = 0; i < params.size(); i++) {
      JvmMethodParameterSignature param = params.get(i);
      JvmMethodParameterKind kind = param.getKind();
      String parameterName;

      if (kind == JvmMethodParameterKind.VALUE) {
        ValueParameterDescriptor parameter = valueParameters.next();
        parameterName = parameter.getName().asString();
      } else {
        String lowercaseKind = kind.name().toLowerCase();
        parameterName = needIndexForVar(kind) ? "$" + lowercaseKind + "$" + i : "$" + lowercaseKind;
      }

      Type type = param.getAsmType();
      mv.visitLocalVariable(
          parameterName, type.getDescriptor(), null, methodBegin, methodEnd, shift);
      shift += type.getSize();
    }
  }
Пример #26
0
  /* VARIABLES */
  private void renderValueParameter(
      @NotNull ValueParameterDescriptor valueParameter,
      @NotNull StringBuilder builder,
      boolean topLevel) {
    if (topLevel) {
      builder.append(renderKeyword("value-parameter")).append(" ");
    }

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

    renderAnnotations(valueParameter, builder);
    renderVariable(valueParameter, builder, topLevel);
    boolean withDefaultValue =
        debugMode ? valueParameter.declaresDefaultValue() : valueParameter.hasDefaultValue();
    if (withDefaultValue) {
      builder.append(" = ...");
    }
  }
Пример #27
0
  private void createComponentFunctions(
      @NotNull MutableClassDescriptor classDescriptor,
      @NotNull ConstructorDescriptor constructorDescriptor) {
    int parameterIndex = 0;
    for (ValueParameterDescriptor parameter : constructorDescriptor.getValueParameters()) {
      if (!parameter.getType().isError()) {
        PropertyDescriptor property =
            trace.get(BindingContext.VALUE_PARAMETER_AS_PROPERTY, parameter);
        if (property != null) {
          ++parameterIndex;

          SimpleFunctionDescriptor functionDescriptor =
              DescriptorResolver.createComponentFunctionDescriptor(
                  parameterIndex, property, parameter, classDescriptor, trace);

          classDescriptor.getBuilder().addFunctionDescriptor(functionDescriptor);
        }
      }
    }
  }
Пример #28
0
  public static boolean containsErrorType(@NotNull FunctionDescriptor function) {
    if (containsErrorType(function.getReturnType())) {
      return true;
    }
    ReceiverParameterDescriptor receiverParameter = function.getReceiverParameter();
    if (receiverParameter != null && containsErrorType(receiverParameter.getType())) {
      return true;
    }
    for (ValueParameterDescriptor parameter : function.getValueParameters()) {
      if (containsErrorType(parameter.getType())) {
        return true;
      }
    }
    for (TypeParameterDescriptor parameter : function.getTypeParameters()) {
      for (JetType upperBound : parameter.getUpperBounds()) {
        if (containsErrorType(upperBound)) {
          return true;
        }
      }
    }

    return false;
  }
Пример #29
0
  @Nullable
  private CompileTimeConstant<?> getCompileTimeConstFromArrayExpression(
      FqName annotationFqName,
      Name valueName,
      PsiArrayInitializerMemberValue value,
      PostponedTasks taskList) {
    PsiAnnotationMemberValue[] initializers = value.getInitializers();
    List<CompileTimeConstant<?>> values =
        getCompileTimeConstantForArrayValues(annotationFqName, valueName, taskList, initializers);

    ClassDescriptor classDescriptor =
        classResolver.resolveClass(annotationFqName, DescriptorSearchRule.INCLUDE_KOTLIN, taskList);

    // TODO: nullability issues
    ValueParameterDescriptor valueParameterDescriptor =
        DescriptorResolverUtils.getValueParameterDescriptorForAnnotationParameter(
            valueName, classDescriptor);
    if (valueParameterDescriptor == null) {
      return null;
    }
    JetType expectedArrayType = valueParameterDescriptor.getType();
    return new ArrayValue(values, expectedArrayType);
  }
Пример #30
0
  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);
    }
  }