JavaDescriptorResolver.java 48.3 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 99
    private static class ResolverClassData {
        private JavaClassDescriptor classDescriptor;
        private boolean kotlin;

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

    protected final Map<String, ResolverClassData> classDescriptorCache = Maps.newHashMap();
100
    protected final Map<PsiTypeParameter, TypeParameterDescriptorInitialization> typeParameterDescriptorCache = Maps.newHashMap();
A
Andrey Breslav 已提交
101
    protected final Map<PsiMethod, FunctionDescriptor> methodDescriptorCache = Maps.newHashMap();
A
Andrey Breslav 已提交
102
    protected final Map<PsiField, VariableDescriptor> fieldDescriptorCache = Maps.newHashMap();
A
Andrey Breslav 已提交
103
    protected final Map<PsiElement, NamespaceDescriptor> namespaceDescriptorCache = Maps.newHashMap();
104 105 106 107 108 109
    protected final JavaPsiFacade javaFacade;
    protected final GlobalSearchScope javaSearchScope;
    protected final JavaSemanticServices semanticServices;

    public JavaDescriptorResolver(Project project, JavaSemanticServices semanticServices) {
        this.javaFacade = JavaPsiFacade.getInstance(project);
110 111 112 113 114 115
        this.javaSearchScope = new DelegatingGlobalSearchScope(GlobalSearchScope.allScope(project)) {
            @Override
            public boolean contains(VirtualFile file) {
                return myBaseScope.contains(file) && file.getFileType() != JetFileType.INSTANCE;
            }
        };
116 117 118
        this.semanticServices = semanticServices;
    }

119
    @Nullable
120 121
    public ClassDescriptor resolveClass(@NotNull PsiClass psiClass) {
        String qualifiedName = psiClass.getQualifiedName();
122 123 124 125 126
        
        if (qualifiedName.endsWith(JvmAbi.TRAIT_IMPL_SUFFIX)) {
            // TODO: only if -$$TImpl class is created by Kotlin
            return null;
        }
127

128
        // First, let's check that this is a real Java class, not a Java's view on a Kotlin class:
129 130 131 132 133
        ClassDescriptor kotlinClassDescriptor = semanticServices.getKotlinClassDescriptor(qualifiedName);
        if (kotlinClassDescriptor != null) {
            return kotlinClassDescriptor;
        }

134
        // Not let's take a descriptor of a Java class
135 136 137 138
        ResolverClassData classData = classDescriptorCache.get(qualifiedName);
        if (classData == null) {
            classData = createJavaClassDescriptor(psiClass);
            classDescriptorCache.put(qualifiedName, classData);
139
        }
140
        return classData.getClassDescriptor();
141 142 143 144
    }

    @Nullable
    public ClassDescriptor resolveClass(@NotNull String qualifiedName) {
145 146 147 148 149 150
        
        if (qualifiedName.endsWith(JvmAbi.TRAIT_IMPL_SUFFIX)) {
            // TODO: only if -$$TImpl class is created by Kotlin
            return null;
        }
        
151
        // First, let's check that this is a real Java class, not a Java's view on a Kotlin class:
152 153 154 155 156
        ClassDescriptor kotlinClassDescriptor = semanticServices.getKotlinClassDescriptor(qualifiedName);
        if (kotlinClassDescriptor != null) {
            return kotlinClassDescriptor;
        }

157
        // Not let's take a descriptor of a Java class
158 159
        ResolverClassData classData = classDescriptorCache.get(qualifiedName);
        if (classData == null) {
160
            PsiClass psiClass = findClass(qualifiedName);
161 162 163
            if (psiClass == null) {
                return null;
            }
164
            classData = createJavaClassDescriptor(psiClass);
165
        }
166
        return classData.getClassDescriptor();
167 168
    }

169
    private ResolverClassData createJavaClassDescriptor(@NotNull final PsiClass psiClass) {
A
Andrey Breslav 已提交
170 171 172
        assert !classDescriptorCache.containsKey(psiClass.getQualifiedName()) : psiClass.getQualifiedName();
        classDescriptorCache.put(psiClass.getQualifiedName(), null); // TODO

173
        String name = psiClass.getName();
174 175
        ResolverClassData classData = new ResolverClassData();
        classData.classDescriptor = new JavaClassDescriptor(
176
                resolveParentDescriptor(psiClass), psiClass.isInterface() ? ClassKind.TRAIT : ClassKind.CLASS
177
        );
178
        classData.classDescriptor.setName(name);
179
        
180 181 182 183 184 185 186 187 188
        class OuterClassTypeVariableResolver implements TypeVariableResolver {

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

A
Andrey Breslav 已提交
189
        List<JetType> supertypes = new ArrayList<JetType>();
190 191 192
        List<TypeParameterDescriptor> typeParameters = resolveClassTypeParameters(psiClass, classData, new OuterClassTypeVariableResolver());
        classData.classDescriptor.setTypeConstructor(new TypeConstructorImpl(
                classData.classDescriptor,
A
Andrey Breslav 已提交
193
                Collections.<AnnotationDescriptor>emptyList(), // TODO
194
                // TODO
195
                psiClass.hasModifierProperty(PsiModifier.FINAL),
A
Andrey Breslav 已提交
196
                name,
A
Andrey Breslav 已提交
197
                typeParameters,
A
Andrey Breslav 已提交
198 199
                supertypes
        ));
200
        classData.classDescriptor.setModality(Modality.convertFromFlags(
201 202
                psiClass.hasModifierProperty(PsiModifier.ABSTRACT) || psiClass.isInterface(),
                !psiClass.hasModifierProperty(PsiModifier.FINAL))
A
Andrey Breslav 已提交
203
        );
204 205 206
        classData.classDescriptor.setVisibility(resolveVisibilityFromPsiModifiers(psiClass));
        classDescriptorCache.put(psiClass.getQualifiedName(), classData);
        classData.classDescriptor.setUnsubstitutedMemberScope(new JavaClassMembersScope(classData.classDescriptor, psiClass, semanticServices, false));
207

208 209
        // UGLY HACK (Andrey Breslav is not sure what did he mean)
        initializeTypeParameters(psiClass);
210

A
Andrey Breslav 已提交
211
        supertypes.addAll(getSupertypes(psiClass));
212
        if (psiClass.isInterface()) {
213
            classData.classDescriptor.setSuperclassType(JetStandardClasses.getAnyType()); // TODO : Make it java.lang.Object
214 215 216 217 218 219 220
        }
        else {
            PsiClassType[] extendsListTypes = psiClass.getExtendsListTypes();
            assert extendsListTypes.length == 0 || extendsListTypes.length == 1;
            JetType superclassType = extendsListTypes.length == 0
                                            ? JetStandardClasses.getAnyType()
                                            : semanticServices.getTypeTransformer().transformToType(extendsListTypes[0]);
221
            classData.classDescriptor.setSuperclassType(superclassType);
222
        }
A
Andrey Breslav 已提交
223 224

        PsiMethod[] psiConstructors = psiClass.getConstructors();
225 226

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

263
        semanticServices.getTrace().record(BindingContext.CLASS, psiClass, classData.classDescriptor);
264

265
        return classData;
266 267
    }

268
    private List<TypeParameterDescriptor> resolveClassTypeParameters(PsiClass psiClass, ResolverClassData classData, TypeVariableResolver typeVariableResolver) {
269
        for (PsiAnnotation annotation : psiClass.getModifierList().getAnnotations()) {
S
Stepan Koltsov 已提交
270
            if (annotation.getQualifiedName().equals(JvmStdlibNames.JET_CLASS.getFqName())) {
271
                classData.kotlin = true;
S
Stepan Koltsov 已提交
272
                PsiLiteralExpression attributeValue = (PsiLiteralExpression) annotation.findAttributeValue(JvmStdlibNames.JET_CLASS_SIGNATURE);
273 274 275
                if (attributeValue != null) {
                    String typeParametersString = (String) attributeValue.getValue();
                    if (typeParametersString != null) {
276
                        return resolveClassTypeParametersFromJetSignature(typeParametersString, psiClass, classData.classDescriptor, typeVariableResolver);
277 278 279 280
                    }
                }
            }
        }
281
        return makeUninitializedTypeParameters(classData.classDescriptor, psiClass.getTypeParameters());
282 283
    }

284
    @NotNull
285
    private PsiTypeParameter getPsiTypeParameterByName(PsiTypeParameterListOwner clazz, String name) {
286 287 288 289 290
        for (PsiTypeParameter typeParameter : clazz.getTypeParameters()) {
            if (typeParameter.getName().equals(name)) {
                return typeParameter; 
            }
        }
291 292 293
        throw new IllegalStateException("PsiTypeParameter '" + name + "' is not found");
    }

S
Stepan Koltsov 已提交
294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310

    // 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();
    }


311 312 313 314 315 316
    private abstract class JetSignatureTypeParameterVisitor extends JetSignatureExceptionsAdapter {
        
        private final DeclarationDescriptor containingDeclaration;
        private final PsiTypeParameterListOwner psiOwner;
        private final String name;
        private final TypeInfoVariance variance;
317
        private final TypeVariableResolver typeVariableResolver;
318 319

        protected JetSignatureTypeParameterVisitor(DeclarationDescriptor containingDeclaration, PsiTypeParameterListOwner psiOwner,
320
                String name, TypeInfoVariance variance, TypeVariableResolver typeVariableResolver)
321
        {
322 323 324 325
            if (name.isEmpty()) {
                throw new IllegalStateException();
            }
            
326 327 328 329
            this.containingDeclaration = containingDeclaration;
            this.psiOwner = psiOwner;
            this.name = name;
            this.variance = variance;
330
            this.typeVariableResolver = typeVariableResolver;
331 332 333 334 335 336
        }

        int index = 0;

        List<JetType> upperBounds = new ArrayList<JetType>();
        List<JetType> lowerBounds = new ArrayList<JetType>();
S
Stepan Koltsov 已提交
337
        
338 339
        @Override
        public JetSignatureVisitor visitClassBound() {
340
            return new JetTypeJetSignatureReader(JavaDescriptorResolver.this, semanticServices.getJetSemanticServices().getStandardLibrary(), typeVariableResolver) {
341 342
                @Override
                protected void done(@NotNull JetType jetType) {
S
Stepan Koltsov 已提交
343 344 345
                    if (isJavaLangObject(jetType)) {
                        return;
                    }
346 347 348 349 350 351 352
                    upperBounds.add(jetType);
                }
            };
        }

        @Override
        public JetSignatureVisitor visitInterfaceBound() {
353
            return new JetTypeJetSignatureReader(JavaDescriptorResolver.this, semanticServices.getJetSemanticServices().getStandardLibrary(), typeVariableResolver) {
354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375
                @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);
376 377
    }

378 379 380
    /**
     * @see #resolveMethodTypeParametersFromJetSignature(String, FunctionDescriptor)
     */
381 382
    private List<TypeParameterDescriptor> resolveClassTypeParametersFromJetSignature(String jetSignature, final PsiClass clazz,
            final JavaClassDescriptor classDescriptor, final TypeVariableResolver outerClassTypeVariableResolver) {
383
        final List<TypeParameterDescriptor> r = new ArrayList<TypeParameterDescriptor>();
384 385 386 387 388 389 390 391 392 393 394 395 396 397 398
        
        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);
            }
        }
        
