JavaDescriptorResolver.java 50.5 KB
Newer Older
1 2
package org.jetbrains.jet.lang.resolve.java;

3
import com.google.common.collect.Lists;
A
Andrey Breslav 已提交
4
import com.google.common.collect.Maps;
A
Andrey Breslav 已提交
5
import com.google.common.collect.Sets;
6
import com.intellij.openapi.project.Project;
7
import com.intellij.openapi.vfs.VirtualFile;
8
import com.intellij.psi.*;
9
import com.intellij.psi.search.DelegatingGlobalSearchScope;
10
import com.intellij.psi.search.GlobalSearchScope;
11
import jet.typeinfo.TypeInfoVariance;
12 13
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
A
Andrey Breslav 已提交
14
import org.jetbrains.jet.lang.descriptors.*;
A
Andrey Breslav 已提交
15
import org.jetbrains.jet.lang.descriptors.annotations.AnnotationDescriptor;
16
import org.jetbrains.jet.lang.resolve.BindingContext;
17
import org.jetbrains.jet.lang.resolve.DescriptorUtils;
18
import org.jetbrains.jet.lang.types.*;
19
import org.jetbrains.jet.plugin.JetFileType;
20
import org.jetbrains.jet.rt.signature.JetSignatureAdapter;
21 22 23
import org.jetbrains.jet.rt.signature.JetSignatureExceptionsAdapter;
import org.jetbrains.jet.rt.signature.JetSignatureReader;
import org.jetbrains.jet.rt.signature.JetSignatureVisitor;
24 25 26 27 28 29 30

import java.util.*;

/**
 * @author abreslav
 */
public class JavaDescriptorResolver {
31 32
    
    public static String JAVA_ROOT = "<java_root>";
33

34 35
    /*package*/ static final DeclarationDescriptor JAVA_METHOD_TYPE_PARAMETER_PARENT = new DeclarationDescriptorImpl(null, Collections.<AnnotationDescriptor>emptyList(), "<java_generic_method>") {

36 37
        @Override
        public DeclarationDescriptor substitute(TypeSubstitutor substitutor) {
38
            throw new UnsupportedOperationException();
39 40
        }

41 42
        @Override
        public <R, D> R accept(DeclarationDescriptorVisitor<R, D> visitor, D data) {
43
            return visitor.visitDeclarationDescriptor(this, data);
44 45 46
        }
    };

A
Andrey Breslav 已提交
47
    /*package*/ static final DeclarationDescriptor JAVA_CLASS_OBJECT = new DeclarationDescriptorImpl(null, Collections.<AnnotationDescriptor>emptyList(), "<java_class_object_emulation>") {
A
Andrey Breslav 已提交
48 49 50
        @NotNull
        @Override
        public DeclarationDescriptor substitute(TypeSubstitutor substitutor) {
51
            throw new UnsupportedOperationException();
A
Andrey Breslav 已提交
52 53 54 55 56 57 58
        }

        @Override
        public <R, D> R accept(DeclarationDescriptorVisitor<R, D> visitor, D data) {
            return visitor.visitDeclarationDescriptor(this, data);
        }
    };
59 60 61 62 63 64 65 66 67
    
    private enum TypeParameterDescriptorOrigin {
        JAVA,
        KOTLIN,
    }
    
    private static class TypeParameterDescriptorInitialization {
        private final TypeParameterDescriptorOrigin origin;
        private final TypeParameterDescriptor descriptor;
68 69 70 71
        @Nullable
        private final List<JetType> upperBoundsForKotlin;
        @Nullable
        private final List<JetType> lowerBoundsForKotlin;
72

73 74
        private TypeParameterDescriptorInitialization(TypeParameterDescriptor descriptor) {
            this.origin = TypeParameterDescriptorOrigin.JAVA;
75
            this.descriptor = descriptor;
76 77 78 79 80 81 82 83 84 85
            this.upperBoundsForKotlin = null;
            this.lowerBoundsForKotlin = null;
        }

        private TypeParameterDescriptorInitialization(TypeParameterDescriptor descriptor,
                List<JetType> upperBoundsForKotlin, List<JetType> lowerBoundsForKotlin) {
            this.origin = TypeParameterDescriptorOrigin.KOTLIN;
            this.descriptor = descriptor;
            this.upperBoundsForKotlin = upperBoundsForKotlin;
            this.lowerBoundsForKotlin = lowerBoundsForKotlin;
86 87
        }
    }
A
Andrey Breslav 已提交
88

89 90 91 92 93 94 95 96 97 98
    private static class ResolverClassData {
        private JavaClassDescriptor classDescriptor;
        private boolean kotlin;

        @NotNull
        public ClassDescriptor getClassDescriptor() {
            return classDescriptor;
        }
    }

99 100 101 102 103 104 105 106 107 108
    private static class ResolverNamespaceData {
        private JavaNamespaceDescriptor namespaceDescriptor;
        private boolean kotlin;

        @NotNull
        public NamespaceDescriptor getNamespaceDescriptor() {
            return namespaceDescriptor;
        }
    }

109
    protected final Map<String, ResolverClassData> classDescriptorCache = Maps.newHashMap();
110 111 112
    protected final Map<String, ResolverNamespaceData> namespaceDescriptorCacheByFqn = Maps.newHashMap();
    protected final Map<PsiElement, ResolverNamespaceData> namespaceDescriptorCache = Maps.newHashMap();

113
    protected final Map<PsiTypeParameter, TypeParameterDescriptorInitialization> typeParameterDescriptorCache = Maps.newHashMap();
A
Andrey Breslav 已提交
114
    protected final Map<PsiMethod, FunctionDescriptor> methodDescriptorCache = Maps.newHashMap();
A
Andrey Breslav 已提交
115
    protected final Map<PsiField, VariableDescriptor> fieldDescriptorCache = Maps.newHashMap();
116 117 118 119 120 121
    protected final JavaPsiFacade javaFacade;
    protected final GlobalSearchScope javaSearchScope;
    protected final JavaSemanticServices semanticServices;

    public JavaDescriptorResolver(Project project, JavaSemanticServices semanticServices) {
        this.javaFacade = JavaPsiFacade.getInstance(project);
122 123 124 125 126 127
        this.javaSearchScope = new DelegatingGlobalSearchScope(GlobalSearchScope.allScope(project)) {
            @Override
            public boolean contains(VirtualFile file) {
                return myBaseScope.contains(file) && file.getFileType() != JetFileType.INSTANCE;
            }
        };
128 129 130
        this.semanticServices = semanticServices;
    }

131
    @Nullable
132 133
    public ClassDescriptor resolveClass(@NotNull PsiClass psiClass) {
        String qualifiedName = psiClass.getQualifiedName();
134 135 136 137 138
        
        if (qualifiedName.endsWith(JvmAbi.TRAIT_IMPL_SUFFIX)) {
            // TODO: only if -$$TImpl class is created by Kotlin
            return null;
        }
139

140
        // First, let's check that this is a real Java class, not a Java's view on a Kotlin class:
141 142 143 144 145
        ClassDescriptor kotlinClassDescriptor = semanticServices.getKotlinClassDescriptor(qualifiedName);
        if (kotlinClassDescriptor != null) {
            return kotlinClassDescriptor;
        }

146
        // Not let's take a descriptor of a Java class
147 148 149 150
        ResolverClassData classData = classDescriptorCache.get(qualifiedName);
        if (classData == null) {
            classData = createJavaClassDescriptor(psiClass);
            classDescriptorCache.put(qualifiedName, classData);
151
        }
152
        return classData.getClassDescriptor();
153 154 155 156
    }

