JavaDescriptorResolver.java 58.9 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.util.text.StringUtil;
8
import com.intellij.openapi.vfs.VirtualFile;
9
import com.intellij.psi.*;
10
import com.intellij.psi.search.DelegatingGlobalSearchScope;
11
import com.intellij.psi.search.GlobalSearchScope;
12
import jet.typeinfo.TypeInfoVariance;
13 14
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
A
Andrey Breslav 已提交
15
import org.jetbrains.jet.lang.descriptors.*;
A
Andrey Breslav 已提交
16
import org.jetbrains.jet.lang.descriptors.annotations.AnnotationDescriptor;
17
import org.jetbrains.jet.lang.resolve.BindingContext;
18
import org.jetbrains.jet.lang.resolve.DescriptorUtils;
19
import org.jetbrains.jet.lang.types.*;
20
import org.jetbrains.jet.plugin.JetFileType;
21
import org.jetbrains.jet.rt.signature.JetSignatureAdapter;
22 23 24
import org.jetbrains.jet.rt.signature.JetSignatureExceptionsAdapter;
import org.jetbrains.jet.rt.signature.JetSignatureReader;
import org.jetbrains.jet.rt.signature.JetSignatureVisitor;
25 26 27 28 29 30 31

import java.util.*;

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

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

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

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

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

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

74 75
        private TypeParameterDescriptorInitialization(TypeParameterDescriptor descriptor) {
            this.origin = TypeParameterDescriptorOrigin.JAVA;
76
            this.descriptor = descriptor;
77 78 79 80 81 82 83 84 85 86
            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;
87 88
        }
    }
89 90 91 92 93 94
    
    private static abstract class ResolverScopeData {
        @Nullable
        private Set<VariableDescriptor> properties;
        private boolean kotlin;
    }
A
Andrey Breslav 已提交
95