399 400 401
        new JetSignatureReader(jetSignature).accept(new JetSignatureExceptionsAdapter() {
            @Override
            public JetSignatureVisitor visitFormalTypeParameter(final String name, final TypeInfoVariance variance) {
402
                return new JetSignatureTypeParameterVisitor(classDescriptor, clazz, name, variance, new MyTypeVariableResolver()) {
403
                    @Override
404 405
                    protected void done(TypeParameterDescriptor typeParameterDescriptor) {
                        r.add(typeParameterDescriptor);
406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424
                    }
                };
            }

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

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

425 426 427
    private DeclarationDescriptor resolveParentDescriptor(PsiClass psiClass) {
        PsiClass containingClass = psiClass.getContainingClass();
        if (containingClass != null) {
428
            return resolveClass(containingClass);
429 430 431 432 433 434 435
        }
        
        PsiJavaFile containingFile = (PsiJavaFile) psiClass.getContainingFile();
        String packageName = containingFile.getPackageName();
        return resolveNamespace(packageName);
    }

436
    private List<TypeParameterDescriptor> makeUninitializedTypeParameters(@NotNull DeclarationDescriptor containingDeclaration, @NotNull PsiTypeParameter[] typeParameters) {
437 438
        List<TypeParameterDescriptor> result = Lists.newArrayList();
        for (PsiTypeParameter typeParameter : typeParameters) {
439
            TypeParameterDescriptor typeParameterDescriptor = makeUninitializedTypeParameter(containingDeclaration, typeParameter);
A
Andrey Breslav 已提交
440
            result.add(typeParameterDescriptor);
441 442 443 444
        }
        return result;
    }

445 446 447
    @NotNull
    private TypeParameterDescriptor makeUninitializedTypeParameter(@NotNull DeclarationDescriptor containingDeclaration, @NotNull PsiTypeParameter psiTypeParameter) {
        assert typeParameterDescriptorCache.get(psiTypeParameter) == null : psiTypeParameter.getText();
448
        TypeParameterDescriptor typeParameterDescriptor = TypeParameterDescriptor.createForFurtherModification(
449
                containingDeclaration,
A
Andrey Breslav 已提交
450
                Collections.<AnnotationDescriptor>emptyList(), // TODO
A
Andrey Breslav 已提交
451
                false,
452
                Variance.INVARIANT,
453 454
                psiTypeParameter.getName(),
                psiTypeParameter.getIndex()
455
        );
456
        typeParameterDescriptorCache.put(psiTypeParameter, new TypeParameterDescriptorInitialization(typeParameterDescriptor));
457 458 459
        return typeParameterDescriptor;
    }

460 461 462
    private void initializeTypeParameter(PsiTypeParameter typeParameter, TypeParameterDescriptorInitialization typeParameterDescriptorInitialization) {
        TypeParameterDescriptor typeParameterDescriptor = typeParameterDescriptorInitialization.descriptor;
        if (typeParameterDescriptorInitialization.origin == TypeParameterDescriptorOrigin.KOTLIN) {
463 464 465 466 467 468 469 470 471 472
            List<?> upperBounds = typeParameterDescriptorInitialization.upperBoundsForKotlin;
            if (upperBounds.size() == 0){
                typeParameterDescriptor.addUpperBound(JetStandardClasses.getNullableAnyType());
            } else {
                for (JetType upperBound : typeParameterDescriptorInitialization.upperBoundsForKotlin) {
                    typeParameterDescriptor.addUpperBound(upperBound);
                }
            }

            // TODO: lower bounds
473 474 475 476 477 478 479 480 481 482 483 484
        } 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 已提交
485 486
            }
        }
487
        typeParameterDescriptor.setInitialized();
488 489 490 491
    }

    private void initializeTypeParameters(PsiTypeParameterListOwner typeParameterListOwner) {
        for (PsiTypeParameter psiTypeParameter : typeParameterListOwner.getTypeParameters()) {
492
            initializeTypeParameter(psiTypeParameter, resolveTypeParameterInitialization(psiTypeParameter));
493
        }
A
Andrey Breslav 已提交
494 495 496
    }

    @NotNull