    @Nullable
    public ClassDescriptor resolveClass(@NotNull String qualifiedName) {
157 158 159 160 161 162
        
        if (qualifiedName.endsWith(JvmAbi.TRAIT_IMPL_SUFFIX)) {
            // TODO: only if -$$TImpl class is created by Kotlin
            return null;
        }
        
163
        // First, let's check that this is a real Java class, not a Java's view on a Kotlin class:
164 165 166 167 168
        ClassDescriptor kotlinClassDescriptor = semanticServices.getKotlinClassDescriptor(qualifiedName);
        if (kotlinClassDescriptor != null) {
            return kotlinClassDescriptor;
        }

169
        // Not let's take a descriptor of a Java class
170 171
        ResolverClassData classData = classDescriptorCache.get(qualifiedName);
        if (classData == null) {
172
            PsiClass psiClass = findClass(qualifiedName);
173 174 175
            if (psiClass == null) {
                return null;
            }
176
            classData = createJavaClassDescriptor(psiClass);
177
        }
178
        return classData.getClassDescriptor();
179 180
    }

181
    private ResolverClassData createJavaClassDescriptor(@NotNull final PsiClass psiClass) {
A
Andrey Breslav 已提交
182 183 184
        assert !classDescriptorCache.containsKey(psiClass.getQualifiedName()) : psiClass.getQualifiedName();
        classDescriptorCache.put(psiClass.getQualifiedName(), null); // TODO

185
        String name = psiClass.getName();
186 187
        ResolverClassData classData = new ResolverClassData();
        classData.classDescriptor = new JavaClassDescriptor(
188
                resolveParentDescriptor(psiClass), psiClass.isInterface() ? ClassKind.TRAIT : ClassKind.CLASS
189
        );
190
        classData.classDescriptor.setName(name);
191
        
192 193 194 195 196 197 198 199 200
        class OuterClassTypeVariableResolver implements TypeVariableResolver {

            @NotNull
            @Override
            public TypeParameterDescriptor getTypeVariable(@NotNull String name) {
                throw new IllegalStateException("not implemented"); // TODO
            }
        }

A
Andrey Breslav 已提交
201
        List<JetType> supertypes = new ArrayList<JetType>();
202 203 204
        List<TypeParameterDescriptor> typeParameters = resolveClassTypeParameters(psiClass, classData, new OuterClassTypeVariableResolver());
        classData.classDescriptor.setTypeConstructor(new TypeConstructorImpl(
                classData.classDescriptor,
A
Andrey Breslav 已提交
205
                Collections.<AnnotationDescriptor>emptyList(), // TODO
206
                // TODO
207
                psiClass.hasModifierProperty(PsiModifier.FINAL),
A
Andrey Breslav 已提交
208
                name,
A
Andrey Breslav 已提交
209
                typeParameters,
A
Andrey Breslav 已提交
210 211
                supertypes
        ));
212
        classData.classDescriptor.setModality(Modality.convertFromFlags(
213 214
                psiClass.hasModifierProperty(PsiModifier.ABSTRACT) || psiClass.isInterface(),
                !psiClass.hasModifierProperty(PsiModifier.FINAL))
A
Andrey Breslav 已提交
215
        );
216 217 218
        classData.classDescriptor.setVisibility(resolveVisibilityFromPsiModifiers(psiClass));
        classDescriptorCache.put(psiClass.getQualifiedName(), classData);
        classData.classDescriptor.setUnsubstitutedMemberScope(new JavaClassMembersScope(classData.classDescriptor, psiClass, semanticServices, false));
219

220 221
        // UGLY HACK (Andrey Breslav is not sure what did he mean)
        initializeTypeParameters(psiClass);
222

A
Andrey Breslav 已提交
223
        supertypes.addAll(getSupertypes(psiClass));
224
        if (psiClass.isInterface()) {
225
            classData.classDescriptor.setSuperclassType(JetStandardClasses.getAnyType()); // TODO : Make it java.lang.Object
226 227 228 229 230 231 232
        }
        else {
            PsiClassType[] extendsListTypes = psiClass.getExtendsListTypes();
            assert extendsListTypes.length == 0 || extendsListTypes.length == 1;
            JetType superclassType = extendsListTypes.length == 0
                                            ? JetStandardClasses.getAnyType()
                                            : semanticServices.getTypeTransformer().transformToType(extendsListTypes[0]);
233
            classData.classDescriptor.setSuperclassType(superclassType);
234
        }
A
Andrey Breslav 已提交
235 236

        PsiMethod[] psiConstructors = psiClass.getConstructors();
237 238

        if (psiConstructors.length == 0) {
A
Andrey Breslav 已提交
239 240 241 242 243
            // We need to create default constructors for classes and abstract classes.
            // Example:
            // class Kotlin() : Java() {}
            // abstract public class Java {}
            if (!psiClass.isInterface()) {
244
                ConstructorDescriptorImpl constructorDescriptor = new ConstructorDescriptorImpl(
245
                        classData.classDescriptor,
A
Andrey Breslav 已提交
246
                        Collections.<AnnotationDescriptor>emptyList(),
247
                        false);
248 249 250
                constructorDescriptor.initialize(typeParameters, Collections.<ValueParameterDescriptor>emptyList(), Modality.FINAL, classData.classDescriptor.getVisibility());
                constructorDescriptor.setReturnType(classData.classDescriptor.getDefaultType());
                classData.classDescriptor.addConstructor(constructorDescriptor);
251
                semanticServices.getTrace().record(BindingContext.CONSTRUCTOR, psiClass, constructorDescriptor);
252 253 254 255 256
            }
        }
        else {
            for (PsiMethod constructor : psiConstructors) {
                ConstructorDescriptorImpl constructorDescriptor = new ConstructorDescriptorImpl(
257
                        classData.classDescriptor,
A
Andrey Breslav 已提交
258
                        Collections.<AnnotationDescriptor>emptyList(), // TODO
259
                        false);
260 261 262 263
                ValueParameterDescriptors valueParameterDescriptors = resolveParameterDescriptors(constructorDescriptor,
                        constructor.getParameterList().getParameters(),
                        new TypeParameterListTypeVariableResolver(typeParameters) // TODO: outer too
                    );
264 265 266 267
                if (valueParameterDescriptors.receiverType != null) {
                    throw new IllegalStateException();
                }
                constructorDescriptor.initialize(typeParameters, valueParameterDescriptors.descriptors, Modality.FINAL,
268
                                                 resolveVisibilityFromPsiModifiers(constructor));
269 270
                constructorDescriptor.setReturnType(classData.classDescriptor.getDefaultType());
                classData.classDescriptor.addConstructor(constructorDescriptor);
271
                semanticServices.getTrace().record(BindingContext.CONSTRUCTOR, constructor, constructorDescriptor);
272
            }
A
Andrey Breslav 已提交
273
        }
274

275
        semanticServices.getTrace().record(BindingContext.CLASS, psiClass, classData.classDescriptor);
276

277
        return classData;
278 279
    }

280
    private List<TypeParameterDescriptor> resolveClassTypeParameters(PsiClass psiClass, ResolverClassData classData, TypeVariableResolver typeVariableResolver) {
281
        for (PsiAnnotation annotation : psiClass.getModifierList().getAnnotations()) {
S
Stepan Koltsov 已提交
282
            if (annotation.getQualifiedName().equals(JvmStdlibNames.JET_CLASS.getFqName())) {
283
                classData.kotlin = true;
S
Stepan Koltsov 已提交
284
                PsiLiteralExpression attributeValue = (PsiLiteralExpression) annotation.findAttributeValue(JvmStdlibNames.JET_CLASS_SIGNATURE);
285 286 287
                if (attributeValue != null) {
                    String typeParametersString = (String) attributeValue.getValue();
                    if (typeParametersString != null) {
288
                        return resolveClassTypeParametersFromJetSignature(typeParametersString, psiClass, classData.classDescriptor, typeVariableResolver);
289 290 291 292
                    }
                }
            }
        }
293
        return makeUninitializedTypeParameters(classData.classDescriptor, psiClass.getTypeParameters());
294 295
    }

296
    @NotNull
297
    private PsiTypeParameter getPsiTypeParameterByName(PsiTypeParameterListOwner clazz, String name) {
298 299 300 301 302
        for (PsiTypeParameter typeParameter : clazz.getTypeParameters()) {
            if (typeParameter.getName().equals(name)) {
                return typeParameter; 
            }
        }
303 304 305
        throw new IllegalStateException("PsiTypeParameter '" + name + "' is not found");
    }

S
Stepan Koltsov 已提交
306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322

