JavaDescriptorResolver.java 62.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.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
            }
        }
        else {
            for (PsiMethod constructor : psiConstructors) {
263 264 265 266 267 268 269 270 271 272 273 274
                PsiAnnotation jetConstructorAnnotation =
                        constructor.getModifierList().findAnnotation(JvmStdlibNames.JET_CONSTRUCTOR.getFqName());
                if (jetConstructorAnnotation != null) {
                    PsiLiteralExpression hiddenExpresson = (PsiLiteralExpression) jetConstructorAnnotation.findAttributeValue(JvmStdlibNames.JET_CONSTRUCTOR_HIDDEN_FIELD);
                    if (hiddenExpresson != null) {
                        boolean hidden = (Boolean) hiddenExpresson.getValue();
                        if (hidden) {
                            continue;
                        }
                    }
                }

275
                ConstructorDescriptorImpl constructorDescriptor = new ConstructorDescriptorImpl(
276
                        classData.classDescriptor,
A
Andrey Breslav 已提交
277
                        Collections.<AnnotationDescriptor>emptyList(), // TODO
278
                        false);
279 280 281 282
                ValueParameterDescriptors valueParameterDescriptors = resolveParameterDescriptors(constructorDescriptor,
                        constructor.getParameterList().getParameters(),
                        new TypeParameterListTypeVariableResolver(typeParameters) // TODO: outer too
                    );
283 284 285 286
                if (valueParameterDescriptors.receiverType != null) {
                    throw new IllegalStateException();
                }
                constructorDescriptor.initialize(typeParameters, valueParameterDescriptors.descriptors, Modality.FINAL,
287
                                                 resolveVisibilityFromPsiModifiers(constructor));
288 289
                constructorDescriptor.setReturnType(classData.classDescriptor.getDefaultType());
                classData.classDescriptor.addConstructor(constructorDescriptor);
290
                semanticServices.getTrace().record(BindingContext.CONSTRUCTOR, constructor, constructorDescriptor);
291
            }
A
Andrey Breslav 已提交
292
        }
293

294
        semanticServices.getTrace().record(BindingContext.CLASS, psiClass, classData.classDescriptor);
295

296
        return classData;
297 298
    }

299
    private List<TypeParameterDescriptor> resolveClassTypeParameters(PsiClass psiClass, ResolverClassData classData, TypeVariableResolver typeVariableResolver) {
300
        for (PsiAnnotation annotation : psiClass.getModifierList().getAnnotations()) {
S
Stepan Koltsov 已提交
301
            if (annotation.getQualifiedName().equals(JvmStdlibNames.JET_CLASS.getFqName())) {
302
                classData.kotlin = true;
S
Stepan Koltsov 已提交
303
                PsiLiteralExpression attributeValue = (PsiLiteralExpression) annotation.findAttributeValue(JvmStdlibNames.JET_CLASS_SIGNATURE);
304 305 306
                if (attributeValue != null) {
                    String typeParametersString = (String) attributeValue.getValue();
                    if (typeParametersString != null) {
307
                        return resolveClassTypeParametersFromJetSignature(typeParametersString, psiClass, classData.classDescriptor, typeVariableResolver);
308 309 310 311
                    }
                }
            }
        }
312
        return makeUninitializedTypeParameters(classData.classDescriptor, psiClass.getTypeParameters());
313 314
    }

315
    @NotNull
316
    private PsiTypeParameter getPsiTypeParameterByName(PsiTypeParameterListOwner clazz, String name) {
317 318 319 320 321
        for (PsiTypeParameter typeParameter : clazz.getTypeParameters()) {
            if (typeParameter.getName().equals(name)) {
                return typeParameter; 
            }
        }
322 323 324
        throw new IllegalStateException("PsiTypeParameter '" + name + "' is not found");
    }

S
Stepan Koltsov 已提交
325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341

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