497 498
    private TypeParameterDescriptorInitialization resolveTypeParameter(@NotNull DeclarationDescriptor containingDeclaration, @NotNull PsiTypeParameter psiTypeParameter) {
        TypeParameterDescriptorInitialization typeParameterDescriptor = typeParameterDescriptorCache.get(psiTypeParameter);
499
        assert typeParameterDescriptor != null : psiTypeParameter.getText();
A
Andrey Breslav 已提交
500 501 502
        return typeParameterDescriptor;
    }

A
Andrey Breslav 已提交
503 504
    private Collection<? extends JetType> getSupertypes(PsiClass psiClass) {
        List<JetType> result = new ArrayList<JetType>();
505 506 507 508 509 510
        result.add(JetStandardClasses.getAnyType());
        transformSupertypeList(result, psiClass.getExtendsListTypes());
        transformSupertypeList(result, psiClass.getImplementsListTypes());
        return result;
    }

A
Andrey Breslav 已提交
511
    private void transformSupertypeList(List<JetType> result, PsiClassType[] extendsListTypes) {
512
        for (PsiClassType type : extendsListTypes) {
A
Andrey Breslav 已提交
513
            JetType transform = semanticServices.getTypeTransformer().transformToType(type);
514 515 516 517 518

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

519
    public NamespaceDescriptor resolveNamespace(String qualifiedName) {
520
        PsiPackage psiPackage = findPackage(qualifiedName);
521
        if (psiPackage == null) {
522
            PsiClass psiClass = findClass(qualifiedName);
A
Andrey Breslav 已提交
523 524
            if (psiClass == null) return null;
            return resolveNamespace(psiClass);
525 526 527 528
        }
        return resolveNamespace(psiPackage);
    }

529 530 531 532
    private PsiClass findClass(String qualifiedName) {
        return javaFacade.findClass(qualifiedName, javaSearchScope);
    }

533
    /*package*/ PsiPackage findPackage(String qualifiedName) {
534 535 536
        return javaFacade.findPackage(qualifiedName);
    }

537 538
    private NamespaceDescriptor resolveNamespace(@NotNull PsiPackage psiPackage) {
        NamespaceDescriptor namespaceDescriptor = namespaceDescriptorCache.get(psiPackage);
539
        if (namespaceDescriptor == null) {
A
Andrey Breslav 已提交
540
            namespaceDescriptor = createJavaNamespaceDescriptor(psiPackage);
541
            namespaceDescriptorCache.put(psiPackage, namespaceDescriptor);
542 543 544 545
        }
        return namespaceDescriptor;
    }

A
Andrey Breslav 已提交
546 547 548 549 550 551 552 553 554
    private NamespaceDescriptor resolveNamespace(@NotNull PsiClass psiClass) {
        NamespaceDescriptor namespaceDescriptor = namespaceDescriptorCache.get(psiClass);
        if (namespaceDescriptor == null) {
            namespaceDescriptor = createJavaNamespaceDescriptor(psiClass);
            namespaceDescriptorCache.put(psiClass, namespaceDescriptor);
        }
        return namespaceDescriptor;
    }

555 556
    private NamespaceDescriptor createJavaNamespaceDescriptor(@NotNull PsiPackage psiPackage) {
        String name = psiPackage.getName();
557
        JavaNamespaceDescriptor namespaceDescriptor = new JavaNamespaceDescriptor(
558
                resolveParentDescriptor(psiPackage),
A
Andrey Breslav 已提交
559
                Collections.<AnnotationDescriptor>emptyList(), // TODO
560
                name == null ? JAVA_ROOT : name
561
        );
562

563
        namespaceDescriptor.setMemberScope(new JavaPackageScope(psiPackage.getQualifiedName(), namespaceDescriptor, semanticServices));
564
        semanticServices.getTrace().record(BindingContext.NAMESPACE, psiPackage, namespaceDescriptor);
565 566 567
        return namespaceDescriptor;
    }

568 569 570 571 572 573 574 575
    private DeclarationDescriptor resolveParentDescriptor(@NotNull PsiPackage psiPackage) {
        PsiPackage parentPackage = psiPackage.getParentPackage();
        if (parentPackage == null) {
            return null;
        }
        return resolveNamespace(parentPackage);
    }

576
    private NamespaceDescriptor createJavaNamespaceDescriptor(@NotNull final PsiClass psiClass) {
577
        JavaNamespaceDescriptor namespaceDescriptor = new JavaNamespaceDescriptor(
578
                resolveParentDescriptor(psiClass),
A
Andrey Breslav 已提交
579
                Collections.<AnnotationDescriptor>emptyList(), // TODO
580
                psiClass.getName()
581
        );
582
        namespaceDescriptor.setMemberScope(new JavaClassMembersScope(namespaceDescriptor, psiClass, semanticServices, true));
583
        semanticServices.getTrace().record(BindingContext.NAMESPACE, psiClass, namespaceDescriptor);
584 585
        return namespaceDescriptor;
    }
586 587 588 589 590 591 592 593 594 595
    
    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;
        }
    }