    // cache
    protected ClassDescriptor javaLangObject;

    @NotNull
    private ClassDescriptor getJavaLangObject() {
        if (javaLangObject == null) {
            javaLangObject = resolveClass("java.lang.Object");
        }
        return javaLangObject;
    }

    private boolean isJavaLangObject(JetType type) {
        return type.getConstructor().getDeclarationDescriptor() == getJavaLangObject();
    }


323 324 325 326 327 328
    private abstract class JetSignatureTypeParameterVisitor extends JetSignatureExceptionsAdapter {
        
        private final DeclarationDescriptor containingDeclaration;
        private final PsiTypeParameterListOwner psiOwner;
        private final String name;
        private final TypeInfoVariance variance;
329
        private final TypeVariableResolver typeVariableResolver;
330 331

        protected JetSignatureTypeParameterVisitor(DeclarationDescriptor containingDeclaration, PsiTypeParameterListOwner psiOwner,
332
                String name, TypeInfoVariance variance, TypeVariableResolver typeVariableResolver)
333
        {
334 335 336 337
            if (name.isEmpty()) {
                throw new IllegalStateException();
            }
            
338 339 340 341
            this.containingDeclaration = containingDeclaration;
            this.psiOwner = psiOwner;
            this.name = name;
            this.variance = variance;
342
            this.typeVariableResolver = typeVariableResolver;
343 344 345 346 347 348
        }

        int index = 0;

        List<JetType> upperBounds = new ArrayList<JetType>();
        List<JetType> lowerBounds = new ArrayList<JetType>();
S
Stepan Koltsov 已提交
349
        
350 351
        @Override
        public JetSignatureVisitor visitClassBound() {
352
            return new JetTypeJetSignatureReader(JavaDescriptorResolver.this, semanticServices.getJetSemanticServices().getStandardLibrary(), typeVariableResolver) {
353 354
                @Override
                protected void done(@NotNull JetType jetType) {
S
Stepan Koltsov 已提交
355 356 357
                    if (isJavaLangObject(jetType)) {
                        return;
                    }
358 359 360 361 362 363 364
                    upperBounds.add(jetType);
                }
            };
        }

        @Override
        public JetSignatureVisitor visitInterfaceBound() {
365
            return new JetTypeJetSignatureReader(JavaDescriptorResolver.this, semanticServices.getJetSemanticServices().getStandardLibrary(), typeVariableResolver) {
366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387
                @Override
                protected void done(@NotNull JetType jetType) {
                    upperBounds.add(jetType);
                }
            };
        }

        @Override
        public void visitFormalTypeParameterEnd() {
            TypeParameterDescriptor typeParameter = TypeParameterDescriptor.createForFurtherModification(
                    containingDeclaration,
                    Collections.<AnnotationDescriptor>emptyList(), // TODO: wrong
                    true, // TODO: wrong
                    JetSignatureUtils.translateVariance(variance),
                    name,
                    ++index);
            PsiTypeParameter psiTypeParameter = getPsiTypeParameterByName(psiOwner, name);
            typeParameterDescriptorCache.put(psiTypeParameter, new TypeParameterDescriptorInitialization(typeParameter, upperBounds, lowerBounds));
            done(typeParameter);
        }
        