96
    private static class ResolverClassData extends ResolverScopeData {
97 98 99 100 101 102 103 104 105
        private JavaClassDescriptor classDescriptor;
        private boolean kotlin;

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

106
    private static class ResolverNamespaceData extends ResolverScopeData {
107 108 109 110 111 112 113 114 115
        private JavaNamespaceDescriptor namespaceDescriptor;
        private boolean kotlin;

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

116
    protected final Map<String, ResolverClassData> classDescriptorCache = Maps.newHashMap();
117 118 119
    protected final Map<String, ResolverNamespaceData> namespaceDescriptorCacheByFqn = Maps.newHashMap();
    protected final Map<PsiElement, ResolverNamespaceData> namespaceDescriptorCache = Maps.newHashMap();

120
    protected final Map<PsiTypeParameter, TypeParameterDescriptorInitialization> typeParameterDescriptorCache = Maps.newHashMap();
A
Andrey Breslav 已提交
121
    protected final Map<PsiMethod, FunctionDescriptor> methodDescriptorCache = Maps.newHashMap();
A
Andrey Breslav 已提交
122
    protected final Map<PsiField, VariableDescriptor> fieldDescriptorCache = Maps.newHashMap();
123 124 125 126 127 128
    protected final JavaPsiFacade javaFacade;
    protected final GlobalSearchScope javaSearchScope;
    protected final JavaSemanticServices semanticServices;

    public JavaDescriptorResolver(Project project, JavaSemanticServices semanticServices) {
        this.javaFacade = JavaPsiFacade.getInstance(project);
129 130 131 132 133 134
        this.javaSearchScope = new DelegatingGlobalSearchScope(GlobalSearchScope.allScope(project)) {
            @Override
            public boolean contains(VirtualFile file) {
                return myBaseScope.contains(file) && file.getFileType() != JetFileType.INSTANCE;
            }
        };
135 136 137
        this.semanticServices = semanticServices;
    }

138
    @Nullable
139 140
    public ClassDescriptor resolveClass(@NotNull PsiClass psiClass) {
        String qualifiedName = psiClass.getQualifiedName();
141 142 143 144 145
        
        if (qualifiedName.endsWith(JvmAbi.TRAIT_IMPL_SUFFIX)) {
            // TODO: only if -$$TImpl class is created by Kotlin
            return null;
        }
146

147
        // First, let's check that this is a real Java class, not a Java's view on a Kotlin class:
148 149 150 151 152
        ClassDescriptor kotlinClassDescriptor = semanticServices.getKotlinClassDescriptor(qualifiedName);
        if (kotlinClassDescriptor != null) {
            return kotlinClassDescriptor;
        }

153
        // Not let's take a descriptor of a Java class
154 155 156 157
        ResolverClassData classData = classDescriptorCache.get(qualifiedName);
        if (classData == null) {
            classData = createJavaClassDescriptor(psiClass);
            classDescriptorCache.put(qualifiedName, classData);
158
        }
159
        return classData.getClassDescriptor();
160 161 162 163
    }

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

176
        // Not let's take a descriptor of a Java class
177 178
        ResolverClassData classData = classDescriptorCache.get(qualifiedName);
        if (classData == null) {
179
            PsiClass psiClass = findClass(qualifiedName);
180 181 182
            if (psiClass == null) {
                return null;
            }
183
            classData = createJavaClassDescriptor(psiClass);
184
        }
185
        return classData.getClassDescriptor();
186 187
    }

188
    private ResolverClassData createJavaClassDescriptor(@NotNull final PsiClass psiClass) {
A
Andrey Breslav 已提交
189 190 191
        assert !classDescriptorCache.containsKey(psiClass.getQualifiedName()) : psiClass.getQualifiedName();
        classDescriptorCache.put(psiClass.getQualifiedName(), null); // TODO

192
        String name = psiClass.getName();
193 194
        ResolverClassData classData = new ResolverClassData();
        classData.classDescriptor = new JavaClassDescriptor(
195
                resolveParentDescriptor(psiClass), psiClass.isInterface() ? ClassKind.TRAIT : ClassKind.CLASS
196
        );
197
        classData.classDescriptor.setName(name);
198
        
199 200 201 202 203 204 205 206 207
        class OuterClassTypeVariableResolver implements TypeVariableResolver {

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

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

227 228
        // UGLY HACK (Andrey Breslav is not sure what did he mean)
        initializeTypeParameters(psiClass);
229

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

        PsiMethod[] psiConstructors = psiClass.getConstructors();
244 245

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

282
        semanticServices.getTrace().record(BindingContext.CLASS, psiClass, classData.classDescriptor);
283

284
        return classData;
285 286
    }

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

303
    @NotNull
304
    private PsiTypeParameter getPsiTypeParameterByName(PsiTypeParameterListOwner clazz, String name) {
305 306 307 308 309
        for (PsiTypeParameter typeParameter : clazz.getTypeParameters()) {
            if (typeParameter.getName().equals(name)) {
                return typeParameter; 
            }
        }
310 311 312
        throw new IllegalStateException("PsiTypeParameter '" + name + "' is not found");
    }

S
Stepan Koltsov 已提交
313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329

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


330 331 332 333 334 335
    private abstract class JetSignatureTypeParameterVisitor extends JetSignatureExceptionsAdapter {
        
        private final DeclarationDescriptor containingDeclaration;
        private final PsiTypeParameterListOwner psiOwner;
        private final String name;
        private final TypeInfoVariance variance;
336
        private final TypeVariableResolver typeVariableResolver;
337 338

        protected JetSignatureTypeParameterVisitor(DeclarationDescriptor containingDeclaration, PsiTypeParameterListOwner psiOwner,
339
                String name, TypeInfoVariance variance, TypeVariableResolver typeVariableResolver)
340
        {
341 342 343 344
            if (name.isEmpty()) {
                throw new IllegalStateException();
            }
            
345 346 347 348
            this.containingDeclaration = containingDeclaration;
            this.psiOwner = psiOwner;
            this.name = name;
            this.variance = variance;
349
            this.typeVariableResolver = typeVariableResolver;
350 351 352 353 354 355
        }

        int index = 0;

        List<JetType> upperBounds = new ArrayList<JetType>();
        List<JetType> lowerBounds = new ArrayList<JetType>();
S
Stepan Koltsov 已提交
356
        
357 358
        @Override
        public JetSignatureVisitor visitClassBound() {
359
            return new JetTypeJetSignatureReader(JavaDescriptorResolver.this, semanticServices.getJetSemanticServices().getStandardLibrary(), typeVariableResolver) {
360 361
                @Override
                protected void done(@NotNull JetType jetType) {
S
Stepan Koltsov 已提交
362 363 364
                    if (isJavaLangObject(jetType)) {
                        return;
                    }
365 366 367 368 369 370 371
                    upperBounds.add(jetType);
                }
            };
        }

        @Override
        public JetSignatureVisitor visitInterfaceBound() {
372
            return new JetTypeJetSignatureReader(JavaDescriptorResolver.this, semanticServices.getJetSemanticServices().getStandardLibrary(), typeVariableResolver) {
373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394
                @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);
395 396
    }

397 398 399
    /**
     * @see #resolveMethodTypeParametersFromJetSignature(String, FunctionDescriptor)
     */
400 401
    private List<TypeParameterDescriptor> resolveClassTypeParametersFromJetSignature(String jetSignature, final PsiClass clazz,
            final JavaClassDescriptor classDescriptor, final TypeVariableResolver outerClassTypeVariableResolver) {
402
        final List<TypeParameterDescriptor> r = new ArrayList<TypeParameterDescriptor>();
403 404 405 406 407 408 409 410 411 412 413 414 415 416 417
        
        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);
            }
        }
        
418 419 420
        new JetSignatureReader(jetSignature).accept(new JetSignatureExceptionsAdapter() {
            @Override
            public JetSignatureVisitor visitFormalTypeParameter(final String name, final TypeInfoVariance variance) {
421
                return new JetSignatureTypeParameterVisitor(classDescriptor, clazz, name, variance, new MyTypeVariableResolver()) {
422
                    @Override
423 424
                    protected void done(TypeParameterDescriptor typeParameterDescriptor) {
                        r.add(typeParameterDescriptor);
425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443
                    }
                };
            }

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

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

444 445 446
    private DeclarationDescriptor resolveParentDescriptor(PsiClass psiClass) {
        PsiClass containingClass = psiClass.getContainingClass();
        if (containingClass != null) {
447
            return resolveClass(containingClass);
448 449 450 451 452 453 454
        }
        
        PsiJavaFile containingFile = (PsiJavaFile) psiClass.getContainingFile();
        String packageName = containingFile.getPackageName();
        return resolveNamespace(packageName);
    }

455
    private List<TypeParameterDescriptor> makeUninitializedTypeParameters(@NotNull DeclarationDescriptor containingDeclaration, @NotNull PsiTypeParameter[] typeParameters) {
456 457
        List<TypeParameterDescriptor> result = Lists.newArrayList();
        for (PsiTypeParameter typeParameter : typeParameters) {
458
            TypeParameterDescriptor typeParameterDescriptor = makeUninitializedTypeParameter(containingDeclaration, typeParameter);
A
Andrey Breslav 已提交
459
            result.add(typeParameterDescriptor);
460 461 462 463
        }
        return result;
    }

464 465 466
    @NotNull
    private TypeParameterDescriptor makeUninitializedTypeParameter(@NotNull DeclarationDescriptor containingDeclaration, @NotNull PsiTypeParameter psiTypeParameter) {
        assert typeParameterDescriptorCache.get(psiTypeParameter) == null : psiTypeParameter.getText();
467
        TypeParameterDescriptor typeParameterDescriptor = TypeParameterDescriptor.createForFurtherModification(
468
                containingDeclaration,
A
Andrey Breslav 已提交
469
                Collections.<AnnotationDescriptor>emptyList(), // TODO
A
Andrey Breslav 已提交
470
                false,
471
                Variance.INVARIANT,
472 473
                psiTypeParameter.getName(),
                psiTypeParameter.getIndex()
474
        );
475
        typeParameterDescriptorCache.put(psiTypeParameter, new TypeParameterDescriptorInitialization(typeParameterDescriptor));
476 477 478
        return typeParameterDescriptor;
    }

479 480 481
    private void initializeTypeParameter(PsiTypeParameter typeParameter, TypeParameterDescriptorInitialization typeParameterDescriptorInitialization) {
        TypeParameterDescriptor typeParameterDescriptor = typeParameterDescriptorInitialization.descriptor;
        if (typeParameterDescriptorInitialization.origin == TypeParameterDescriptorOrigin.KOTLIN) {
482 483 484 485 486 487 488 489 490 491
            List<?> upperBounds = typeParameterDescriptorInitialization.upperBoundsForKotlin;
            if (upperBounds.size() == 0){
                typeParameterDescriptor.addUpperBound(JetStandardClasses.getNullableAnyType());
            } else {
                for (JetType upperBound : typeParameterDescriptorInitialization.upperBoundsForKotlin) {
                    typeParameterDescriptor.addUpperBound(upperBound);
                }
            }

            // TODO: lower bounds
492 493 494 495 496 497 498 499 500 501 502 503
        } 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 已提交
504 505
            }
        }
506
        typeParameterDescriptor.setInitialized();
507 508 509 510
    }

    private void initializeTypeParameters(PsiTypeParameterListOwner typeParameterListOwner) {
        for (PsiTypeParameter psiTypeParameter : typeParameterListOwner.getTypeParameters()) {
511
            initializeTypeParameter(psiTypeParameter, resolveTypeParameterInitialization(psiTypeParameter));
512
        }
A
Andrey Breslav 已提交
513 514 515
    }

    @NotNull
516 517
    private TypeParameterDescriptorInitialization resolveTypeParameter(@NotNull DeclarationDescriptor containingDeclaration, @NotNull PsiTypeParameter psiTypeParameter) {
        TypeParameterDescriptorInitialization typeParameterDescriptor = typeParameterDescriptorCache.get(psiTypeParameter);
518
        assert typeParameterDescriptor != null : psiTypeParameter.getText();
A
Andrey Breslav 已提交
519 520 521
        return typeParameterDescriptor;
    }

A
Andrey Breslav 已提交
522 523
    private Collection<? extends JetType> getSupertypes(PsiClass psiClass) {
        List<JetType> result = new ArrayList<JetType>();
524 525 526 527 528 529
        result.add(JetStandardClasses.getAnyType());
        transformSupertypeList(result, psiClass.getExtendsListTypes());
        transformSupertypeList(result, psiClass.getImplementsListTypes());
        return result;
    }

A
Andrey Breslav 已提交
530
    private void transformSupertypeList(List<JetType> result, PsiClassType[] extendsListTypes) {
531
        for (PsiClassType type : extendsListTypes) {
A
Andrey Breslav 已提交
532
            JetType transform = semanticServices.getTypeTransformer().transformToType(type);
533 534 535 536 537

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

538
    public NamespaceDescriptor resolveNamespace(String qualifiedName) {
539
        PsiPackage psiPackage = findPackage(qualifiedName);
540
        if (psiPackage == null) {
541
            PsiClass psiClass = findClass(qualifiedName);
A
Andrey Breslav 已提交
542 543
            if (psiClass == null) return null;
            return resolveNamespace(psiClass);
544 545 546 547
        }
        return resolveNamespace(psiPackage);
    }

548 549 550 551
    private PsiClass findClass(String qualifiedName) {
        return javaFacade.findClass(qualifiedName, javaSearchScope);
    }

552
    /*package*/ PsiPackage findPackage(String qualifiedName) {
553 554 555
        return javaFacade.findPackage(qualifiedName);
    }

556
    private NamespaceDescriptor resolveNamespace(@NotNull PsiPackage psiPackage) {
557 558 559 560 561
        ResolverNamespaceData namespaceData = namespaceDescriptorCache.get(psiPackage);
        if (namespaceData == null) {
            namespaceData = createJavaNamespaceDescriptor(psiPackage);
            namespaceDescriptorCache.put(psiPackage, namespaceData);
            namespaceDescriptorCacheByFqn.put(psiPackage.getQualifiedName(), namespaceData);
562
        }
563
        return namespaceData.namespaceDescriptor;
564 565
    }

A
Andrey Breslav 已提交
566
    private NamespaceDescriptor resolveNamespace(@NotNull PsiClass psiClass) {
567 568 569 570 571
        ResolverNamespaceData namespaceData = namespaceDescriptorCache.get(psiClass);
        if (namespaceData == null) {
            namespaceData = createJavaNamespaceDescriptor(psiClass);
            namespaceDescriptorCache.put(psiClass, namespaceData);
            namespaceDescriptorCacheByFqn.put(psiClass.getQualifiedName(), namespaceData);
A
Andrey Breslav 已提交
572
        }
573
        return namespaceData.namespaceDescriptor;
A
Andrey Breslav 已提交
574 575
    }

576 577
    private ResolverNamespaceData createJavaNamespaceDescriptor(@NotNull PsiPackage psiPackage) {
        ResolverNamespaceData namespaceData = new ResolverNamespaceData();
578
        String name = psiPackage.getName();
579
        namespaceData.namespaceDescriptor = new JavaNamespaceDescriptor(
580
                resolveParentDescriptor(psiPackage),
A
Andrey Breslav 已提交
581
                Collections.<AnnotationDescriptor>emptyList(), // TODO
582 583
                name == null ? JAVA_ROOT : name,
                name == null ? JAVA_ROOT : psiPackage.getQualifiedName()
584
        );
585

586 587 588 589 590
        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;
591 592
    }

593 594 595 596 597 598 599 600
    private DeclarationDescriptor resolveParentDescriptor(@NotNull PsiPackage psiPackage) {
        PsiPackage parentPackage = psiPackage.getParentPackage();
        if (parentPackage == null) {
            return null;
        }
        return resolveNamespace(parentPackage);
    }

601 602 603
    private ResolverNamespaceData createJavaNamespaceDescriptor(@NotNull final PsiClass psiClass) {
        ResolverNamespaceData namespaceData = new ResolverNamespaceData();
        namespaceData.namespaceDescriptor = new JavaNamespaceDescriptor(
604
                resolveParentDescriptor(psiClass),
A
Andrey Breslav 已提交
605
                Collections.<AnnotationDescriptor>emptyList(), // TODO
606 607
                psiClass.getName(),
                psiClass.getQualifiedName()
608
        );
609 610 611
        namespaceData.namespaceDescriptor.setMemberScope(new JavaClassMembersScope(namespaceData.namespaceDescriptor, psiClass, semanticServices, true));
        semanticServices.getTrace().record(BindingContext.NAMESPACE, psiClass, namespaceData.namespaceDescriptor);
        return namespaceData;
612
    }
613 614 615 616 617 618 619 620 621 622
    
    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;
        }
    }
623

624 625
    public ValueParameterDescriptors resolveParameterDescriptors(DeclarationDescriptor containingDeclaration,
            PsiParameter[] parameters, TypeVariableResolver typeVariableResolver) {
626
        List<ValueParameterDescriptor> result = new ArrayList<ValueParameterDescriptor>();
627
        JetType receiverType = null;
628 629
        for (int i = 0, parametersLength = parameters.length; i < parametersLength; i++) {
            PsiParameter parameter = parameters[i];
630
            JvmMethodParameterMeaning meaning = resolveParameterDescriptor(containingDeclaration, i, parameter, typeVariableResolver);
631 632 633 634 635 636 637 638 639
            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 已提交
640
            }
641
        }
642
        return new ValueParameterDescriptors(receiverType, result);
643
    }