596

597 598
    public ValueParameterDescriptors resolveParameterDescriptors(DeclarationDescriptor containingDeclaration,
            PsiParameter[] parameters, TypeVariableResolver typeVariableResolver) {
599
        List<ValueParameterDescriptor> result = new ArrayList<ValueParameterDescriptor>();
600
        JetType receiverType = null;
601 602
        for (int i = 0, parametersLength = parameters.length; i < parametersLength; i++) {
            PsiParameter parameter = parameters[i];
603
            JvmMethodParameterMeaning meaning = resolveParameterDescriptor(containingDeclaration, i, parameter, typeVariableResolver);
604 605 606 607 608 609 610 611 612
            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 已提交
613
            }
614
        }
615
        return new ValueParameterDescriptors(receiverType, result);
616
    }
A
Andrey Breslav 已提交
617

618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650
    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
651 652
    private JvmMethodParameterMeaning resolveParameterDescriptor(DeclarationDescriptor containingDeclaration, int i,
            PsiParameter parameter, TypeVariableResolver typeVariableResolver) {
653 654 655 656 657 658 659 660 661 662
        PsiType psiType = parameter.getType();

        JetType varargElementType;
        if (psiType instanceof PsiEllipsisType) {
            PsiEllipsisType psiEllipsisType = (PsiEllipsisType) psiType;
            varargElementType = semanticServices.getTypeTransformer().transformToType(psiEllipsisType.getComponentType());
        }
        else {
            varargElementType = null;
        }
663 664 665

        boolean changeNullable = false;
        boolean nullable = true;
S
Stepan Koltsov 已提交
666
        String typeFromAnnotation = null;
667
        
668
        boolean receiver = false;
669
        boolean hasDefaultValue = false;
670
        
671 672 673 674
        // 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 已提交
675 676
            if (annotation.getQualifiedName().equals(JvmStdlibNames.JET_VALUE_PARAMETER.getFqName())) {
                PsiLiteralExpression nameExpression = (PsiLiteralExpression) annotation.findAttributeValue(JvmStdlibNames.JET_VALUE_PARAMETER_NAME_FIELD);
677 678 679 680
                if (nameExpression != null) {
                    name = (String) nameExpression.getValue();
                }
                
S
Stepan Koltsov 已提交
681
                PsiLiteralExpression nullableExpression = (PsiLiteralExpression) annotation.findAttributeValue(JvmStdlibNames.JET_VALUE_PARAMETER_NULLABLE_FIELD);
682 683 684 685 686 687 688
                if (nullableExpression != null) {
                    nullable = (Boolean) nullableExpression.getValue();
                } else {
                    // default value of parameter
                    nullable = false;
                    changeNullable = true;
                }
S
Stepan Koltsov 已提交
689
                
S
Stepan Koltsov 已提交
690
                PsiLiteralExpression signatureExpression = (PsiLiteralExpression) annotation.findAttributeValue(JvmStdlibNames.JET_VALUE_PARAMETER_TYPE_FIELD);
S
Stepan Koltsov 已提交
691 692 693
                if (signatureExpression != null) {
                    typeFromAnnotation = (String) signatureExpression.getValue();
                }
694 695


S
Stepan Koltsov 已提交
696
                PsiLiteralExpression receiverExpression = (PsiLiteralExpression) annotation.findAttributeValue(JvmStdlibNames.JET_VALUE_PARAMETER_RECEIVER_FIELD);
697
                if (receiverExpression != null) {
698
                    receiver = (Boolean) receiverExpression.getValue();
699
                }
700
                
S
Stepan Koltsov 已提交
701
                PsiLiteralExpression hasDefaultValueExpression = (PsiLiteralExpression) annotation.findAttributeValue(JvmStdlibNames.JET_VALUE_PARAMETER_HAS_DEFAULT_VALUE_FIELD);
702 703 704
                if (hasDefaultValueExpression != null) {
                    hasDefaultValue = (Boolean) hasDefaultValueExpression.getValue();
                }
705 706


S
Stepan Koltsov 已提交
707
            } else if (annotation.getQualifiedName().equals(JvmStdlibNames.JET_TYPE_PARAMETER.getFqName())) {
708
                return JvmMethodParameterMeaning.typeInfo(new Object());
709 710 711
            }
        }
        