        protected abstract void done(TypeParameterDescriptor typeParameterDescriptor);
388 389
    }

390 391 392
    /**
     * @see #resolveMethodTypeParametersFromJetSignature(String, FunctionDescriptor)
     */
393 394
    private List<TypeParameterDescriptor> resolveClassTypeParametersFromJetSignature(String jetSignature, final PsiClass clazz,
            final JavaClassDescriptor classDescriptor, final TypeVariableResolver outerClassTypeVariableResolver) {
395
        final List<TypeParameterDescriptor> r = new ArrayList<TypeParameterDescriptor>();
396 397 398 399 400 401 402 403 404 405 406 407 408 409 410
        
        class MyTypeVariableResolver implements TypeVariableResolver {

            @NotNull
            @Override
            public TypeParameterDescriptor getTypeVariable(@NotNull String name) {
                for (TypeParameterDescriptor typeParameter : r) {
                    if (typeParameter.getName().equals(name)) {
                        return typeParameter;
                    }
                }
                return outerClassTypeVariableResolver.getTypeVariable(name);
            }
        }
        
411 412 413
        new JetSignatureReader(jetSignature).accept(new JetSignatureExceptionsAdapter() {
            @Override
            public JetSignatureVisitor visitFormalTypeParameter(final String name, final TypeInfoVariance variance) {
414
                return new JetSignatureTypeParameterVisitor(classDescriptor, clazz, name, variance, new MyTypeVariableResolver()) {
415
                    @Override
416 417
                    protected void done(TypeParameterDescriptor typeParameterDescriptor) {
                        r.add(typeParameterDescriptor);
418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436
                    }
                };
            }

            @Override
            public JetSignatureVisitor visitSuperclass() {
                // TODO
                return new JetSignatureAdapter();
            }

            @Override
            public JetSignatureVisitor visitInterface() {
                // TODO
                return new JetSignatureAdapter();
            }
        });
        return r;
    }

437 438 439
    private DeclarationDescriptor resolveParentDescriptor(PsiClass psiClass) {
        PsiClass containingClass = psiClass.getContainingClass();
        if (containingClass != null) {
440
            return resolveClass(containingClass);
441 442 443 444 445 446 447
        }
        
        PsiJavaFile containingFile = (PsiJavaFile) psiClass.getContainingFile();
        String packageName = containingFile.getPackageName();
        return resolveNamespace(packageName);
    }

448
    private List<TypeParameterDescriptor> makeUninitializedTypeParameters(@NotNull DeclarationDescriptor containingDeclaration, @NotNull PsiTypeParameter[] typeParameters) {
449 450
        List<TypeParameterDescriptor> result = Lists.newArrayList();
        for (PsiTypeParameter typeParameter : typeParameters) {
451
            TypeParameterDescriptor typeParameterDescriptor = makeUninitializedTypeParameter(containingDeclaration, typeParameter);
A
Andrey Breslav 已提交
452
            result.add(typeParameterDescriptor);
453 454 455 456
        }
        return result;
    }

457 458 459
    @NotNull
    private TypeParameterDescriptor makeUninitializedTypeParameter(@NotNull DeclarationDescriptor containingDeclaration, @NotNull PsiTypeParameter psiTypeParameter) {
        assert typeParameterDescriptorCache.get(psiTypeParameter) == null : psiTypeParameter.getText();
460
        TypeParameterDescriptor typeParameterDescriptor = TypeParameterDescriptor.createForFurtherModification(
461
                containingDeclaration,
A
Andrey Breslav 已提交
462
                Collections.<AnnotationDescriptor>emptyList(), // TODO
A
Andrey Breslav 已提交
463
                false,
464
                Variance.INVARIANT,
465 466
                psiTypeParameter.getName(),
                psiTypeParameter.getIndex()
467
        );
468
        typeParameterDescriptorCache.put(psiTypeParameter, new TypeParameterDescriptorInitialization(typeParameterDescriptor));
469 470 471
        return typeParameterDescriptor;
    }

472 473 474
    private void initializeTypeParameter(PsiTypeParameter typeParameter, TypeParameterDescriptorInitialization typeParameterDescriptorInitialization) {
        TypeParameterDescriptor typeParameterDescriptor = typeParameterDescriptorInitialization.descriptor;
        if (typeParameterDescriptorInitialization.origin == TypeParameterDescriptorOrigin.KOTLIN) {
475 476 477 478 479 480 481 482 483 484
            List<?> upperBounds = typeParameterDescriptorInitialization.upperBoundsForKotlin;
            if (upperBounds.size() == 0){
                typeParameterDescriptor.addUpperBound(JetStandardClasses.getNullableAnyType());
            } else {
                for (JetType upperBound : typeParameterDescriptorInitialization.upperBoundsForKotlin) {
                    typeParameterDescriptor.addUpperBound(upperBound);
                }
            }

            // TODO: lower bounds
485 486 487 488 489 490 491 492 493 494 495 496
        } else {
            PsiClassType[] referencedTypes = typeParameter.getExtendsList().getReferencedTypes();
            if (referencedTypes.length == 0){
                typeParameterDescriptor.addUpperBound(JetStandardClasses.getNullableAnyType());
            }
            else if (referencedTypes.length == 1) {
                typeParameterDescriptor.addUpperBound(semanticServices.getTypeTransformer().transformToType(referencedTypes[0]));
            }
            else {
                for (PsiClassType referencedType : referencedTypes) {
                    typeParameterDescriptor.addUpperBound(semanticServices.getTypeTransformer().transformToType(referencedType));
                }
A
Andrey Breslav 已提交
497 498
            }
        }
499
        typeParameterDescriptor.setInitialized();
500 501 502 503
    }

    private void initializeTypeParameters(PsiTypeParameterListOwner typeParameterListOwner) {
        for (PsiTypeParameter psiTypeParameter : typeParameterListOwner.getTypeParameters()) {
504
            initializeTypeParameter(psiTypeParameter, resolveTypeParameterInitialization(psiTypeParameter));
505
        }
A
Andrey Breslav 已提交
506 507 508
    }

    @NotNull
509 510
    private TypeParameterDescriptorInitialization resolveTypeParameter(@NotNull DeclarationDescriptor containingDeclaration, @NotNull PsiTypeParameter psiTypeParameter) {
        TypeParameterDescriptorInitialization typeParameterDescriptor = typeParameterDescriptorCache.get(psiTypeParameter);
511
        assert typeParameterDescriptor != null : psiTypeParameter.getText();
A
Andrey Breslav 已提交
512 513 514
        return typeParameterDescriptor;
    }

A
Andrey Breslav 已提交
515 516
    private Collection<? extends JetType> getSupertypes(PsiClass psiClass) {
        List<JetType> result = new ArrayList<JetType>();
517 518 519 520 521 522
        result.add(JetStandardClasses.getAnyType());
        transformSupertypeList(result, psiClass.getExtendsListTypes());
        transformSupertypeList(result, psiClass.getImplementsListTypes());
        return result;
    }

A
Andrey Breslav 已提交
523
    private void transformSupertypeList(List<JetType> result, PsiClassType[] extendsListTypes) {
524
        for (PsiClassType type : extendsListTypes) {
A
Andrey Breslav 已提交
525
            JetType transform = semanticServices.getTypeTransformer().transformToType(type);
526 527 528 529 530

            result.add(TypeUtils.makeNotNullable(transform));
        }
    }

531
    public NamespaceDescriptor resolveNamespace(String qualifiedName) {
532
        PsiPackage psiPackage = findPackage(qualifiedName);
533
        if (psiPackage == null) {
534
            PsiClass psiClass = findClass(qualifiedName);
A
Andrey Breslav 已提交
535 536
            if (psiClass == null) return null;
            return resolveNamespace(psiClass);
537 538 539 540
        }
        return resolveNamespace(psiPackage);
    }

541 542 543 544
    private PsiClass findClass(String qualifiedName) {
        return javaFacade.findClass(qualifiedName, javaSearchScope);
    }

545
    /*package*/ PsiPackage findPackage(String qualifiedName) {
546 547 548
        return javaFacade.findPackage(qualifiedName);
    }

549
    private NamespaceDescriptor resolveNamespace(@NotNull PsiPackage psiPackage) {
550 551 552 553 554
        ResolverNamespaceData namespaceData = namespaceDescriptorCache.get(psiPackage);
        if (namespaceData == null) {
            namespaceData = createJavaNamespaceDescriptor(psiPackage);
            namespaceDescriptorCache.put(psiPackage, namespaceData);
            namespaceDescriptorCacheByFqn.put(psiPackage.getQualifiedName(), namespaceData);
555
        }
556
        return namespaceData.namespaceDescriptor;
557 558
    }

A
Andrey Breslav 已提交
559
    private NamespaceDescriptor resolveNamespace(@NotNull PsiClass psiClass) {
560 561 562 563 564
        ResolverNamespaceData namespaceData = namespaceDescriptorCache.get(psiClass);
        if (namespaceData == null) {
            namespaceData = createJavaNamespaceDescriptor(psiClass);
            namespaceDescriptorCache.put(psiClass, namespaceData);
            namespaceDescriptorCacheByFqn.put(psiClass.getQualifiedName(), namespaceData);
A
Andrey Breslav 已提交
565
        }
566
        return namespaceData.namespaceDescriptor;
A
Andrey Breslav 已提交
567 568
    }

569 570
    private ResolverNamespaceData createJavaNamespaceDescriptor(@NotNull PsiPackage psiPackage) {
        ResolverNamespaceData namespaceData = new ResolverNamespaceData();
571
        String name = psiPackage.getName();
572
        namespaceData.namespaceDescriptor = new JavaNamespaceDescriptor(
573
                resolveParentDescriptor(psiPackage),
A
Andrey Breslav 已提交
574
                Collections.<AnnotationDescriptor>emptyList(), // TODO
575 576
                name == null ? JAVA_ROOT : name,
                name == null ? JAVA_ROOT : psiPackage.getQualifiedName()
577
        );
578

579 580 581 582 583
        namespaceData.namespaceDescriptor.setMemberScope(new JavaPackageScope(psiPackage.getQualifiedName(), namespaceData.namespaceDescriptor, semanticServices));
        semanticServices.getTrace().record(BindingContext.NAMESPACE, psiPackage, namespaceData.namespaceDescriptor);
        // TODO: hack
        namespaceData.kotlin = true;
        return namespaceData;
584 585
    }

586 587 588 589 590 591 592 593
    private DeclarationDescriptor resolveParentDescriptor(@NotNull PsiPackage psiPackage) {
        PsiPackage parentPackage = psiPackage.getParentPackage();
        if (parentPackage == null) {
            return null;
        }
        return resolveNamespace(parentPackage);
    }

594 595 596
    private ResolverNamespaceData createJavaNamespaceDescriptor(@NotNull final PsiClass psiClass) {
        ResolverNamespaceData namespaceData = new ResolverNamespaceData();
        namespaceData.namespaceDescriptor = new JavaNamespaceDescriptor(
597
                resolveParentDescriptor(psiClass),
A
Andrey Breslav 已提交
598
                Collections.<AnnotationDescriptor>emptyList(), // TODO
599 600
                psiClass.getName(),
                psiClass.getQualifiedName()
601
        );
602 603 604
        namespaceData.namespaceDescriptor.setMemberScope(new JavaClassMembersScope(namespaceData.namespaceDescriptor, psiClass, semanticServices, true));
        semanticServices.getTrace().record(BindingContext.NAMESPACE, psiClass, namespaceData.namespaceDescriptor);
        return namespaceData;
605
    }
606 607 608 609 610 611 612 613 614 615
    