A
Andrey Breslav 已提交
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 671 672 673 674 675 676 677
    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
678 679
    private JvmMethodParameterMeaning resolveParameterDescriptor(DeclarationDescriptor containingDeclaration, int i,
            PsiParameter parameter, TypeVariableResolver typeVariableResolver) {
680 681 682 683 684 685 686 687 688 689
        PsiType psiType = parameter.getType();

        JetType varargElementType;
        if (psiType instanceof PsiEllipsisType) {
            PsiEllipsisType psiEllipsisType = (PsiEllipsisType) psiType;
            varargElementType = semanticServices.getTypeTransformer().transformToType(psiEllipsisType.getComponentType());
        }
        else {
            varargElementType = null;
        }
690 691 692

        boolean changeNullable = false;
        boolean nullable = true;
S
Stepan Koltsov 已提交
693
        String typeFromAnnotation = null;
694
        
695
        boolean receiver = false;
696
        boolean hasDefaultValue = false;
697
        
698 699 700 701
        // 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 已提交
702 703
            if (annotation.getQualifiedName().equals(JvmStdlibNames.JET_VALUE_PARAMETER.getFqName())) {
                PsiLiteralExpression nameExpression = (PsiLiteralExpression) annotation.findAttributeValue(JvmStdlibNames.JET_VALUE_PARAMETER_NAME_FIELD);
704 705 706 707
                if (nameExpression != null) {
                    name = (String) nameExpression.getValue();
                }
                
S
Stepan Koltsov 已提交
708
                PsiLiteralExpression nullableExpression = (PsiLiteralExpression) annotation.findAttributeValue(JvmStdlibNames.JET_VALUE_PARAMETER_NULLABLE_FIELD);
709 710 711 712 713 714 715
                if (nullableExpression != null) {
                    nullable = (Boolean) nullableExpression.getValue();
                } else {
                    // default value of parameter
                    nullable = false;
                    changeNullable = true;
                }
S
Stepan Koltsov 已提交
716
                
S
Stepan Koltsov 已提交
717
                PsiLiteralExpression signatureExpression = (PsiLiteralExpression) annotation.findAttributeValue(JvmStdlibNames.JET_VALUE_PARAMETER_TYPE_FIELD);
S
Stepan Koltsov 已提交
718 719 720
                if (signatureExpression != null) {
                    typeFromAnnotation = (String) signatureExpression.getValue();
                }
721 722


S
Stepan Koltsov 已提交
723
                PsiLiteralExpression receiverExpression = (PsiLiteralExpression) annotation.findAttributeValue(JvmStdlibNames.JET_VALUE_PARAMETER_RECEIVER_FIELD);
724
                if (receiverExpression != null) {
725
                    receiver = (Boolean) receiverExpression.getValue();
726
                }
727
                
S
Stepan Koltsov 已提交
728
                PsiLiteralExpression hasDefaultValueExpression = (PsiLiteralExpression) annotation.findAttributeValue(JvmStdlibNames.JET_VALUE_PARAMETER_HAS_DEFAULT_VALUE_FIELD);
729 730 731
                if (hasDefaultValueExpression != null) {
                    hasDefaultValue = (Boolean) hasDefaultValueExpression.getValue();
                }
732 733


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

761
    /*
A
Andrey Breslav 已提交
762 763 764 765 766 767 768 769 770
    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 已提交
771
                Collections.<AnnotationDescriptor>emptyList(),
772
                Modality.FINAL,
773
                resolveVisibilityFromPsiModifiers(field),
A
Andrey Breslav 已提交
774 775
                !isFinal,
                null,
776
                DescriptorUtils.getExpectedThisObjectIfNeeded(containingDeclaration),
A
Andrey Breslav 已提交
777 778
                field.getName(),
                type);
779
        semanticServices.getTrace().record(BindingContext.VARIABLE, field, propertyDescriptor);
A
Andrey Breslav 已提交
780 781 782
        fieldDescriptorCache.put(field, propertyDescriptor);
        return propertyDescriptor;
    }
783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 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 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 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 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 954 955 956 957 958 959 960 961 962 963 964 965 966 967 968 969 970 971 972 973 974 975 976
    */
    
    private static class PropertyKey {
        @NotNull
        private final String name;
        @NotNull
        private final PsiType type;

        private PropertyKey(String name, PsiType type) {
            this.name = name;
            this.type = type;
        }

        @Override
        public boolean equals(Object o) {
            // generated by Idea
            if (this == o) return true;
            if (o == null || getClass() != o.getClass()) return false;

            PropertyKey that = (PropertyKey) o;

            if (!name.equals(that.name)) return false;
            if (!type.equals(that.type)) return false;

            return true;
        }

        @Override
        public int hashCode() {
            int result = name.hashCode();
            result = 31 * result + type.hashCode();
            return result;
        }
    }

    private static class MembersForProperty {
        private PsiField field;
        private PsiMethod setter;
        private PsiMethod getter;
    }
    
    private Map<PropertyKey, MembersForProperty> getMembersForProperties(@NotNull PsiClass clazz, boolean staticMembers, boolean kotlin) {
        Map<PropertyKey, MembersForProperty> membersMap = Maps.newHashMap();
        if (!kotlin) {
            for (PsiField field : clazz.getFields()) {
                if (field.getModifierList().hasExplicitModifier(PsiModifier.STATIC) != staticMembers) {
                    continue;
                }

                if (field.hasModifierProperty(PsiModifier.PRIVATE)) {
                    continue;
                }

                MembersForProperty members = new MembersForProperty();
                members.field = field;
                membersMap.put(new PropertyKey(field.getName(), field.getType()), members);
            }
        }
        
        for (PsiMethod method : clazz.getMethods()) {
            if (method.getModifierList().hasExplicitModifier(PsiModifier.STATIC) != staticMembers) {
                continue;
            }

            if (method.hasModifierProperty(PsiModifier.PRIVATE)) {
                continue;
            }

            // TODO: "is" prefix
            if (method.getName().startsWith(JvmAbi.GETTER_PREFIX)) {
                // TODO: some java properties too
                if (method.getModifierList().findAnnotation(JvmStdlibNames.JET_PROPERTY.getFqName()) != null) {
                    if (method.getParameterList().getParametersCount() == 0) {
                        if (method.getName().equals(JvmStdlibNames.JET_OBJECT_GET_TYPEINFO_METHOD)) {
                            continue;
                        }

                        String propertyName = StringUtil.decapitalize(method.getName().substring(JvmAbi.GETTER_PREFIX.length()));
                        PropertyKey key = new PropertyKey(propertyName, method.getReturnType());
                        MembersForProperty members = membersMap.get(key);
                        if (members == null) {
                            members = new MembersForProperty();
                            membersMap.put(key, members);
                        }
                        members.getter = method;
                    }
                }
            } else if (method.getName().startsWith(JvmAbi.SETTER_PREFIX)) {
                if (method.getModifierList().findAnnotation(JvmStdlibNames.JET_PROPERTY.getFqName()) != null) {
                    if (method.getParameterList().getParametersCount() == 1) {
                        String propertyName = StringUtil.decapitalize(method.getName().substring(JvmAbi.SETTER_PREFIX.length()));
                        PropertyKey key = new PropertyKey(propertyName, method.getParameterList().getParameters()[0].getType());
                        MembersForProperty members = membersMap.get(key);
                        if (members == null) {
                            members = new MembersForProperty();
                            membersMap.put(key, members);
                        }
                        members.setter = method;
                    }
                }
            }
        }
        
        return membersMap;
    }
    
    public Set<VariableDescriptor> resolveFieldGroupByName(@NotNull DeclarationDescriptor owner, PsiClass psiClass, String fieldName, boolean staticMembers) {
        Set<VariableDescriptor> r = Sets.newHashSet();
        // TODO: slow
        Set<VariableDescriptor> variables = resolveFieldGroup(owner, psiClass, staticMembers);
        for (VariableDescriptor variable : variables) {
            if (variable.getName().equals(fieldName)) {
                r.add(variable);
            }
        }
        return r;
    }

    @NotNull
    public Set<VariableDescriptor> resolveFieldGroup(@NotNull DeclarationDescriptor owner, PsiClass psiClass, boolean staticMembers) {
        
        ResolverScopeData scopeData;
        if (owner instanceof JavaNamespaceDescriptor) {
            scopeData = namespaceDescriptorCacheByFqn.get(((JavaNamespaceDescriptor) owner).getQualifiedName());
        } else if (owner instanceof JavaClassDescriptor) {
            scopeData = classDescriptorCache.get(psiClass.getQualifiedName());
        } else {
            throw new IllegalStateException();
        }
        if (scopeData == null) {
            throw new IllegalStateException();
        }
        
        if (scopeData.properties != null) {
            return scopeData.properties;
        }
        
        Set<VariableDescriptor> descriptors = Sets.newHashSet();
        for (Map.Entry<PropertyKey, MembersForProperty> entry : getMembersForProperties(psiClass, staticMembers, scopeData.kotlin).entrySet()) {
            //VariableDescriptor variableDescriptor = fieldDescriptorCache.get(field);
            //if (variableDescriptor != null) {
            //    return variableDescriptor;
            //}
            String propertyName = entry.getKey().name;
            PsiType propertyType = entry.getKey().type;
            MembersForProperty members = entry.getValue();

            JetType type = semanticServices.getTypeTransformer().transformToType(propertyType);
            boolean isFinal;
            if (members.setter == null && members.getter == null) {
                isFinal = members.field.hasModifierProperty(PsiModifier.FINAL);
            } else if (members.getter != null) {
                isFinal = members.getter.hasModifierProperty(PsiModifier.FINAL);
            } else if (members.setter != null) {
                isFinal = members.setter.hasModifierProperty(PsiModifier.FINAL);
            } else {
                isFinal = false;
            }
            
            PsiMember anyMember;
            if (members.getter != null) {
                anyMember = members.getter;
            } else if (members.field != null) {
                anyMember = members.field;
            } else if (members.setter != null) {
                anyMember = members.setter;
            } else {
                throw new IllegalStateException();
            }
            
            boolean isVar;
            if (members.getter == null && members.setter == null) {
                isVar = true;
            } else {
                isVar = members.setter != null;
            }
            
            PropertyDescriptor propertyDescriptor = new PropertyDescriptor(
                    owner,
                    Collections.<AnnotationDescriptor>emptyList(),
                    isFinal && !staticMembers ? Modality.FINAL : Modality.OPEN, // TODO: abstract
                    resolveVisibilityFromPsiModifiers(anyMember),
                    isVar, 
                    null,
                    DescriptorUtils.getExpectedThisObjectIfNeeded(owner),
                    propertyName,
                    type);
            semanticServices.getTrace().record(BindingContext.VARIABLE, anyMember, propertyDescriptor);
            //fieldDescriptorCache.put(field, propertyDescriptor);
            descriptors.add(propertyDescriptor);
        }
        scopeData.properties = descriptors;
        return descriptors;
    }
A
Andrey Breslav 已提交
977

A
Andrey Breslav 已提交
978
    @NotNull
A
Andrey Breslav 已提交
979 980
    public Set<FunctionDescriptor> resolveFunctionGroup(@NotNull DeclarationDescriptor owner, @NotNull PsiClass psiClass, @Nullable ClassDescriptor classDescriptor, @NotNull String methodName, boolean staticMembers) {
        Set<FunctionDescriptor> writableFunctionGroup = Sets.newLinkedHashSet();
981
        final Collection<HierarchicalMethodSignature> signatures = psiClass.getVisibleSignatures();
A
Andrey Breslav 已提交
982
        TypeSubstitutor typeSubstitutor = createSubstitutorForGenericSupertypes(classDescriptor);
983
        for (HierarchicalMethodSignature signature: signatures) {
984
            if (!methodName.equals(signature.getName())) {
A
Andrey Breslav 已提交
985 986 987
                 continue;
            }

988
            FunctionDescriptor substitutedFunctionDescriptor = resolveHierarchicalSignatureToFunction(owner, psiClass, staticMembers, typeSubstitutor, signature);
989
            if (substitutedFunctionDescriptor != null) {
A
Andrey Breslav 已提交
990
                writableFunctionGroup.add(substitutedFunctionDescriptor);
991
            }
A
Andrey Breslav 已提交
992 993 994
        }
        return writableFunctionGroup;
    }
A
Andrey Breslav 已提交
995

996 997 998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010
    @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 已提交
1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021
    public TypeSubstitutor createSubstitutorForGenericSupertypes(ClassDescriptor classDescriptor) {
        TypeSubstitutor typeSubstitutor;
        if (classDescriptor != null) {
            typeSubstitutor = TypeUtils.buildDeepSubstitutor(classDescriptor.getDefaultType());
        }
        else {
            typeSubstitutor = TypeSubstitutor.EMPTY;
        }
        return typeSubstitutor;
    }

1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041
    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 已提交
1042
    @Nullable
A
Andrey Breslav 已提交
1043
    public FunctionDescriptor resolveMethodToFunctionDescriptor(DeclarationDescriptor owner, PsiClass psiClass, TypeSubstitutor typeSubstitutorForGenericSuperclasses, PsiMethod method) {
A
Andrey Breslav 已提交
1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054
        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;
        }
1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073 1074

        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) {
1075 1076
                if (method.getModifierList().findAnnotation(JvmStdlibNames.JET_PROPERTY.getFqName()) != null)
                    return null;
1077 1078
            }
            if (method.getName().startsWith(JvmAbi.SETTER_PREFIX) && method.getParameterList().getParametersCount() == 1) {
1079 1080
                if (method.getModifierList().findAnnotation(JvmStdlibNames.JET_PROPERTY.getFqName()) != null)
                    return null;
1081 1082 1083
            }
        }
        