S
Stepan Koltsov 已提交
712
        JetType outType;
713
        if (typeFromAnnotation != null && typeFromAnnotation.length() > 0) {
714
            outType = semanticServices.getTypeTransformer().transformToType(typeFromAnnotation, typeVariableResolver);
S
Stepan Koltsov 已提交
715 716 717
        } else {
            outType = semanticServices.getTypeTransformer().transformToType(psiType);
        }
718 719 720 721 722 723 724 725 726 727
        if (receiver) {
            return JvmMethodParameterMeaning.receiver(outType);
        } else {
            return JvmMethodParameterMeaning.regular(new ValueParameterDescriptorImpl(
                    containingDeclaration,
                    i,
                    Collections.<AnnotationDescriptor>emptyList(), // TODO
                    name,
                    null, // TODO : review
                    changeNullable ? TypeUtils.makeNullableAsSpecified(outType, nullable) : outType,
728
                    hasDefaultValue,
729 730 731
                    varargElementType
            ));
        }
732 733
    }

A
Andrey Breslav 已提交
734 735 736 737 738 739 740 741 742
    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 已提交
743
                Collections.<AnnotationDescriptor>emptyList(),
744
                Modality.FINAL,
745
                resolveVisibilityFromPsiModifiers(field),
A
Andrey Breslav 已提交
746 747
                !isFinal,
                null,