342 343 344 345 346 347
    private abstract class JetSignatureTypeParameterVisitor extends JetSignatureExceptionsAdapter {
        
        private final DeclarationDescriptor containingDeclaration;
        private final PsiTypeParameterListOwner psiOwner;
        private final String name;
        private final TypeInfoVariance variance;
348
        private final TypeVariableResolver typeVariableResolver;
349 350

        protected JetSignatureTypeParameterVisitor(DeclarationDescriptor containingDeclaration, PsiTypeParameterListOwner psiOwner,
351
                String name, TypeInfoVariance variance, TypeVariableResolver typeVariableResolver)
352
        {
353 354 355 356
            if (name.isEmpty()) {
                throw new IllegalStateException();
            }
            
357 358 359 360
            this.containingDeclaration = containingDeclaration;
            this.psiOwner = psiOwner;
            this.name = name;
            this.variance = variance;
361
            this.typeVariableResolver = typeVariableResolver;
362 363 364 365 366 367
        }

        int index = 0;

        List<JetType> upperBounds = new ArrayList<JetType>();
        List<JetType> lowerBounds = new ArrayList<JetType>();
S
Stepan Koltsov 已提交
368
        
369 370
        @Override
        public JetSignatureVisitor visitClassBound() {
371
            return new JetTypeJetSignatureReader(semanticServices, semanticServices.getJetSemanticServices().getStandardLibrary(), typeVariableResolver) {
372 373
                @Override
                protected void done(@NotNull JetType jetType) {
S
Stepan Koltsov 已提交
374 375 376
                    if (isJavaLangObject(jetType)) {
                        return;
                    }
377 378 379 380 381 382 383
                    upperBounds.add(jetType);
                }
            };
        }

        @Override
        public JetSignatureVisitor visitInterfaceBound() {
384
            return new JetTypeJetSignatureReader(semanticServices, semanticServices.getJetSemanticServices().getStandardLibrary(), typeVariableResolver) {
385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406
                @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);
407 408
    }

409 410 411
    /**
     * @see #resolveMethodTypeParametersFromJetSignature(String, FunctionDescriptor)
     */
412 413
    private List<TypeParameterDescriptor> resolveClassTypeParametersFromJetSignature(String jetSignature, final PsiClass clazz,
            final JavaClassDescriptor classDescriptor, final TypeVariableResolver outerClassTypeVariableResolver) {
414
        final List<TypeParameterDescriptor> r = new ArrayList<TypeParameterDescriptor>();
415 416 417 418 419 420 421 422 423 424 425 426 427 428 429
        
        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);
            }
        }
        
430 431 432
        new JetSignatureReader(jetSignature).accept(new JetSignatureExceptionsAdapter() {
            @Override
            public JetSignatureVisitor visitFormalTypeParameter(final String name, final TypeInfoVariance variance) {
433
                return new JetSignatureTypeParameterVisitor(classDescriptor, clazz, name, variance, new MyTypeVariableResolver()) {
434
                    @Override
435 436
                    protected void done(TypeParameterDescriptor typeParameterDescriptor) {
                        r.add(typeParameterDescriptor);
437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455
                    }
                };
            }

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

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

456 457 458
    private DeclarationDescriptor resolveParentDescriptor(PsiClass psiClass) {
        PsiClass containingClass = psiClass.getContainingClass();
        if (containingClass != null) {
459
            return resolveClass(containingClass);
460 461 462 463 464 465 466
        }
        
        PsiJavaFile containingFile = (PsiJavaFile) psiClass.getContainingFile();
        String packageName = containingFile.getPackageName();
        return resolveNamespace(packageName);
    }

467
    private List<TypeParameterDescriptor> makeUninitializedTypeParameters(@NotNull DeclarationDescriptor containingDeclaration, @NotNull PsiTypeParameter[] typeParameters) {
468 469
        List<TypeParameterDescriptor> result = Lists.newArrayList();
        for (PsiTypeParameter typeParameter : typeParameters) {
470
            TypeParameterDescriptor typeParameterDescriptor = makeUninitializedTypeParameter(containingDeclaration, typeParameter);
A
Andrey Breslav 已提交
471
            result.add(typeParameterDescriptor);
472 473 474 475
        }
        return result;
    }

476 477 478
    @NotNull
    private TypeParameterDescriptor makeUninitializedTypeParameter(@NotNull DeclarationDescriptor containingDeclaration, @NotNull PsiTypeParameter psiTypeParameter) {
        assert typeParameterDescriptorCache.get(psiTypeParameter) == null : psiTypeParameter.getText();
479
        TypeParameterDescriptor typeParameterDescriptor = TypeParameterDescriptor.createForFurtherModification(
480
                containingDeclaration,
A
Andrey Breslav 已提交
481
                Collections.<AnnotationDescriptor>emptyList(), // TODO
A
Andrey Breslav 已提交
482
                false,
483
                Variance.INVARIANT,
484 485
                psiTypeParameter.getName(),
                psiTypeParameter.getIndex()
486
        );
487
        typeParameterDescriptorCache.put(psiTypeParameter, new TypeParameterDescriptorInitialization(typeParameterDescriptor));
488 489 490
        return typeParameterDescriptor;
    }

491 492 493
    private void initializeTypeParameter(PsiTypeParameter typeParameter, TypeParameterDescriptorInitialization typeParameterDescriptorInitialization) {
        TypeParameterDescriptor typeParameterDescriptor = typeParameterDescriptorInitialization.descriptor;
        if (typeParameterDescriptorInitialization.origin == TypeParameterDescriptorOrigin.KOTLIN) {
494 495 496 497 498 499 500 501 502 503
            List<?> upperBounds = typeParameterDescriptorInitialization.upperBoundsForKotlin;
            if (upperBounds.size() == 0){
                typeParameterDescriptor.addUpperBound(JetStandardClasses.getNullableAnyType());
            } else {
                for (JetType upperBound : typeParameterDescriptorInitialization.upperBoundsForKotlin) {
                    typeParameterDescriptor.addUpperBound(upperBound);
                }
            }

            // TODO: lower bounds
504 505 506 507 508 509 510 511 512 513 514 515
        } 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 已提交
516 517
            }
        }
518
        typeParameterDescriptor.setInitialized();
519 520 521 522
    }

    private void initializeTypeParameters(PsiTypeParameterListOwner typeParameterListOwner) {
        for (PsiTypeParameter psiTypeParameter : typeParameterListOwner.getTypeParameters()) {
523
            initializeTypeParameter(psiTypeParameter, resolveTypeParameterInitialization(psiTypeParameter));
524
        }
A
Andrey Breslav 已提交
525 526 527
    }

    @NotNull