1084 1085 1086 1087 1088 1089 1090 1091 1092 1093 1094
        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();
        }
1095 1096 1097
        if (classDescriptor == null) {
            return null;
        }
A
Andrey Breslav 已提交
1098 1099
        PsiParameter[] parameters = method.getParameterList().getParameters();
        FunctionDescriptorImpl functionDescriptorImpl = new FunctionDescriptorImpl(
A
Andrey Breslav 已提交
1100 1101
                owner,
                Collections.<AnnotationDescriptor>emptyList(), // TODO
A
Andrey Breslav 已提交
1102 1103 1104
                method.getName()
        );
        methodDescriptorCache.put(method, functionDescriptorImpl);
1105 1106 1107 1108 1109 1110 1111 1112 1113 1114 1115 1116 1117 1118 1119 1120 1121 1122 1123 1124 1125 1126 1127 1128 1129 1130 1131

        // 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 已提交
1132
        functionDescriptorImpl.initialize(
1133
                valueParameterDescriptors.receiverType,
A
Andrey Breslav 已提交
1134
                DescriptorUtils.getExpectedThisObjectIfNeeded(classDescriptor),
1135
                methodTypeParameters,
1136
                valueParameterDescriptors.descriptors,
1137
                makeReturnType(returnType, method, new MethodTypeVariableResolver()),
1138
                Modality.convertFromFlags(method.hasModifierProperty(PsiModifier.ABSTRACT), !method.hasModifierProperty(PsiModifier.FINAL)),
1139
                resolveVisibilityFromPsiModifiers(method)
A
Andrey Breslav 已提交
1140
        );