748
                DescriptorUtils.getExpectedThisObjectIfNeeded(containingDeclaration),
A
Andrey Breslav 已提交
749 750 751
                field.getName(),
                isFinal ? null : type,
                type);
752
        semanticServices.getTrace().record(BindingContext.VARIABLE, field, propertyDescriptor);
A
Andrey Breslav 已提交
753 754 755 756
        fieldDescriptorCache.put(field, propertyDescriptor);
        return propertyDescriptor;
    }

A
Andrey Breslav 已提交
757
    @NotNull
A
Andrey Breslav 已提交
758 759
    public Set<FunctionDescriptor> resolveFunctionGroup(@NotNull DeclarationDescriptor owner, @NotNull PsiClass psiClass, @Nullable ClassDescriptor classDescriptor, @NotNull String methodName, boolean staticMembers) {
        Set<FunctionDescriptor> writableFunctionGroup = Sets.newLinkedHashSet();
760
        final Collection<HierarchicalMethodSignature> signatures = psiClass.getVisibleSignatures();
A
Andrey Breslav 已提交
761
        TypeSubstitutor typeSubstitutor = createSubstitutorForGenericSupertypes(classDescriptor);
762
        for (HierarchicalMethodSignature signature: signatures) {
763
            if (!methodName.equals(signature.getName())) {
A
Andrey Breslav 已提交
764 765 766
                 continue;
            }

767
            FunctionDescriptor substitutedFunctionDescriptor = resolveHierarchicalSignatureToFunction(owner, psiClass, staticMembers, typeSubstitutor, signature);
768
            if (substitutedFunctionDescriptor != null) {
A
Andrey Breslav 已提交
769
                writableFunctionGroup.add(substitutedFunctionDescriptor);
770
            }
A
Andrey Breslav 已提交
771 772 773
        }
        return writableFunctionGroup;
    }