528 529
    private TypeParameterDescriptorInitialization resolveTypeParameter(@NotNull DeclarationDescriptor containingDeclaration, @NotNull PsiTypeParameter psiTypeParameter) {
        TypeParameterDescriptorInitialization typeParameterDescriptor = typeParameterDescriptorCache.get(psiTypeParameter);
530
        assert typeParameterDescriptor != null : psiTypeParameter.getText();
A
Andrey Breslav 已提交
531 532 533
        return typeParameterDescriptor;
    }

A
Andrey Breslav 已提交
534 535
    private Collection<? extends JetType> getSupertypes(PsiClass psiClass) {
        List<JetType> result = new ArrayList<JetType>();
536 537 538 539 540 541
        result.add(JetStandardClasses.getAnyType());
        transformSupertypeList(result, psiClass.getExtendsListTypes());
        transformSupertypeList(result, psiClass.getImplementsListTypes());
        return result;
    }

A
Andrey Breslav 已提交
542
    private void transformSupertypeList(List<JetType> result, PsiClassType[] extendsListTypes) {
543
        for (PsiClassType type : extendsListTypes) {
A
Andrey Breslav 已提交
544
            JetType transform = semanticServices.getTypeTransformer().transformToType(type);
545 546 547 548 549

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

550
    public NamespaceDescriptor resolveNamespace(String qualifiedName) {
551
        PsiPackage psiPackage = findPackage(qualifiedName);
552
        if (psiPackage == null) {
553
            PsiClass psiClass = findClass(qualifiedName);
A
Andrey Breslav 已提交
554 555
            if (psiClass == null) return null;
            return resolveNamespace(psiClass);
556 557 558 559
        }
        return resolveNamespace(psiPackage);
    }

560 561 562 563
    private PsiClass findClass(String qualifiedName) {
        return javaFacade.findClass(qualifiedName, javaSearchScope);
    }

564
    /*package*/ PsiPackage findPackage(String qualifiedName) {
565 566 567
        return javaFacade.findPackage(qualifiedName);
    }

568
    private NamespaceDescriptor resolveNamespace(@NotNull PsiPackage psiPackage) {
569 570 571 572 573
        ResolverNamespaceData namespaceData = namespaceDescriptorCache.get(psiPackage);
        if (namespaceData == null) {
            namespaceData = createJavaNamespaceDescriptor(psiPackage);
            namespaceDescriptorCache.put(psiPackage, namespaceData);
            namespaceDescriptorCacheByFqn.put(psiPackage.getQualifiedName(), namespaceData);
574
        }
575
        return namespaceData.namespaceDescriptor;
576 577
    }

A
Andrey Breslav 已提交
578
    private NamespaceDescriptor resolveNamespace(@NotNull PsiClass psiClass) {
579 580 581 582 583
        ResolverNamespaceData namespaceData = namespaceDescriptorCache.get(psiClass);
        if (namespaceData == null) {
            namespaceData = createJavaNamespaceDescriptor(psiClass);
            namespaceDescriptorCache.put(psiClass, namespaceData);
            namespaceDescriptorCacheByFqn.put(psiClass.getQualifiedName(), namespaceData);
A
Andrey Breslav 已提交
584
        }
585
        return namespaceData.namespaceDescriptor;
A
Andrey Breslav 已提交
586 587
    }

588 589
    private ResolverNamespaceData createJavaNamespaceDescriptor(@NotNull PsiPackage psiPackage) {
        ResolverNamespaceData namespaceData = new ResolverNamespaceData();
590
        String name = psiPackage.getName();
591
        namespaceData.namespaceDescriptor = new JavaNamespaceDescriptor(
592
                resolveParentDescriptor(psiPackage),
A
Andrey Breslav 已提交
593
                Collections.<AnnotationDescriptor>emptyList(), // TODO
594 595
                name == null ? JAVA_ROOT : name,
                name == null ? JAVA_ROOT : psiPackage.getQualifiedName()
596
        );
597

598 599 600 601 602
        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;
603 604
    }

605 606 607 608 609 610 611 612
    private DeclarationDescriptor resolveParentDescriptor(@NotNull PsiPackage psiPackage) {
        PsiPackage parentPackage = psiPackage.getParentPackage();
        if (parentPackage == null) {
            return null;
        }
        return resolveNamespace(parentPackage);
    }

613 614 615
    private ResolverNamespaceData createJavaNamespaceDescriptor(@NotNull final PsiClass psiClass) {
        ResolverNamespaceData namespaceData = new ResolverNamespaceData();
        namespaceData.namespaceDescriptor = new JavaNamespaceDescriptor(
616
                resolveParentDescriptor(psiClass),
A
Andrey Breslav 已提交
617
                Collections.<AnnotationDescriptor>emptyList(), // TODO
618 619
                psiClass.getName(),
                psiClass.getQualifiedName()
620
        );
621 622 623
        namespaceData.namespaceDescriptor.setMemberScope(new JavaClassMembersScope(namespaceData.namespaceDescriptor, psiClass, semanticServices, true));
        semanticServices.getTrace().record(BindingContext.NAMESPACE, psiClass, namespaceData.namespaceDescriptor);
        return namespaceData;
624
    }
625 626 627 628 629 630 631 632 633 634
    
    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;
        }
    }