1141
        semanticServices.getTrace().record(BindingContext.FUNCTION, method, functionDescriptorImpl);
A
Andrey Breslav 已提交
1142 1143 1144 1145 1146 1147
        FunctionDescriptor substitutedFunctionDescriptor = functionDescriptorImpl;
        if (method.getContainingClass() != psiClass) {
            substitutedFunctionDescriptor = functionDescriptorImpl.substitute(typeSubstitutorForGenericSuperclasses);
        }
        return substitutedFunctionDescriptor;
    }
1148

1149
    private List<TypeParameterDescriptor> resolveMethodTypeParameters(PsiMethod method, FunctionDescriptorImpl functionDescriptorImpl, TypeVariableResolver classTypeVariableResolver) {
1150
        for (PsiAnnotation annotation : method.getModifierList().getAnnotations()) {
S
Stepan Koltsov 已提交
1151 1152
            if (annotation.getQualifiedName().equals(JvmStdlibNames.JET_METHOD.getFqName())) {
                PsiLiteralExpression attributeValue = (PsiLiteralExpression) annotation.findAttributeValue(JvmStdlibNames.JET_METHOD_TYPE_PARAMETERS_FIELD);
1153 1154 1155
                if (attributeValue != null) {
                    String typeParametersString = (String) attributeValue.getValue();
                    if (typeParametersString != null) {
1156
                        List<TypeParameterDescriptor> r = resolveMethodTypeParametersFromJetSignature(typeParametersString, method, functionDescriptorImpl, classTypeVariableResolver);
1157 1158
                        initializeTypeParameters(method);
                        return r;
1159 1160 1161 1162 1163 1164 1165 1166 1167
                    }
                }
            }
        }
        
        List<TypeParameterDescriptor> typeParameters = makeUninitializedTypeParameters(functionDescriptorImpl, method.getTypeParameters());
        initializeTypeParameters(method);
        return typeParameters;
    }