A
Andrey Breslav 已提交
774

775 776 777 778 779 780 781 782 783 784 785 786 787 788 789
    @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 已提交
790 791 792 793 794 795 796 797 798 799 800
    public TypeSubstitutor createSubstitutorForGenericSupertypes(ClassDescriptor classDescriptor) {
        TypeSubstitutor typeSubstitutor;
        if (classDescriptor != null) {
            typeSubstitutor = TypeUtils.buildDeepSubstitutor(classDescriptor.getDefaultType());
        }
        else {
            typeSubstitutor = TypeSubstitutor.EMPTY;
        }
        return typeSubstitutor;
    }

801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820
    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 已提交
821
    @Nullable
A
Andrey Breslav 已提交
822
    public FunctionDescriptor resolveMethodToFunctionDescriptor(DeclarationDescriptor owner, PsiClass psiClass, TypeSubstitutor typeSubstitutorForGenericSuperclasses, PsiMethod method) {
A
Andrey Breslav 已提交
823 824 825 826 827 828 829 830 831 832 833
        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;
        }
834 835 836 837 838 839 840 841 842 843 844
        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();
        }
845 846 847
        if (classDescriptor == null) {
            return null;
        }
A
Andrey Breslav 已提交
848 849
        PsiParameter[] parameters = method.getParameterList().getParameters();
        FunctionDescriptorImpl functionDescriptorImpl = new FunctionDescriptorImpl(
A
Andrey Breslav 已提交
850 851
                owner,
                Collections.<AnnotationDescriptor>emptyList(), // TODO
A
Andrey Breslav 已提交
852 853 854
                method.getName()
        );
        methodDescriptorCache.put(method, functionDescriptorImpl);
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 880 881

        // 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 已提交
882
        functionDescriptorImpl.initialize(
883
                valueParameterDescriptors.receiverType,
A
Andrey Breslav 已提交
884
                DescriptorUtils.getExpectedThisObjectIfNeeded(classDescriptor),
885
                methodTypeParameters,
886
                valueParameterDescriptors.descriptors,
887
                makeReturnType(returnType, method, new MethodTypeVariableResolver()),
888
                Modality.convertFromFlags(method.hasModifierProperty(PsiModifier.ABSTRACT), !method.hasModifierProperty(PsiModifier.FINAL)),
889
                resolveVisibilityFromPsiModifiers(method)
A
Andrey Breslav 已提交
890
        );
891
        semanticServices.getTrace().record(BindingContext.FUNCTION, method, functionDescriptorImpl);
A
Andrey Breslav 已提交
892 893 894 895 896 897
        FunctionDescriptor substitutedFunctionDescriptor = functionDescriptorImpl;
        if (method.getContainingClass() != psiClass) {
            substitutedFunctionDescriptor = functionDescriptorImpl.substitute(typeSubstitutorForGenericSuperclasses);
        }
        return substitutedFunctionDescriptor;
    }
898

899
    private List<TypeParameterDescriptor> resolveMethodTypeParameters(PsiMethod method, FunctionDescriptorImpl functionDescriptorImpl, TypeVariableResolver classTypeVariableResolver) {
900
        for (PsiAnnotation annotation : method.getModifierList().getAnnotations()) {
S
Stepan Koltsov 已提交
901 902
            if (annotation.getQualifiedName().equals(JvmStdlibNames.JET_METHOD.getFqName())) {
                PsiLiteralExpression attributeValue = (PsiLiteralExpression) annotation.findAttributeValue(JvmStdlibNames.JET_METHOD_TYPE_PARAMETERS_FIELD);
903 904 905
                if (attributeValue != null) {
                    String typeParametersString = (String) attributeValue.getValue();
                    if (typeParametersString != null) {
906
                        List<TypeParameterDescriptor> r = resolveMethodTypeParametersFromJetSignature(typeParametersString, method, functionDescriptorImpl, classTypeVariableResolver);
907 908
                        initializeTypeParameters(method);
                        return r;
909 910 911 912 913 914 915 916 917
                    }
                }
            }
        }
        
        List<TypeParameterDescriptor> typeParameters = makeUninitializedTypeParameters(functionDescriptorImpl, method.getTypeParameters());
        initializeTypeParameters(method);
        return typeParameters;
    }
