Exemple #1
0
 @NotNull
 public OverloadResolutionResults<VariableDescriptor> resolveSimpleProperty(
     @NotNull BasicCallResolutionContext context) {
   JetExpression calleeExpression = context.call.getCalleeExpression();
   assert calleeExpression instanceof JetSimpleNameExpression;
   JetSimpleNameExpression nameExpression = (JetSimpleNameExpression) calleeExpression;
   Name referencedName = nameExpression.getReferencedNameAsName();
   List<CallableDescriptorCollector<? extends VariableDescriptor>> callableDescriptorCollectors =
       Lists.newArrayList();
   if (nameExpression.getReferencedNameElementType() == JetTokens.FIELD_IDENTIFIER) {
     referencedName = Name.identifier(referencedName.asString().substring(1));
     callableDescriptorCollectors.add(CallableDescriptorCollectors.PROPERTIES);
   } else {
     callableDescriptorCollectors.add(CallableDescriptorCollectors.VARIABLES);
   }
   List<ResolutionTask<VariableDescriptor, VariableDescriptor>> prioritizedTasks =
       TaskPrioritizer.<VariableDescriptor, VariableDescriptor>computePrioritizedTasks(
           context, referencedName, nameExpression, callableDescriptorCollectors);
   return doResolveCallOrGetCachedResults(
       ResolutionResultsCache.PROPERTY_MEMBER_TYPE,
       context,
       prioritizedTasks,
       CallTransformer.PROPERTY_CALL_TRANSFORMER,
       nameExpression);
 }
    @Nullable
    @Override
    protected ClassData getClassData(@NotNull ClassId classId) {
      InputStream stream =
          getStreamNullable(BuiltInsSerializationUtil.getClassMetadataPath(classId));
      if (stream == null) {
        return null;
      }

      try {
        ProtoBuf.Class classProto = ProtoBuf.Class.parseFrom(stream);

        Name expectedShortName = classId.getRelativeClassName().shortName();
        Name actualShortName =
            nameResolver.getClassId(classProto.getFqName()).getRelativeClassName().shortName();
        if (!actualShortName.isSpecial() && !actualShortName.equals(expectedShortName)) {
          // Workaround for case-insensitive file systems,
          // otherwise we'd find "Collection" for "collection" etc
          return null;
        }

        return new ClassData(nameResolver, classProto);
      } catch (IOException e) {
        throw new IllegalStateException(e);
      }
    }
Exemple #3
0
 private static void addForClassType(
     ArrayList<String> result, JetType jetType, JetNameValidator validator) {
   ClassDescriptor classDescriptor = TypeUtils.getClassDescriptor(jetType);
   if (classDescriptor != null) {
     Name className = classDescriptor.getName();
     addCamelNames(result, className.getName(), validator);
   }
 }
  private static String getJvmInternalFQNameImpl(
      BindingTrace bindingTrace, DeclarationDescriptor descriptor) {
    if (descriptor instanceof FunctionDescriptor) {
      throw new IllegalStateException("requested fq name for function: " + descriptor);
    }

    if (descriptor.getContainingDeclaration() instanceof ModuleDescriptor
        || descriptor instanceof ScriptDescriptor) {
      return "";
    }

    if (descriptor instanceof ModuleDescriptor) {
      throw new IllegalStateException("missed something");
    }

    if (descriptor instanceof ClassDescriptor) {
      ClassDescriptor klass = (ClassDescriptor) descriptor;
      if (klass.getKind() == ClassKind.OBJECT || klass.getKind() == ClassKind.CLASS_OBJECT) {
        if (klass.getContainingDeclaration() instanceof ClassDescriptor) {
          ClassDescriptor containingKlass = (ClassDescriptor) klass.getContainingDeclaration();
          if (containingKlass.getKind() == ClassKind.ENUM_CLASS) {
            return getJvmInternalName(bindingTrace, containingKlass).getInternalName();
          } else {
            return getJvmInternalName(bindingTrace, containingKlass).getInternalName()
                + JvmAbi.CLASS_OBJECT_SUFFIX;
          }
        }
      }

      JvmClassName name = bindingTrace.getBindingContext().get(FQN, descriptor);
      if (name != null) {
        return name.getInternalName();
      }
    }

    DeclarationDescriptor container = descriptor.getContainingDeclaration();

    if (container == null) {
      throw new IllegalStateException("descriptor has no container: " + descriptor);
    }

    Name name = descriptor.getName();

    String baseName = getJvmInternalName(bindingTrace, container).getInternalName();
    if (!baseName.isEmpty()) {
      return baseName
          + (container instanceof NamespaceDescriptor ? "/" : "$")
          + name.getIdentifier();
    }

    return name.getIdentifier();
  }