1168 1169

    /**
1170
     * @see #resolveClassTypeParametersFromJetSignature(String, com.intellij.psi.PsiClass, JavaClassDescriptor) 
1171
     */
1172 1173 1174
    private List<TypeParameterDescriptor> resolveMethodTypeParametersFromJetSignature(String jetSignature, final PsiMethod method,
            final FunctionDescriptor functionDescriptor, final TypeVariableResolver classTypeVariableResolver)
    {
1175
        final List<TypeParameterDescriptor> r = new ArrayList<TypeParameterDescriptor>();
1176 1177 1178 1179 1180 1181 1182 1183 1184 1185 1186 1187 1188 1189 1190
        
        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);
            }
        }
        
1191 1192
        new JetSignatureReader(jetSignature).acceptFormalTypeParametersOnly(new JetSignatureExceptionsAdapter() {
            @Override
S
Stepan Koltsov 已提交
1193
            public JetSignatureVisitor visitFormalTypeParameter(final String name, final TypeInfoVariance variance) {
1194
                
1195
                return new JetSignatureTypeParameterVisitor(functionDescriptor, method, name, variance, new MyTypeVariableResolver()) {
1196
                    @Override
1197 1198
                    protected void done(TypeParameterDescriptor typeParameterDescriptor) {
                        r.add(typeParameterDescriptor);
1199 1200
                    }
                };
1201

1202 1203 1204 1205 1206
            }
        });
        return r;
    }