918 919

    /**
920
     * @see #resolveClassTypeParametersFromJetSignature(String, com.intellij.psi.PsiClass, JavaClassDescriptor) 
921
     */
922 923 924
    private List<TypeParameterDescriptor> resolveMethodTypeParametersFromJetSignature(String jetSignature, final PsiMethod method,
            final FunctionDescriptor functionDescriptor, final TypeVariableResolver classTypeVariableResolver)
    {
925
        final List<TypeParameterDescriptor> r = new ArrayList<TypeParameterDescriptor>();
926 927 928 929 930 931 932 933 934 935 936 937 938 939 940
        
        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);
            }
        }
        
941 942
        new JetSignatureReader(jetSignature).acceptFormalTypeParametersOnly(new JetSignatureExceptionsAdapter() {
            @Override
S
Stepan Koltsov 已提交
943
            public JetSignatureVisitor visitFormalTypeParameter(final String name, final TypeInfoVariance variance) {
944
                
945
                return new JetSignatureTypeParameterVisitor(functionDescriptor, method, name, variance, new MyTypeVariableResolver()) {
946
                    @Override
947 948
                    protected void done(TypeParameterDescriptor typeParameterDescriptor) {
                        r.add(typeParameterDescriptor);
949 950
                    }
                };
951

952 953 954 955 956
            }
        });
        return r;
    }

957
    private JetType makeReturnType(PsiType returnType, PsiMethod method, TypeVariableResolver typeVariableResolver) {
958 959
        boolean changeNullable = false;
        boolean nullable = true;
S
Stepan Koltsov 已提交
960 961
        
        String returnTypeFromAnnotation = null;
962 963

        for (PsiAnnotation annotation : method.getModifierList().getAnnotations()) {
S
Stepan Koltsov 已提交
964 965
            if (annotation.getQualifiedName().equals(JvmStdlibNames.JET_METHOD.getFqName())) {
                PsiLiteralExpression nullableExpression = (PsiLiteralExpression) annotation.findAttributeValue(JvmStdlibNames.JET_METHOD_NULLABLE_RETURN_TYPE_FIELD);
966 967 968 969 970 971 972
                if (nullableExpression != null) {
                    nullable = (Boolean) nullableExpression.getValue();
                } else {
                    // default value of parameter
                    nullable = false;
                    changeNullable = true;
                }
S
Stepan Koltsov 已提交
973
                
S
Stepan Koltsov 已提交
974
                PsiLiteralExpression returnTypeExpression = (PsiLiteralExpression) annotation.findAttributeValue(JvmStdlibNames.JET_METHOD_RETURN_TYPE_FIELD);
S
Stepan Koltsov 已提交
975 976 977
                if (returnTypeExpression != null) {
                    returnTypeFromAnnotation = (String) returnTypeExpression.getValue();
                }
978 979
            }
        }
S
Stepan Koltsov 已提交
980
        JetType transformedType;
981
        if (returnTypeFromAnnotation != null && returnTypeFromAnnotation.length() > 0) {
982
            transformedType = semanticServices.getTypeTransformer().transformToType(returnTypeFromAnnotation, typeVariableResolver);
S
Stepan Koltsov 已提交
983 984 985
        } else {
            transformedType = semanticServices.getTypeTransformer().transformToType(returnType);
        }
986 987 988 989 990 991 992
        if (changeNullable) {
            return TypeUtils.makeNullableAsSpecified(transformedType, nullable);
        } else {
            return transformedType;
        }
    }

993
    private static Visibility resolveVisibilityFromPsiModifiers(PsiModifierListOwner modifierListOwner) {
994 995 996 997 998 999
        //TODO report error
        return modifierListOwner.hasModifierProperty(PsiModifier.PUBLIC) ? Visibility.PUBLIC :
                                        (modifierListOwner.hasModifierProperty(PsiModifier.PRIVATE) ? Visibility.PRIVATE :
                                        (modifierListOwner.hasModifierProperty(PsiModifier.PROTECTED) ? Visibility.PROTECTED : Visibility.INTERNAL));
    }

1000 1001
    @NotNull
    private TypeParameterDescriptorInitialization resolveTypeParameterInitialization(PsiTypeParameter typeParameter) {
1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025
        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);
    }
1026 1027 1028 1029

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