635

636 637
    public ValueParameterDescriptors resolveParameterDescriptors(DeclarationDescriptor containingDeclaration,
            PsiParameter[] parameters, TypeVariableResolver typeVariableResolver) {
638
        List<ValueParameterDescriptor> result = new ArrayList<ValueParameterDescriptor>();
639
        JetType receiverType = null;
640
        int indexDelta = 0;
641 642
        for (int i = 0, parametersLength = parameters.length; i < parametersLength; i++) {
            PsiParameter parameter = parameters[i];
643
            JvmMethodParameterMeaning meaning = resolveParameterDescriptor(containingDeclaration, i + indexDelta, parameter, typeVariableResolver);
644 645
            if (meaning.kind == JvmMethodParameterKind.TYPE_INFO) {
                // TODO
646
                --indexDelta;
647 648 649 650 651 652
            } 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");
                }
653
                --indexDelta;
654
                receiverType = meaning.receiverType;
S
Stepan Koltsov 已提交
655
            }
656
        }
657
        return new ValueParameterDescriptors(receiverType, result);
658
    }
A
Andrey Breslav 已提交
659

660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692
    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
693 694
    private JvmMethodParameterMeaning resolveParameterDescriptor(DeclarationDescriptor containingDeclaration, int i,
            PsiParameter parameter, TypeVariableResolver typeVariableResolver) {
695 696 697 698 699 700 701 702 703 704
        PsiType psiType = parameter.getType();

        JetType varargElementType;
        if (psiType instanceof PsiEllipsisType) {
            PsiEllipsisType psiEllipsisType = (PsiEllipsisType) psiType;
            varargElementType = semanticServices.getTypeTransformer().transformToType(psiEllipsisType.getComponentType());
        }
        else {
            varargElementType = null;
        }
705 706 707

        boolean changeNullable = false;
        boolean nullable = true;
S
Stepan Koltsov 已提交
708
        String typeFromAnnotation = null;
709
        
710
        boolean receiver = false;
711
        boolean hasDefaultValue = false;
712
        
713 714 715 716
        // 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 已提交
717 718
            if (annotation.getQualifiedName().equals(JvmStdlibNames.JET_VALUE_PARAMETER.getFqName())) {
                PsiLiteralExpression nameExpression = (PsiLiteralExpression) annotation.findAttributeValue(JvmStdlibNames.JET_VALUE_PARAMETER_NAME_FIELD);
719 720 721 722
                if (nameExpression != null) {
                    name = (String) nameExpression.getValue();
                }
                
S
Stepan Koltsov 已提交
723
                PsiLiteralExpression nullableExpression = (PsiLiteralExpression) annotation.findAttributeValue(JvmStdlibNames.JET_VALUE_PARAMETER_NULLABLE_FIELD);
724 725 726 727 728 729 730
                if (nullableExpression != null) {
                    nullable = (Boolean) nullableExpression.getValue();
                } else {
                    // default value of parameter
                    nullable = false;
                    changeNullable = true;
                }
S
Stepan Koltsov 已提交
731
                
S
Stepan Koltsov 已提交
732
                PsiLiteralExpression signatureExpression = (PsiLiteralExpression) annotation.findAttributeValue(JvmStdlibNames.JET_VALUE_PARAMETER_TYPE_FIELD);
S
Stepan Koltsov 已提交
733 734 735
                if (signatureExpression != null) {
                    typeFromAnnotation = (String) signatureExpression.getValue();
                }
736 737


S
Stepan Koltsov 已提交
738
                PsiLiteralExpression receiverExpression = (PsiLiteralExpression) annotation.findAttributeValue(JvmStdlibNames.JET_VALUE_PARAMETER_RECEIVER_FIELD);
739
                if (receiverExpression != null) {
740
                    receiver = (Boolean) receiverExpression.getValue();
741
                }
742
                
743
                hasDefaultValue = getBooleanAnnotationAttributeValue(annotation, JvmStdlibNames.JET_VALUE_PARAMETER_HAS_DEFAULT_VALUE_FIELD, false);
744 745


S
Stepan Koltsov 已提交
746
            } else if (annotation.getQualifiedName().equals(JvmStdlibNames.JET_TYPE_PARAMETER.getFqName())) {
747
                return JvmMethodParameterMeaning.typeInfo(new Object());
748 749 750
            }
        }
        