1207
    private JetType makeReturnType(PsiType returnType, PsiMethod method, TypeVariableResolver typeVariableResolver) {
1208 1209
        boolean changeNullable = false;
        boolean nullable = true;
S
Stepan Koltsov 已提交
1210 1211
        
        String returnTypeFromAnnotation = null;
1212 1213

        for (PsiAnnotation annotation : method.getModifierList().getAnnotations()) {
S
Stepan Koltsov 已提交
1214 1215
            if (annotation.getQualifiedName().equals(JvmStdlibNames.JET_METHOD.getFqName())) {
                PsiLiteralExpression nullableExpression = (PsiLiteralExpression) annotation.findAttributeValue(JvmStdlibNames.JET_METHOD_NULLABLE_RETURN_TYPE_FIELD);
1216 1217 1218 1219 1220 1221 1222
                if (nullableExpression != null) {
                    nullable = (Boolean) nullableExpression.getValue();
                } else {
                    // default value of parameter
                    nullable = false;
                    changeNullable = true;
                }
S
Stepan Koltsov 已提交
1223
                
S
Stepan Koltsov 已提交
1224
                PsiLiteralExpression returnTypeExpression = (PsiLiteralExpression) annotation.findAttributeValue(JvmStdlibNames.JET_METHOD_RETURN_TYPE_FIELD);
S
Stepan Koltsov 已提交
1225 1226 1227
                if (returnTypeExpression != null) {
                    returnTypeFromAnnotation = (String) returnTypeExpression.getValue();
                }
1228 1229
            }
        }
S
Stepan Koltsov 已提交
1230
        JetType transformedType;
1231
        if (returnTypeFromAnnotation != null && returnTypeFromAnnotation.length() > 0) {
1232
            transformedType = semanticServices.getTypeTransformer().transformToType(returnTypeFromAnnotation, typeVariableResolver);
S
Stepan Koltsov 已提交
1233 1234 1235
        } else {
            transformedType = semanticServices.getTypeTransformer().transformToType(returnType);
        }
1236 1237 1238 1239 1240 1241 1242
        if (changeNullable) {
            return TypeUtils.makeNullableAsSpecified(transformedType, nullable);
        } else {
            return transformedType;
        }
    }

1243
    private static Visibility resolveVisibilityFromPsiModifiers(PsiModifierListOwner modifierListOwner) {
1244 1245 1246 1247 1248 1249
        //TODO report error
        return modifierListOwner.hasModifierProperty(PsiModifier.PUBLIC) ? Visibility.PUBLIC :
                                        (modifierListOwner.hasModifierProperty(PsiModifier.PRIVATE) ? Visibility.PRIVATE :
                                        (modifierListOwner.hasModifierProperty(PsiModifier.PROTECTED) ? Visibility.PROTECTED : Visibility.INTERNAL));
    }

1250 1251
    @NotNull
    private TypeParameterDescriptorInitialization resolveTypeParameterInitialization(PsiTypeParameter typeParameter) {
1252 1253 1254 1255 1256 1257 1258 1259 1260 1261 1262 1263 1264 1265 1266 1267 1268 1269 1270 1271 1272 1273 1274 1275
        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);
    }
1276 1277 1278 1279

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