Exemple #5
0
  @Test
  public void pathSegments() {
    Assert.assertEquals(Lists.newArrayList(), new FqName("").pathSegments());

    for (String name : new String[] {"com", "com.jetbrains", "com.jetbrains.jet"}) {
      List<Name> segments = new FqName(name).pathSegments();
      List<String> segmentsStrings = new ArrayList<String>();
      for (Name segment : segments) {
        segmentsStrings.add(segment.getName());
      }
      Assert.assertEquals(Arrays.asList(name.split("\\.")), segmentsStrings);
    }
  }
  @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;
  }
  public void testMultiPackageFunction() {
    myFixture.configureByText(
        JetFileType.INSTANCE,
        "package test.testing\n" + "fun other(v : Int) = 12\n" + "fun other(v : String) {}");

    StubPackageMemberDeclarationProvider provider =
        new StubPackageMemberDeclarationProvider(
            new FqName("test.testing"), getProject(), GlobalSearchScope.projectScope(getProject()));

    List<JetNamedFunction> other =
        Lists.newArrayList(provider.getFunctionDeclarations(Name.identifier("other")));
    Collection<String> functionTexts =
        Collections2.transform(
            other,
            new Function<JetNamedFunction, String>() {
              @Override
              public String apply(JetNamedFunction function) {
                return function.getText();
              }
            });

    assertSize(2, other);
    assertTrue(functionTexts.contains("fun other(v : Int) = 12"));
    assertTrue(functionTexts.contains("fun other(v : String) {}"));
  }
Exemple #8
0
  @NotNull
  protected ExpressionCodegen createOrGetClInitCodegen() {
    DeclarationDescriptor descriptor = context.getContextDescriptor();
    assert state.getClassBuilderMode() == ClassBuilderMode.FULL
        : "<clinit> should not be generated for light classes. Descriptor: " + descriptor;
    if (clInit == null) {
      MethodVisitor mv = v.newMethod(null, ACC_STATIC, "<clinit>", "()V", null, null);
      mv.visitCode();
      SimpleFunctionDescriptorImpl clInit =
          SimpleFunctionDescriptorImpl.create(
              descriptor, Annotations.EMPTY, Name.special("<clinit>"), SYNTHESIZED);
      clInit.initialize(
          null,
          null,
          Collections.<TypeParameterDescriptor>emptyList(),
          Collections.<ValueParameterDescriptor>emptyList(),
          null,
          null,
          Visibilities.PRIVATE);

      this.clInit =
          new ExpressionCodegen(
              mv, new FrameMap(), Type.VOID_TYPE, context.intoFunction(clInit), state, this);
    }
    return clInit;
  }
  private ClassDescriptor recordClassForFunction(FunctionDescriptor funDescriptor) {
    ClassDescriptor classDescriptor;
    int arity = funDescriptor.getValueParameters().size();

    classDescriptor =
        new ClassDescriptorImpl(
            funDescriptor.getContainingDeclaration(),
            Collections.<AnnotationDescriptor>emptyList(),
            Modality.FINAL,
            Name.special("<closure>"));
    ((ClassDescriptorImpl) classDescriptor)
        .initialize(
            false,
            Collections.<TypeParameterDescriptor>emptyList(),
            Collections.singleton(
                (funDescriptor.getReceiverParameter().exists()
                        ? JetStandardClasses.getReceiverFunction(arity)
                        : JetStandardClasses.getFunction(arity))
                    .getDefaultType()),
            JetScope.EMPTY,
            Collections.<ConstructorDescriptor>emptySet(),
            null);

    assert PsiCodegenPredictor.checkPredictedClassNameForFun(
        bindingContext, funDescriptor, classDescriptor);
    bindingTrace.record(CLASS_FOR_FUNCTION, funDescriptor, classDescriptor);
    return classDescriptor;
  }
  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);
  }
Exemple #11
0
 static {
   ERROR_MODULE =
       new ModuleDescriptorImpl(
           Name.special("<ERROR MODULE>"),
           Collections.<ImportPath>emptyList(),
           PlatformToKotlinClassMap.EMPTY);
 }