    private static class ValueParameterDescriptors {
        private final JetType receiverType;
        private final List<ValueParameterDescriptor> descriptors;

        private ValueParameterDescriptors(@Nullable JetType receiverType, List<ValueParameterDescriptor> descriptors) {
            this.receiverType = receiverType;
            this.descriptors = descriptors;
        }
    }
616

617 618
    public ValueParameterDescriptors resolveParameterDescriptors(DeclarationDescriptor containingDeclaration,
            PsiParameter[] parameters, TypeVariableResolver typeVariableResolver) {
619
        List<ValueParameterDescriptor> result = new ArrayList<ValueParameterDescriptor>();
620
        JetType receiverType = null;
621 622
        for (int i = 0, parametersLength = parameters.length; i < parametersLength; i++) {
            PsiParameter parameter = parameters[i];
623
            JvmMethodParameterMeaning meaning = resolveParameterDescriptor(containingDeclaration, i, parameter, typeVariableResolver);
624 625 626 627 628 629 630 631 632
            if (meaning.kind == JvmMethodParameterKind.TYPE_INFO) {
                // TODO
            } else if (meaning.kind == JvmMethodParameterKind.REGULAR) {
                result.add(meaning.valueParameterDescriptor);
            } else if (meaning.kind == JvmMethodParameterKind.RECEIVER) {
                if (receiverType != null) {
                    throw new IllegalStateException("more then one receiver");
                }
                receiverType = meaning.receiverType;
S
Stepan Koltsov 已提交
633
            }
634
        }
635
        return new ValueParameterDescriptors(receiverType, result);
636
    }
A
Andrey Breslav 已提交
637

638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670
    private enum JvmMethodParameterKind {
        REGULAR,
        RECEIVER,
        TYPE_INFO,
    }
    
    private static class JvmMethodParameterMeaning {
        private final JvmMethodParameterKind kind;
        private final JetType receiverType;
        private final ValueParameterDescriptor valueParameterDescriptor;
        private final Object typeInfo;

        private JvmMethodParameterMeaning(JvmMethodParameterKind kind, JetType receiverType, ValueParameterDescriptor valueParameterDescriptor, Object typeInfo) {
            this.kind = kind;
            this.receiverType = receiverType;
            this.valueParameterDescriptor = valueParameterDescriptor;
            this.typeInfo = typeInfo;
        }
        
        public static JvmMethodParameterMeaning receiver(@NotNull JetType receiverType) {
            return new JvmMethodParameterMeaning(JvmMethodParameterKind.RECEIVER, receiverType, null, null);
        }
        
        public static JvmMethodParameterMeaning regular(@NotNull ValueParameterDescriptor valueParameterDescriptor) {
            return new JvmMethodParameterMeaning(JvmMethodParameterKind.REGULAR, null, valueParameterDescriptor, null);
        }
        
        public static JvmMethodParameterMeaning typeInfo(@NotNull Object typeInfo) {
            return new JvmMethodParameterMeaning(JvmMethodParameterKind.TYPE_INFO, null, null, typeInfo);
        }
    }