S
Stepan Koltsov 已提交
751
        JetType outType;
752
        if (typeFromAnnotation != null && typeFromAnnotation.length() > 0) {
753
            outType = semanticServices.getTypeTransformer().transformToType(typeFromAnnotation, typeVariableResolver);
S
Stepan Koltsov 已提交
754 755 756
        } else {
            outType = semanticServices.getTypeTransformer().transformToType(psiType);
        }
757 758 759 760 761 762 763 764
        if (receiver) {
            return JvmMethodParameterMeaning.receiver(outType);
        } else {
            return JvmMethodParameterMeaning.regular(new ValueParameterDescriptorImpl(
                    containingDeclaration,
                    i,
                    Collections.<AnnotationDescriptor>emptyList(), // TODO
                    name,
S
Stepan Koltsov 已提交
765
                    false,
766
                    changeNullable ? TypeUtils.makeNullableAsSpecified(outType, nullable) : outType,
767
                    hasDefaultValue,
768 769 770
                    varargElementType
            ));
        }
771 772
    }

773 774 775 776 777 778 779 780 781
    private static boolean getBooleanAnnotationAttributeValue(PsiAnnotation annotation, String parameterName, boolean defaultValue) {
        PsiLiteralExpression receiverExpression = (PsiLiteralExpression) annotation.findAttributeValue(parameterName);
        if (receiverExpression != null) {
            return (Boolean) receiverExpression.getValue();
        } else {
            return defaultValue;
        }
    }

782
    /*
A
Andrey Breslav 已提交
783 784 785 786 787 788 789 790 791
    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 已提交
792
                Collections.<AnnotationDescriptor>emptyList(),
793
                Modality.FINAL,
794
                resolveVisibilityFromPsiModifiers(field),
A
Andrey Breslav 已提交
795 796
                !isFinal,
                null,
797
                DescriptorUtils.getExpectedThisObjectIfNeeded(containingDeclaration),
A
Andrey Breslav 已提交
798 799
                field.getName(),
                type);
800
        semanticServices.getTrace().record(BindingContext.VARIABLE, field, propertyDescriptor);
A
Andrey Breslav 已提交
801 802 803
        fieldDescriptorCache.put(field, propertyDescriptor);
        return propertyDescriptor;
    }
804 805 806 807 808 809 810
    */
    
    private static class PropertyKey {
        @NotNull
        private final String name;
        @NotNull
        private final PsiType type;
811 812
        @Nullable
        private final PsiType receiverType;
813

814
        private PropertyKey(@NotNull String name, @NotNull PsiType type, @Nullable PsiType receiverType) {
815 816
            this.name = name;
            this.type = type;
817
            this.receiverType = receiverType;
818 819 820 821 822 823 824 825 826 827
        }

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

            PropertyKey that = (PropertyKey) o;

            if (!name.equals(that.name)) return false;
828 829
            if (receiverType != null ? !receiverType.equals(that.receiverType) : that.receiverType != null)
                return false;
830 831 832 833 834 835 836 837 838
            if (!type.equals(that.type)) return false;

            return true;
        }

        @Override
        public int hashCode() {
            int result = name.hashCode();
            result = 31 * result + type.hashCode();
839
            result = 31 * result + (receiverType != null ? receiverType.hashCode() : 0);
840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863
            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;
864
                membersMap.put(new PropertyKey(field.getName(), field.getType(), null), members);
865 866 867 868 869 870 871 872 873 874 875 876 877
            }
        }
        
        for (PsiMethod method : clazz.getMethods()) {
            if (method.getModifierList().hasExplicitModifier(PsiModifier.STATIC) != staticMembers) {
                continue;
            }

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

            // TODO: "is" prefix
878
            // TODO: remove getJavaClass
879 880 881
            if (method.getName().startsWith(JvmAbi.GETTER_PREFIX)) {
                // TODO: some java properties too
                if (method.getModifierList().findAnnotation(JvmStdlibNames.JET_PROPERTY.getFqName()) != null) {
882
                    PsiType receiverType;
883
                    if (method.getParameterList().getParametersCount() == 0) {
884 885 886 887 888 889
                        receiverType = null;
                    } else if (method.getParameterList().getParametersCount() == 1) {
                        if (method.getParameterList().getParameters()[0].getModifierList().findAnnotation(JvmStdlibNames.JET_TYPE_PARAMETER.getFqName()) != null) {
                            receiverType = null;
                        } else {
                            receiverType = method.getParameterList().getParameters()[0].getType();
890
                        }
891 892 893
                    } else if (method.getParameterList().getParametersCount() == 2) {
                        if (method.getParameterList().getParameters()[1].getModifierList().findAnnotation(JvmStdlibNames.JET_TYPE_PARAMETER.getFqName()) == null) {
                            throw new IllegalStateException();
894
                        }
895 896 897
                        receiverType = method.getParameterList().getParameters()[0].getType();
                    } else {
                        throw new IllegalStateException();
898
                    }
899 900 901 902 903 904 905 906 907 908 909 910 911
                    
                    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(), receiverType);
                    MembersForProperty members = membersMap.get(key);
                    if (members == null) {
                        members = new MembersForProperty();
                        membersMap.put(key, members);
                    }
                    members.getter = method;
912 913 914
                }
            } else if (method.getName().startsWith(JvmAbi.SETTER_PREFIX)) {
                if (method.getModifierList().findAnnotation(JvmStdlibNames.JET_PROPERTY.getFqName()) != null) {
915 916 917 918 919 920 921 922 923 924 925 926 927
                    if (method.getParameterList().getParametersCount() == 0) {
                        throw new IllegalStateException();
                    }

                    int i = 0;

                    PsiType receiverType = null;
                    PsiParameter p1 = method.getParameterList().getParameters()[0];
                    PsiAnnotation p1a = p1.getModifierList().findAnnotation(JvmStdlibNames.JET_VALUE_PARAMETER.getFqName());
                    if (p1a != null) {
                        if (getBooleanAnnotationAttributeValue(p1a, JvmStdlibNames.JET_VALUE_PARAMETER_RECEIVER_FIELD, false)) {
                            receiverType = p1.getType();
                            ++i;
928 929
                        }
                    }
930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948
                    
                    while (i < method.getParameterList().getParametersCount() && method.getParameterList().getParameters()[i].getModifierList().findAnnotation(JvmStdlibNames.JET_TYPE_PARAMETER.getFqName()) != null) {
                        ++i;
                    }
                    
                    if (i + 1 != method.getParameterList().getParametersCount()) {
                        throw new IllegalStateException();
                    }
                    
                    PsiType propertyType = method.getParameterList().getParameters()[i].getType();

                    String propertyName = StringUtil.decapitalize(method.getName().substring(JvmAbi.SETTER_PREFIX.length()));
                    PropertyKey key = new PropertyKey(propertyName, propertyType, receiverType);
                    MembersForProperty members = membersMap.get(key);
                    if (members == null) {
                        members = new MembersForProperty();
                        membersMap.put(key, members);
                    }
                    members.setter = method;
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 977 978 979 980 981 982 983 984 985 986 987 988 989 990 991 992 993 994
                }
            }
        }
        
        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;