Exemple #12
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);
    }
  public static AnalyzeExhaust analyzeFilesWithJavaIntegration(
      Project project,
      Collection<JetFile> files,
      BindingTrace trace,
      List<AnalyzerScriptParameter> scriptParameters,
      Predicate<PsiFile> filesToAnalyzeCompletely,
      boolean storeContextForBodiesResolve) {
    final ModuleDescriptor owner = new ModuleDescriptor(Name.special("<module>"));

    TopDownAnalysisParameters topDownAnalysisParameters =
        new TopDownAnalysisParameters(filesToAnalyzeCompletely, false, false, scriptParameters);

    InjectorForTopDownAnalyzerForJvm injector =
        new InjectorForTopDownAnalyzerForJvm(
            project, topDownAnalysisParameters, new ObservableBindingTrace(trace), owner);
    try {
      injector.getTopDownAnalyzer().analyzeFiles(files, scriptParameters);
      BodiesResolveContext bodiesResolveContext =
          storeContextForBodiesResolve
              ? new CachedBodiesResolveContext(injector.getTopDownAnalysisContext())
              : null;
      return AnalyzeExhaust.success(
          trace.getBindingContext(), bodiesResolveContext, injector.getModuleConfiguration());
    } finally {
      injector.destroy();
    }
  }
Exemple #14
0
/** @author Stepan Koltsov */
public class ScriptDescriptor extends DeclarationDescriptorNonRootImpl {
  private static final Name NAME = Name.special("<script>");

  private final int priority;

  private JetType returnType;
  private List<ValueParameterDescriptor> valueParameters;

  private final ScriptCodeDescriptor scriptCodeDescriptor = new ScriptCodeDescriptor(this);
  private final ReceiverDescriptor implicitReceiver = new ScriptReceiver(this);

  public ScriptDescriptor(@Nullable DeclarationDescriptor containingDeclaration, int priority) {
    super(containingDeclaration, Collections.<AnnotationDescriptor>emptyList(), NAME);
    this.priority = priority;
  }

  public void initialize(@NotNull JetType returnType) {
    this.returnType = returnType;
    scriptCodeDescriptor.initialize(implicitReceiver, valueParameters, returnType);
  }

  public int getPriority() {
    return priority;
  }

  @NotNull
  public JetType getReturnType() {
    return returnType;
  }

  @NotNull
  public List<ValueParameterDescriptor> getValueParameters() {
    return valueParameters;
  }

  @NotNull
  public ScriptCodeDescriptor getScriptCodeDescriptor() {
    return scriptCodeDescriptor;
  }

  @NotNull
  public ReceiverDescriptor getImplicitReceiver() {
    return implicitReceiver;
  }

  @Override
  public DeclarationDescriptor substitute(TypeSubstitutor substitutor) {
    throw new IllegalStateException("nothing to substitute in script");
  }

  @Override
  public <R, D> R accept(DeclarationDescriptorVisitor<R, D> visitor, D data) {
    return visitor.visitScriptDescriptor(this, data);
  }

  public void setValueParameters(@NotNull List<ValueParameterDescriptor> valueParameters) {
    this.valueParameters = valueParameters;
  }
}
 public ErrorSimpleFunctionDescriptorImpl(ErrorUtils.ErrorScope ownerScope) {
   super(
       ErrorUtils.getErrorClass(),
       Annotations.EMPTY,
       Name.special("<ERROR FUNCTION>"),
       Kind.DECLARATION);
   this.ownerScope = ownerScope;
 }
  @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
 @Override
 protected Collection<DeclarationDescriptor> computeAllDescriptors() {
   Collection<DeclarationDescriptor> result = super.computeAllDescriptors();
   for (PsiClass nested : declarationProvider.getPsiClass().getInnerClasses()) {
     ContainerUtil.addIfNotNull(result, getNamespace(Name.identifier(nested.getName())));
   }
   return result;
 }