    @NotNull
671 672
    private JvmMethodParameterMeaning resolveParameterDescriptor(DeclarationDescriptor containingDeclaration, int i,
            PsiParameter parameter, TypeVariableResolver typeVariableResolver) {
673 674 675 676 677 678 679 680 681 682
        PsiType psiType = parameter.getType();

        JetType varargElementType;
        if (psiType instanceof PsiEllipsisType) {
            PsiEllipsisType psiEllipsisType = (PsiEllipsisType) psiType;
            varargElementType = semanticServices.getTypeTransformer().transformToType(psiEllipsisType.getComponentType());
        }
        else {
            varargElementType = null;
        }
683 684 685

        boolean changeNullable = false;
        boolean nullable = true;
S
Stepan Koltsov 已提交
686
        String typeFromAnnotation = null;
687
        
688
        boolean receiver = false;
689
        boolean hasDefaultValue = false;
690
        
691 692 693 694
        // TODO: must be very slow, make it lazy?
        String name = parameter.getName() != null ? parameter.getName() : "p" + i;
        for (PsiAnnotation annotation : parameter.getModifierList().getAnnotations()) {

S
Stepan Koltsov 已提交
695 696
            if (annotation.getQualifiedName().equals(JvmStdlibNames.JET_VALUE_PARAMETER.getFqName())) {
                PsiLiteralExpression nameExpression = (PsiLiteralExpression) annotation.findAttributeValue(JvmStdlibNames.JET_VALUE_PARAMETER_NAME_FIELD);
697 698 699 700
                if (nameExpression != null) {
                    name = (String) nameExpression.getValue();
                }
                
S
Stepan Koltsov 已提交
701
                PsiLiteralExpression nullableExpression = (PsiLiteralExpression) annotation.findAttributeValue(JvmStdlibNames.JET_VALUE_PARAMETER_NULLABLE_FIELD);
702 703 704 705 706 707 708
                if (nullableExpression != null) {
                    nullable = (Boolean) nullableExpression.getValue();
                } else {
                    // default value of parameter
                    nullable = false;
                    changeNullable = true;
                }
S
Stepan Koltsov 已提交
709
                
S
Stepan Koltsov 已提交
710
                PsiLiteralExpression signatureExpression = (PsiLiteralExpression) annotation.findAttributeValue(JvmStdlibNames.JET_VALUE_PARAMETER_TYPE_FIELD);
S
Stepan Koltsov 已提交
711 712 713
                if (signatureExpression != null) {
                    typeFromAnnotation = (String) signatureExpression.getValue();
                }
714 715


S
Stepan Koltsov 已提交
716
                PsiLiteralExpression receiverExpression = (PsiLiteralExpression) annotation.findAttributeValue(JvmStdlibNames.JET_VALUE_PARAMETER_RECEIVER_FIELD);
717
                if (receiverExpression != null) {
718
                    receiver = (Boolean) receiverExpression.getValue();
719
                }
720
                
S
Stepan Koltsov 已提交
721
                PsiLiteralExpression hasDefaultValueExpression = (PsiLiteralExpression) annotation.findAttributeValue(JvmStdlibNames.JET_VALUE_PARAMETER_HAS_DEFAULT_VALUE_FIELD);
722 723 724
                if (hasDefaultValueExpression != null) {
                    hasDefaultValue = (Boolean) hasDefaultValueExpression.getValue();
                }
725 726


S
Stepan Koltsov 已提交
727
            } else if (annotation.getQualifiedName().equals(JvmStdlibNames.JET_TYPE_PARAMETER.getFqName())) {
728
                return JvmMethodParameterMeaning.typeInfo(new Object());
729 730 731
            }
        }
        
S
Stepan Koltsov 已提交
732
        JetType outType;
733
        if (typeFromAnnotation != null && typeFromAnnotation.length() > 0) {
734
            outType = semanticServices.getTypeTransformer().transformToType(typeFromAnnotation, typeVariableResolver);
S
Stepan Koltsov 已提交
735 736 737
        } else {
            outType = semanticServices.getTypeTransformer().transformToType(psiType);
        }
738 739 740 741 742 743 744 745
        if (receiver) {
            return JvmMethodParameterMeaning.receiver(outType);
        } else {
            return JvmMethodParameterMeaning.regular(new ValueParameterDescriptorImpl(
                    containingDeclaration,
                    i,
                    Collections.<AnnotationDescriptor>emptyList(), // TODO
                    name,
S
Stepan Koltsov 已提交
746
                    false,
747
                    changeNullable ? TypeUtils.makeNullableAsSpecified(outType, nullable) : outType,
748
                    hasDefaultValue,
749 750 751
                    varargElementType
            ));
        }
752 753
    }

A
Andrey Breslav 已提交
754 755 756 757 758 759 760 761 762
    public VariableDescriptor resolveFieldToVariableDescriptor(DeclarationDescriptor containingDeclaration, PsiField field) {
        VariableDescriptor variableDescriptor = fieldDescriptorCache.get(field);
        if (variableDescriptor != null) {
            return variableDescriptor;
        }
        JetType type = semanticServices.getTypeTransformer().transformToType(field.getType());
        boolean isFinal = field.hasModifierProperty(PsiModifier.FINAL);
        PropertyDescriptor propertyDescriptor = new PropertyDescriptor(
                containingDeclaration,
A
Andrey Breslav 已提交
763
                Collections.<AnnotationDescriptor>emptyList(),
764
                Modality.FINAL,
765
                resolveVisibilityFromPsiModifiers(field),
A
Andrey Breslav 已提交
766 767
                !isFinal,
                null,
768
                DescriptorUtils.getExpectedThisObjectIfNeeded(containingDeclaration),
A
Andrey Breslav 已提交
769 770
                field.getName(),
                type);
771
        semanticServices.getTrace().record(BindingContext.VARIABLE, field, propertyDescriptor);
A
Andrey Breslav 已提交
772 773 774 775
        fieldDescriptorCache.put(field, propertyDescriptor);
        return propertyDescriptor;
    }

A
Andrey Breslav 已提交
776
    @NotNull
A
Andrey Breslav 已提交
777 778
    public Set<FunctionDescriptor> resolveFunctionGroup(@NotNull DeclarationDescriptor owner, @NotNull PsiClass psiClass, @Nullable ClassDescriptor classDescriptor, @NotNull String methodName, boolean staticMembers) {
        Set<FunctionDescriptor> writableFunctionGroup = Sets.newLinkedHashSet();
779
        final Collection<HierarchicalMethodSignature> signatures = psiClass.getVisibleSignatures();
A
Andrey Breslav 已提交
780
        TypeSubstitutor typeSubstitutor = createSubstitutorForGenericSupertypes(classDescriptor);
781
        for (HierarchicalMethodSignature signature: signatures) {
782
            if (!methodName.equals(signature.getName())) {
A
Andrey Breslav 已提交
783 784 785
                 continue;
            }

786
            FunctionDescriptor substitutedFunctionDescriptor = resolveHierarchicalSignatureToFunction(owner, psiClass, staticMembers, typeSubstitutor, signature);
787
            if (substitutedFunctionDescriptor != null) {
A
Andrey Breslav 已提交
788
                writableFunctionGroup.add(substitutedFunctionDescriptor);
789
            }
A
Andrey Breslav 已提交
790 791 792
        }
        return writableFunctionGroup;
    }
A
Andrey Breslav 已提交
793

794 795 796 797 798 799 800 801 802 803 804 805 806 807 808
    @Nullable
    private FunctionDescriptor resolveHierarchicalSignatureToFunction(DeclarationDescriptor owner, PsiClass psiClass, boolean staticMembers, TypeSubstitutor typeSubstitutor, HierarchicalMethodSignature signature) {
        PsiMethod method = signature.getMethod();
        if (method.hasModifierProperty(PsiModifier.STATIC) != staticMembers) {
                return null;
        }
        FunctionDescriptor functionDescriptor = resolveMethodToFunctionDescriptor(owner, psiClass, typeSubstitutor, method);
//        if (functionDescriptor != null && !staticMembers) {
//            for (HierarchicalMethodSignature superSignature : signature.getSuperSignatures()) {
//                ((FunctionDescriptorImpl) functionDescriptor).addOverriddenFunction(resolveHierarchicalSignatureToFunction(owner, superSignature.getMethod().getContainingClass(), false, typeSubstitutor, superSignature));
//            }
//        }
        return functionDescriptor;
    }

A
Andrey Breslav 已提交
809 810 811 812 813 814 815 816 817 818 819
    public TypeSubstitutor createSubstitutorForGenericSupertypes(ClassDescriptor classDescriptor) {
        TypeSubstitutor typeSubstitutor;
        if (classDescriptor != null) {
            typeSubstitutor = TypeUtils.buildDeepSubstitutor(classDescriptor.getDefaultType());
        }
        else {
            typeSubstitutor = TypeSubstitutor.EMPTY;
        }
        return typeSubstitutor;
    }

820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839
    private static class TypeParameterListTypeVariableResolver implements TypeVariableResolver {