995
            PsiType receiverType = entry.getKey().receiverType;
996 997 998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027
            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;
            }
            
1028 1029 1030 1031 1032 1033 1034
            JetType receiverJetType;
            if (receiverType == null) {
                receiverJetType = null;
            } else {
                receiverJetType = semanticServices.getTypeTransformer().transformToType(receiverType);
            }
            
1035 1036 1037 1038 1039
            PropertyDescriptor propertyDescriptor = new PropertyDescriptor(
                    owner,
                    Collections.<AnnotationDescriptor>emptyList(),
                    isFinal && !staticMembers ? Modality.FINAL : Modality.OPEN, // TODO: abstract
                    resolveVisibilityFromPsiModifiers(anyMember),
1040 1041
                    isVar,
                    false,
1042
                    receiverJetType,
1043 1044 1045 1046 1047 1048 1049 1050 1051 1052
                    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 已提交
1053

A
Andrey Breslav 已提交
1054
    @NotNull
A
Andrey Breslav 已提交
1055 1056
    public Set<FunctionDescriptor> resolveFunctionGroup(@NotNull DeclarationDescriptor owner, @NotNull PsiClass psiClass, @Nullable ClassDescriptor classDescriptor, @NotNull String methodName, boolean staticMembers) {
        Set<FunctionDescriptor> writableFunctionGroup = Sets.newLinkedHashSet();
1057
        final Collection<HierarchicalMethodSignature> signatures = psiClass.getVisibleSignatures();
A
Andrey Breslav 已提交
1058
        TypeSubstitutor typeSubstitutor = createSubstitutorForGenericSupertypes(classDescriptor);
1059
        for (HierarchicalMethodSignature signature: signatures) {
1060
            if (!methodName.equals(signature.getName())) {
A
Andrey Breslav 已提交
1061 1062 1063
                 continue;
            }

1064
            FunctionDescriptor substitutedFunctionDescriptor = resolveHierarchicalSignatureToFunction(owner, psiClass, staticMembers, typeSubstitutor, signature);
1065
            if (substitutedFunctionDescriptor != null) {
A
Andrey Breslav 已提交
1066
                writableFunctionGroup.add(substitutedFunctionDescriptor);
1067
            }
A
Andrey Breslav 已提交
1068 1069 1070
        }
        return writableFunctionGroup;
    }
A
Andrey Breslav 已提交
1071

1072 1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086
    @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 已提交
1087 1088 1089 1090 1091 1092 1093 1094 1095 1096 1097
    public TypeSubstitutor createSubstitutorForGenericSupertypes(ClassDescriptor classDescriptor) {
        TypeSubstitutor typeSubstitutor;
        if (classDescriptor != null) {
            typeSubstitutor = TypeUtils.buildDeepSubstitutor(classDescriptor.getDefaultType());
        }
        else {
            typeSubstitutor = TypeSubstitutor.EMPTY;
        }
        return typeSubstitutor;
    }

1098 1099 1100 1101 1102 1103 1104 1105 1106 1107 1108 1109 1110 1111 1112 1113 1114 1115 1116 1117
    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 已提交
1118
    @Nullable
A
Andrey Breslav 已提交
1119
    public FunctionDescriptor resolveMethodToFunctionDescriptor(DeclarationDescriptor owner, PsiClass psiClass, TypeSubstitutor typeSubstitutorForGenericSuperclasses, PsiMethod method) {
A
Andrey Breslav 已提交
1120 1121 1122 1123 1124 1125 1126 1127 1128 1129 1130
        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;
        }
1131 1132 1133 1134 1135 1136 1137 1138 1139 1140 1141 1142 1143 1144 1145 1146 1147

        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;
        }