Exemple #18
0
 @NotNull
 public static TypeParameterDescriptor createErrorTypeParameter(
     int index, @NotNull String debugMessage) {
   return TypeParameterDescriptorImpl.createWithDefaultBound(
       ERROR_CLASS,
       Annotations.EMPTY,
       false,
       Variance.INVARIANT,
       Name.special("<ERROR: " + debugMessage + ">"),
       index);
 }
  @NotNull
  public static SimpleFunctionDescriptor createSamConstructorFunction(
      @NotNull ClassOrNamespaceDescriptor owner, @NotNull ClassDescriptor samInterface) {
    assert isSamInterface(samInterface) : samInterface;

    SimpleFunctionDescriptorImpl result =
        new SimpleFunctionDescriptorImpl(
            owner,
            samInterface.getAnnotations(),
            samInterface.getName(),
            CallableMemberDescriptor.Kind.SYNTHESIZED);

    TypeParameters typeParameters =
        recreateAndInitializeTypeParameters(
            samInterface.getTypeConstructor().getParameters(), result);

    JetType parameterTypeUnsubstituted = getFunctionTypeForSamType(samInterface.getDefaultType());
    JetType parameterType =
        typeParameters.substitutor.substitute(parameterTypeUnsubstituted, Variance.IN_VARIANCE);
    assert parameterType != null
        : "couldn't substitute type: "
            + parameterType
            + ", substitutor = "
            + typeParameters.substitutor;
    ValueParameterDescriptor parameter =
        new ValueParameterDescriptorImpl(
            result,
            0,
            Collections.<AnnotationDescriptor>emptyList(),
            Name.identifier("function"),
            parameterType,
            false,
            null);

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

    result.initialize(
        null,
        null,
        typeParameters.descriptors,
        Arrays.asList(parameter),
        returnType,
        Modality.FINAL,
        samInterface.getVisibility(),
        false);

    return result;
  }
 public ModuleDescriptorImpl(
     @NotNull Name name,
     @NotNull List<ImportPath> defaultImports,
     @NotNull PlatformToKotlinClassMap platformToKotlinClassMap) {
   super(Annotations.EMPTY, name);
   if (!name.isSpecial()) {
     throw new IllegalArgumentException("module name must be special: " + name);
   }
   this.defaultImports = defaultImports;
   this.platformToKotlinClassMap = platformToKotlinClassMap;
 }
  public void testSinglePackageFunction() {
    myFixture.configureByText(JetFileType.INSTANCE, "package test.testing\n" + "fun some() {}");
    StubPackageMemberDeclarationProvider provider =
        new StubPackageMemberDeclarationProvider(
            new FqName("test.testing"), getProject(), GlobalSearchScope.projectScope(getProject()));

    List<JetNamedFunction> some =
        Lists.newArrayList(provider.getFunctionDeclarations(Name.identifier("some")));

    assertSize(1, some);
    assertEquals("fun some() {}", some.get(0).getText());
  }
  public void testPackageProperty() {
    myFixture.configureByText(JetFileType.INSTANCE, "package test.testing\n" + "val test = 12\n");

    StubPackageMemberDeclarationProvider provider =
        new StubPackageMemberDeclarationProvider(
            new FqName("test.testing"), getProject(), GlobalSearchScope.projectScope(getProject()));

    List<JetProperty> testProperties =
        Lists.newArrayList(provider.getPropertyDeclarations(Name.identifier("test")));

    assertSize(1, testProperties);
    assertEquals("val test = 12", testProperties.get(0).getText());
  }
  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();
  }
 public void initializeDefault() {
   assert parameter == null;
   parameter =
       new ValueParameterDescriptorImpl(
           this,
           0,
           Collections.<AnnotationDescriptor>emptyList(),
           Name.special("<set-?>"),
           false,
           getCorrespondingProperty().getReturnType(),
           false,
           null);
 }
  @Test
  public void testJetStandardLibrary() throws Exception {
    List<JetFile> files = Lists.newArrayList();
    addJetFilesFromDir(files, new File("compiler/frontend/src/jet"));

    final Map<FqName, Name> aliases =
        ImmutableMap.<FqName, Name>builder()
            .put(new FqName("jet.Unit"), Name.identifier("Tuple0"))
            .build();

    ModuleDescriptor lazyModule = new ModuleDescriptor(Name.special("<lazy module>"));
    ResolveSession session =
        new ResolveSession(
            getProject(),
            lazyModule,
            new SpecialModuleConfiguration(),
            new FileBasedDeclarationProviderFactory(files),
            new Function<FqName, Name>() {
              @Override
              public Name fun(FqName name) {
                return aliases.get(name);
              }
            },
            Predicates.in(
                Sets.newHashSet(new FqNameUnsafe("jet.Any"), new FqNameUnsafe("jet.Nothing"))),
            new BindingTraceContext());

    NamespaceDescriptor jetNamespaceFromJSL =
        (NamespaceDescriptor) KotlinBuiltIns.getInstance().getInt().getContainingDeclaration();
    NamespaceDescriptor jetNamespaceFromLazy =
        lazyModule.getRootNamespace().getMemberScope().getNamespace(jetNamespaceFromJSL.getName());

    NamespaceComparator.compareNamespaces(
        jetNamespaceFromJSL,
        jetNamespaceFromLazy,
        NamespaceComparator.RECURSIVE,
        new File("compiler/testData/builtin-classes.txt"));
  }