        private final List<TypeParameterDescriptor> typeParameters;

        private TypeParameterListTypeVariableResolver(List<TypeParameterDescriptor> typeParameters) {
            this.typeParameters = typeParameters;
        }

        @NotNull
        @Override
        public TypeParameterDescriptor getTypeVariable(@NotNull String name) {
            for (TypeParameterDescriptor typeParameter : typeParameters) {
                if (typeParameter.getName().equals(name)) {
                    return typeParameter;
                }
            }
            throw new IllegalStateException("unresolver variable: " + name); // TODO: report properly
        }
    }

A
Andrey Breslav 已提交
840
    @Nullable
A
Andrey Breslav 已提交
841
    public FunctionDescriptor resolveMethodToFunctionDescriptor(DeclarationDescriptor owner, PsiClass psiClass, TypeSubstitutor typeSubstitutorForGenericSuperclasses, PsiMethod method) {
A
Andrey Breslav 已提交
842 843 844 845 846 847 848 849 850 851 852
        PsiType returnType = method.getReturnType();
        if (returnType == null) {
            return null;
        }
        FunctionDescriptor functionDescriptor = methodDescriptorCache.get(method);
        if (functionDescriptor != null) {
            if (method.getContainingClass() != psiClass) {
                functionDescriptor = functionDescriptor.substitute(typeSubstitutorForGenericSuperclasses);
            }
            return functionDescriptor;
        }
853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879

        boolean kotlin;
        if (owner instanceof JavaNamespaceDescriptor) {
            JavaNamespaceDescriptor javaNamespaceDescriptor = (JavaNamespaceDescriptor) owner;
            ResolverNamespaceData namespaceData = namespaceDescriptorCacheByFqn.get(javaNamespaceDescriptor.getQualifiedName());
            if (namespaceData == null) {
                throw new IllegalStateException("namespaceData not found by name " + javaNamespaceDescriptor.getQualifiedName());
            }
            kotlin = namespaceData.kotlin;
        } else {
            ResolverClassData classData = classDescriptorCache.get(psiClass.getQualifiedName());
            if (classData == null) {
                throw new IllegalStateException("classData not found by name " + psiClass.getQualifiedName());
            }
            kotlin = classData.kotlin;
        }

        // TODO: hide getters and setters properly
        if (kotlin) {
            if (method.getName().startsWith(JvmAbi.GETTER_PREFIX) && method.getParameterList().getParametersCount() == 0) {
                return null;
            }
            if (method.getName().startsWith(JvmAbi.SETTER_PREFIX) && method.getParameterList().getParametersCount() == 1) {
                return null;
            }
        }
        
880 881 882 883 884 885 886 887 888 889 890
        DeclarationDescriptor classDescriptor;
        final List<TypeParameterDescriptor> classTypeParameters;
        if (method.hasModifierProperty(PsiModifier.STATIC)) {
            classDescriptor = resolveNamespace(method.getContainingClass());
            classTypeParameters = Collections.emptyList();
        }
        else {
            ClassDescriptor classClassDescriptor = resolveClass(method.getContainingClass());
            classDescriptor = classClassDescriptor;
            classTypeParameters = classClassDescriptor.getTypeConstructor().getParameters();
        }
891 892 893
        if (classDescriptor == null) {
            return null;
        }
A
Andrey Breslav 已提交
894 895
        PsiParameter[] parameters = method.getParameterList().getParameters();
        FunctionDescriptorImpl functionDescriptorImpl = new FunctionDescriptorImpl(
A
Andrey Breslav 已提交
896 897
                owner,
                Collections.<AnnotationDescriptor>emptyList(), // TODO
A
Andrey Breslav 已提交
898 899 900
                method.getName()
        );
        methodDescriptorCache.put(method, functionDescriptorImpl);
901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927

        // TODO: add outer classes
        TypeParameterListTypeVariableResolver typeVariableResolverForParameters = new TypeParameterListTypeVariableResolver(classTypeParameters);

        final List<TypeParameterDescriptor> methodTypeParameters = resolveMethodTypeParameters(method, functionDescriptorImpl, typeVariableResolverForParameters);

        class MethodTypeVariableResolver implements TypeVariableResolver {

            @NotNull
            @Override
            public TypeParameterDescriptor getTypeVariable(@NotNull String name) {
                for (TypeParameterDescriptor typeParameter : methodTypeParameters) {
                    if (typeParameter.getName().equals(name)) {
                        return typeParameter;
                    }
                }
                for (TypeParameterDescriptor typeParameter : classTypeParameters) {
                    if (typeParameter.getName().equals(name)) {
                        return typeParameter;
                    }
                }
                throw new IllegalStateException("unresolver variable: " + name); // TODO: report properly
            }
        }


        ValueParameterDescriptors valueParameterDescriptors = resolveParameterDescriptors(functionDescriptorImpl, parameters, new MethodTypeVariableResolver());
A
Andrey Breslav 已提交
928
        functionDescriptorImpl.initialize(
929
                valueParameterDescriptors.receiverType,
A
Andrey Breslav 已提交
930
                DescriptorUtils.getExpectedThisObjectIfNeeded(classDescriptor),
931
                methodTypeParameters,
932
                valueParameterDescriptors.descriptors,
933
                makeReturnType(returnType, method, new MethodTypeVariableResolver()),
934
                Modality.convertFromFlags(method.hasModifierProperty(PsiModifier.ABSTRACT), !method.hasModifierProperty(PsiModifier.FINAL)),
935
                resolveVisibilityFromPsiModifiers(method)
A
Andrey Breslav 已提交
936
        );
937
        semanticServices.getTrace().record(BindingContext.FUNCTION, method, functionDescriptorImpl);
A
Andrey Breslav 已提交
938 939 940 941 942 943
        FunctionDescriptor substitutedFunctionDescriptor = functionDescriptorImpl;
        if (method.getContainingClass() != psiClass) {
            substitutedFunctionDescriptor = functionDescriptorImpl.substitute(typeSubstitutorForGenericSuperclasses);
        }
        return substitutedFunctionDescriptor;
    }
944

945
    private List<TypeParameterDescriptor> resolveMethodTypeParameters(PsiMethod method, FunctionDescriptorImpl functionDescriptorImpl, TypeVariableResolver classTypeVariableResolver) {
946
        for (PsiAnnotation annotation : method.getModifierList().getAnnotations()) {
S
Stepan Koltsov 已提交
947 948
            if (annotation.getQualifiedName().equals(JvmStdlibNames.JET_METHOD.getFqName())) {
                PsiLiteralExpression attributeValue = (PsiLiteralExpression) annotation.findAttributeValue(JvmStdlibNames.JET_METHOD_TYPE_PARAMETERS_FIELD);
949 950 951
                if (attributeValue != null) {
                    String typeParametersString = (String) attributeValue.getValue();
                    if (typeParametersString != null) {
952
                        List<TypeParameterDescriptor> r = resolveMethodTypeParametersFromJetSignature(typeParametersString, method, functionDescriptorImpl, classTypeVariableResolver);
953 954
                        initializeTypeParameters(method);
                        return r;
955 956 957 958 959 960 961 962 963
                    }
                }
            }
        }
        
        List<TypeParameterDescriptor> typeParameters = makeUninitializedTypeParameters(functionDescriptorImpl, method.getTypeParameters());
        initializeTypeParameters(method);
        return typeParameters;
    }
964 965