1148 1149 1150
        // TODO: ugly
        if (method.getModifierList().findAnnotation(JvmStdlibNames.JET_PROPERTY.getFqName()) != null) {
            return null;
1151
        }
1152

1153 1154 1155 1156 1157 1158 1159 1160 1161 1162 1163
        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();
        }
1164 1165 1166
        if (classDescriptor == null) {
            return null;
        }
A
Andrey Breslav 已提交
1167
        PsiParameter[] parameters = method.getParameterList().getParameters();
S
Stepan Koltsov 已提交
1168
        NamedFunctionDescriptorImpl functionDescriptorImpl = new NamedFunctionDescriptorImpl(
A
Andrey Breslav 已提交
1169 1170
                owner,
                Collections.<AnnotationDescriptor>emptyList(), // TODO
A
Andrey Breslav 已提交
1171 1172 1173
                method.getName()
        );
        methodDescriptorCache.put(method, functionDescriptorImpl);
1174 1175 1176 1177 1178 1179 1180 1181 1182 1183 1184 1185 1186 1187 1188 1189 1190 1191 1192 1193 1194 1195 1196 1197 1198 1199 1200

        // 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 已提交
1201
        functionDescriptorImpl.initialize(
1202
                valueParameterDescriptors.receiverType,
A
Andrey Breslav 已提交
1203
                DescriptorUtils.getExpectedThisObjectIfNeeded(classDescriptor),
1204
                methodTypeParameters,
1205
                valueParameterDescriptors.descriptors,
1206
                makeReturnType(returnType, method, new MethodTypeVariableResolver()),
1207
                Modality.convertFromFlags(method.hasModifierProperty(PsiModifier.ABSTRACT), !method.hasModifierProperty(PsiModifier.FINAL)),
1208
                resolveVisibilityFromPsiModifiers(method)
A
Andrey Breslav 已提交
1209
        );
1210
        semanticServices.getTrace().record(BindingContext.FUNCTION, method, functionDescriptorImpl);
A
Andrey Breslav 已提交
1211 1212 1213 1214 1215 1216
        FunctionDescriptor substitutedFunctionDescriptor = functionDescriptorImpl;
        if (method.getContainingClass() != psiClass) {
            substitutedFunctionDescriptor = functionDescriptorImpl.substitute(typeSubstitutorForGenericSuperclasses);
        }
        return substitutedFunctionDescriptor;
    }
1217

1218
    private List<TypeParameterDescriptor> resolveMethodTypeParameters(PsiMethod method, FunctionDescriptorImpl functionDescriptorImpl, TypeVariableResolver classTypeVariableResolver) {
1219
        for (PsiAnnotation annotation : method.getModifierList().getAnnotations()) {
S
Stepan Koltsov 已提交
1220 1221
            if (annotation.getQualifiedName().equals(JvmStdlibNames.JET_METHOD.getFqName())) {
                PsiLiteralExpression attributeValue = (PsiLiteralExpression) annotation.findAttributeValue(JvmStdlibNames.JET_METHOD_TYPE_PARAMETERS_FIELD);
1222 1223 1224
                if (attributeValue != null) {
                    String typeParametersString = (String) attributeValue.getValue();
                    if (typeParametersString != null) {
1225
                        List<TypeParameterDescriptor> r = resolveMethodTypeParametersFromJetSignature(typeParametersString, method, functionDescriptorImpl, classTypeVariableResolver);
1226 1227
                        initializeTypeParameters(method);
                        return r;
1228 1229 1230 1231 1232 1233 1234 1235 1236
                    }
                }
            }
        }
        
        List<TypeParameterDescriptor> typeParameters = makeUninitializedTypeParameters(functionDescriptorImpl, method.getTypeParameters());
        initializeTypeParameters(method);
        return typeParameters;
    }