Exemple #26
0
  @Nullable
  public static Name getAliasName(@NotNull JetImportDirective importDirective) {
    String aliasName = importDirective.getAliasName();
    JetExpression importedReference = importDirective.getImportedReference();
    if (importedReference == null) {
      return null;
    }
    JetSimpleNameExpression referenceExpression = getLastReference(importedReference);
    if (aliasName == null) {
      aliasName = referenceExpression != null ? referenceExpression.getReferencedName() : null;
    }

    return aliasName != null && !aliasName.isEmpty() ? Name.identifier(aliasName) : null;
  }
Exemple #27
0
  /**
   * Add one segment of nesting to given qualified name according to the full qualified name.
   *
   * @param fqn
   * @param fullFQN
   * @return qualified name with one more segment or null if fqn is not head part of fullFQN or
   *     there's no additional segment.
   */
  @Nullable
  public static FqName plusOneSegment(@NotNull FqName fqn, @NotNull FqName fullFQN) {
    if (!isSubpackageOf(fullFQN, fqn)) {
      return null;
    }

    final String nextSegment = getFirstSegment(tail(fqn, fullFQN));

    if (isOneSegmentFQN(nextSegment)) {
      return combine(fqn, Name.guess(nextSegment));
    }

    return null;
  }
Exemple #28
0
 @Nullable
 public static Name getShortName(@NotNull JetAnnotationEntry annotation) {
   JetTypeReference typeReference = annotation.getTypeReference();
   assert typeReference != null : "Annotation entry hasn't typeReference " + annotation.getText();
   JetTypeElement typeElement = typeReference.getTypeElement();
   if (typeElement instanceof JetUserType) {
     JetUserType userType = (JetUserType) typeElement;
     String shortName = userType.getReferencedName();
     if (shortName != null) {
       return Name.identifier(shortName);
     }
   }
   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;
  }
    public void doTest(String path) throws Exception {
      File dir = new File(path);

      CompilerConfiguration configuration =
          JetTestUtils.compilerConfigurationForTests(
              ConfigurationKind.JDK_ONLY, TestJdkKind.MOCK_JDK, new File(dir, "java"));
      configuration.put(
          CommonConfigurationKeys.SOURCE_ROOTS_KEY,
          Arrays.asList(new File(dir, "kotlin").getAbsolutePath()));
      JetCoreEnvironment environment =
          new JetCoreEnvironment(getTestRootDisposable(), configuration);

      ModuleDescriptor moduleDescriptor = new ModuleDescriptor(Name.special("<test module>"));

      // we need the same binding trace for resolve from Java and Kotlin
      BindingTrace trace =
          CliLightClassGenerationSupport.getInstanceForCli(environment.getProject()).getTrace();

      InjectorForJavaDescriptorResolver injectorForJava =
          new InjectorForJavaDescriptorResolver(environment.getProject(), trace, moduleDescriptor);

      InjectorForTopDownAnalyzerForJvm injectorForAnalyzer =
          new InjectorForTopDownAnalyzerForJvm(
              environment.getProject(),
              new TopDownAnalysisParameters(
                  Predicates.<PsiFile>alwaysFalse(),
                  false,
                  false,
                  Collections.<AnalyzerScriptParameter>emptyList()),
              trace,
              moduleDescriptor);

      injectorForAnalyzer
          .getTopDownAnalyzer()
          .analyzeFiles(
              environment.getSourceFiles(), Collections.<AnalyzerScriptParameter>emptyList());

      JavaDescriptorResolver javaDescriptorResolver = injectorForJava.getJavaDescriptorResolver();
      NamespaceDescriptor namespaceDescriptor =
          javaDescriptorResolver.resolveNamespace(
              LoadDescriptorUtil.TEST_PACKAGE_FQNAME, DescriptorSearchRule.INCLUDE_KOTLIN);
      assert namespaceDescriptor != null;

      compareNamespaceWithFile(
          namespaceDescriptor,
          NamespaceComparator.DONT_INCLUDE_METHODS_OF_OBJECT,
          new File(dir, "expected.txt"));

      ExpectedLoadErrorsUtil.checkForLoadErrors(namespaceDescriptor, trace.getBindingContext());
    }