    /**
966
     * @see #resolveClassTypeParametersFromJetSignature(String, com.intellij.psi.PsiClass, JavaClassDescriptor) 
967
     */
968 969 970
    private List<TypeParameterDescriptor> resolveMethodTypeParametersFromJetSignature(String jetSignature, final PsiMethod method,
            final FunctionDescriptor functionDescriptor, final TypeVariableResolver classTypeVariableResolver)
    {
971
        final List<TypeParameterDescriptor> r = new ArrayList<TypeParameterDescriptor>();
972 973 974 975 976 977 978 979 980 981 982 983 984 985 986
        
        class MyTypeVariableResolver implements TypeVariableResolver {

            @NotNull
            @Override
            public TypeParameterDescriptor getTypeVariable(@NotNull String name) {
                for (TypeParameterDescriptor typeParameter : r) {
                    if (typeParameter.getName().equals(name)) {
                        return typeParameter;
                    }
                }
                return classTypeVariableResolver.getTypeVariable(name);
            }
        }
        
987 988
        new JetSignatureReader(jetSignature).acceptFormalTypeParametersOnly(new JetSignatureExceptionsAdapter() {
            @Override
S
Stepan Koltsov 已提交
989
            public JetSignatureVisitor visitFormalTypeParameter(final String name, final TypeInfoVariance variance) {
990
                
991
                return new JetSignatureTypeParameterVisitor(functionDescriptor, method, name, variance, new MyTypeVariableResolver()) {
992
                    @Override
993 994
                    protected void done(TypeParameterDescriptor typeParameterDescriptor) {
                        r.add(typeParameterDescriptor);
995 996
                    }
                };
997

998 999 1000 1001 1002
            }
        });
        return r;
    }

1003
    private JetType makeReturnType(PsiType returnType, PsiMethod method, TypeVariableResolver typeVariableResolver) {
1004 1005
        boolean changeNullable = false;
        boolean nullable = true;
S
Stepan Koltsov 已提交
1006 1007
        
        String returnTypeFromAnnotation = null;
1008 1009

        for (PsiAnnotation annotation : method.getModifierList().getAnnotations()) {
S
Stepan Koltsov 已提交
1010 1011
            if (annotation.getQualifiedName().equals(JvmStdlibNames.JET_METHOD.getFqName())) {
                PsiLiteralExpression nullableExpression = (PsiLiteralExpression) annotation.findAttributeValue(JvmStdlibNames.JET_METHOD_NULLABLE_RETURN_TYPE_FIELD);
1012 1013 1014 1015 1016 1017 1018
                if (nullableExpression != null) {
                    nullable = (Boolean) nullableExpression.getValue();
                } else {
                    // default value of parameter
                    nullable = false;
                    changeNullable = true;
                }
S
Stepan Koltsov 已提交
1019
                
S
Stepan Koltsov 已提交
1020
                PsiLiteralExpression returnTypeExpression = (PsiLiteralExpression) annotation.findAttributeValue(JvmStdlibNames.JET_METHOD_RETURN_TYPE_FIELD);
S
Stepan Koltsov 已提交
1021 1022 1023
                if (returnTypeExpression != null) {
                    returnTypeFromAnnotation = (String) returnTypeExpression.getValue();
                }
1024 1025
            }
        }
S
Stepan Koltsov 已提交
1026
        JetType transformedType;
1027
        if (returnTypeFromAnnotation != null && returnTypeFromAnnotation.length() > 0) {
1028
            transformedType = semanticServices.getTypeTransformer().transformToType(returnTypeFromAnnotation, typeVariableResolver);
S
Stepan Koltsov 已提交
1029 1030 1031
        } else {
            transformedType = semanticServices.getTypeTransformer().transformToType(returnType);
        }
1032 1033 1034 1035 1036 1037 1038
        if (changeNullable) {
            return TypeUtils.makeNullableAsSpecified(transformedType, nullable);
        } else {
            return transformedType;
        }
    }

1039
    private static Visibility resolveVisibilityFromPsiModifiers(PsiModifierListOwner modifierListOwner) {
1040 1041 1042 1043 1044 1045
        //TODO report error
        return modifierListOwner.hasModifierProperty(PsiModifier.PUBLIC) ? Visibility.PUBLIC :
                                        (modifierListOwner.hasModifierProperty(PsiModifier.PRIVATE) ? Visibility.PRIVATE :
                                        (modifierListOwner.hasModifierProperty(PsiModifier.PROTECTED) ? Visibility.PROTECTED : Visibility.INTERNAL));
    }

1046 1047
    @NotNull
    private TypeParameterDescriptorInitialization resolveTypeParameterInitialization(PsiTypeParameter typeParameter) {
1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071
        PsiTypeParameterListOwner owner = typeParameter.getOwner();
        if (owner instanceof PsiClass) {
            PsiClass psiClass = (PsiClass) owner;
            return resolveTypeParameter(resolveClass(psiClass), typeParameter);
        }
        if (owner instanceof PsiMethod) {
            PsiMethod psiMethod = (PsiMethod) owner;
            PsiClass containingClass = psiMethod.getContainingClass();
            DeclarationDescriptor ownerOwner;
            TypeSubstitutor substitutorForGenericSupertypes;
            if (psiMethod.hasModifierProperty(PsiModifier.STATIC)) {
                substitutorForGenericSupertypes = TypeSubstitutor.EMPTY;
                return resolveTypeParameter(JAVA_METHOD_TYPE_PARAMETER_PARENT, typeParameter);
            }
            else {
                ClassDescriptor classDescriptor = resolveClass(containingClass);
                ownerOwner = classDescriptor;
                substitutorForGenericSupertypes = semanticServices.getDescriptorResolver().createSubstitutorForGenericSupertypes(classDescriptor);
            }
            FunctionDescriptor functionDescriptor = resolveMethodToFunctionDescriptor(ownerOwner, containingClass, substitutorForGenericSupertypes, psiMethod);
            return resolveTypeParameter(functionDescriptor, typeParameter);
        }
        throw new IllegalStateException("Unknown parent type: " + owner);
    }
1072 1073 1074 1075

    public TypeParameterDescriptor resolveTypeParameter(PsiTypeParameter typeParameter) {
        return resolveTypeParameterInitialization(typeParameter).descriptor;
    }
1076
}