1237 1238

    /**
1239
     * @see #resolveClassTypeParametersFromJetSignature(String, com.intellij.psi.PsiClass, JavaClassDescriptor) 
1240
     */
1241 1242 1243
    private List<TypeParameterDescriptor> resolveMethodTypeParametersFromJetSignature(String jetSignature, final PsiMethod method,
            final FunctionDescriptor functionDescriptor, final TypeVariableResolver classTypeVariableResolver)
    {
1244
        final List<TypeParameterDescriptor> r = new ArrayList<TypeParameterDescriptor>();
1245 1246 1247 1248 1249 1250 1251 1252 1253 1254 1255 1256 1257 1258 1259
        
        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);
            }
        }
        
1260 1261
        new JetSignatureReader(jetSignature).acceptFormalTypeParametersOnly(new JetSignatureExceptionsAdapter() {
            @Override
S
Stepan Koltsov 已提交
1262
            public JetSignatureVisitor visitFormalTypeParameter(final String name, final TypeInfoVariance variance) {
1263
                
1264
                return new JetSignatureTypeParameterVisitor(functionDescriptor, method, name, variance, new MyTypeVariableResolver()) {
1265
                    @Override
1266 1267
                    protected void done(TypeParameterDescriptor typeParameterDescriptor) {
                        r.add(typeParameterDescriptor);
1268 1269
                    }
                };
1270

1271 1272 1273 1274 1275
            }
        });
        return r;
    }

1276
    private JetType makeReturnType(PsiType returnType, PsiMethod method, TypeVariableResolver typeVariableResolver) {
1277 1278
        boolean changeNullable = false;
        boolean nullable = true;
S
Stepan Koltsov 已提交
1279 1280
        
        String returnTypeFromAnnotation = null;
1281 1282

        for (PsiAnnotation annotation : method.getModifierList().getAnnotations()) {
S
Stepan Koltsov 已提交
1283 1284
            if (annotation.getQualifiedName().equals(JvmStdlibNames.JET_METHOD.getFqName())) {
                PsiLiteralExpression nullableExpression = (PsiLiteralExpression) annotation.findAttributeValue(JvmStdlibNames.JET_METHOD_NULLABLE_RETURN_TYPE_FIELD);
1285 1286 1287 1288 1289 1290 1291
                if (nullableExpression != null) {
                    nullable = (Boolean) nullableExpression.getValue();
                } else {
                    // default value of parameter
                    nullable = false;
                    changeNullable = true;
                }
S
Stepan Koltsov 已提交
1292
                
S
Stepan Koltsov 已提交
1293
                PsiLiteralExpression returnTypeExpression = (PsiLiteralExpression) annotation.findAttributeValue(JvmStdlibNames.JET_METHOD_RETURN_TYPE_FIELD);
S
Stepan Koltsov 已提交
1294 1295 1296
                if (returnTypeExpression != null) {
                    returnTypeFromAnnotation = (String) returnTypeExpression.getValue();
                }
1297 1298
            }
        }
S
Stepan Koltsov 已提交
1299
        JetType transformedType;
1300
        if (returnTypeFromAnnotation != null && returnTypeFromAnnotation.length() > 0) {
1301
            transformedType = semanticServices.getTypeTransformer().transformToType(returnTypeFromAnnotation, typeVariableResolver);
S
Stepan Koltsov 已提交
1302 1303 1304
        } else {
            transformedType = semanticServices.getTypeTransformer().transformToType(returnType);
        }
1305 1306 1307 1308 1309 1310 1311
        if (changeNullable) {
            return TypeUtils.makeNullableAsSpecified(transformedType, nullable);
        } else {
            return transformedType;
        }
    }

1312
    private static Visibility resolveVisibilityFromPsiModifiers(PsiModifierListOwner modifierListOwner) {
1313 1314 1315 1316 1317 1318
        //TODO report error
        return modifierListOwner.hasModifierProperty(PsiModifier.PUBLIC) ? Visibility.PUBLIC :
                                        (modifierListOwner.hasModifierProperty(PsiModifier.PRIVATE) ? Visibility.PRIVATE :
                                        (modifierListOwner.hasModifierProperty(PsiModifier.PROTECTED) ? Visibility.PROTECTED : Visibility.INTERNAL));
    }

1319 1320
    @NotNull
    private TypeParameterDescriptorInitialization resolveTypeParameterInitialization(PsiTypeParameter typeParameter) {
1321 1322 1323 1324 1325 1326 1327 1328 1329 1330 1331 1332 1333 1334 1335 1336 1337 1338 1339 1340 1341 1342 1343 1344
        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);
    }
1345 1346 1347 1348

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