JavaDescriptorResolver.java 62.6 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 10 11 12 13 14 15 16 17 18 19 20 21 22 23
import com.intellij.psi.HierarchicalMethodSignature;
import com.intellij.psi.JavaPsiFacade;
import com.intellij.psi.PsiClass;
import com.intellij.psi.PsiClassType;
import com.intellij.psi.PsiElement;
import com.intellij.psi.PsiEllipsisType;
import com.intellij.psi.PsiField;
import com.intellij.psi.PsiJavaFile;
import com.intellij.psi.PsiMethod;
import com.intellij.psi.PsiModifier;
import com.intellij.psi.PsiModifierListOwner;
import com.intellij.psi.PsiPackage;
import com.intellij.psi.PsiType;
import com.intellij.psi.PsiTypeParameter;
import com.intellij.psi.PsiTypeParameterListOwner;
24
import com.intellij.psi.search.DelegatingGlobalSearchScope;
25
import com.intellij.psi.search.GlobalSearchScope;
26
import jet.typeinfo.TypeInfoVariance;
27 28
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
29 30 31 32 33 34 35 36 37 38 39
import org.jetbrains.jet.lang.descriptors.ClassDescriptor;
import org.jetbrains.jet.lang.descriptors.ClassKind;
import org.jetbrains.jet.lang.descriptors.ConstructorDescriptorImpl;
import org.jetbrains.jet.lang.descriptors.DeclarationDescriptor;
import org.jetbrains.jet.lang.descriptors.DeclarationDescriptorImpl;
import org.jetbrains.jet.lang.descriptors.DeclarationDescriptorVisitor;
import org.jetbrains.jet.lang.descriptors.FunctionDescriptor;
import org.jetbrains.jet.lang.descriptors.Modality;
import org.jetbrains.jet.lang.descriptors.NamedFunctionDescriptorImpl;
import org.jetbrains.jet.lang.descriptors.NamespaceDescriptor;
import org.jetbrains.jet.lang.descriptors.PropertyDescriptor;
40 41
import org.jetbrains.jet.lang.descriptors.PropertyGetterDescriptor;
import org.jetbrains.jet.lang.descriptors.PropertySetterDescriptor;
42 43 44 45 46
import org.jetbrains.jet.lang.descriptors.TypeParameterDescriptor;
import org.jetbrains.jet.lang.descriptors.ValueParameterDescriptor;
import org.jetbrains.jet.lang.descriptors.ValueParameterDescriptorImpl;
import org.jetbrains.jet.lang.descriptors.VariableDescriptor;
import org.jetbrains.jet.lang.descriptors.Visibility;
A
Andrey Breslav 已提交
47
import org.jetbrains.jet.lang.descriptors.annotations.AnnotationDescriptor;
48
import org.jetbrains.jet.lang.resolve.BindingContext;
49
import org.jetbrains.jet.lang.resolve.DescriptorUtils;
50 51 52 53 54 55 56
import org.jetbrains.jet.lang.resolve.java.kt.JetClassAnnotation;
import org.jetbrains.jet.lang.types.JetStandardClasses;
import org.jetbrains.jet.lang.types.JetType;
import org.jetbrains.jet.lang.types.TypeConstructorImpl;
import org.jetbrains.jet.lang.types.TypeSubstitutor;
import org.jetbrains.jet.lang.types.TypeUtils;
import org.jetbrains.jet.lang.types.Variance;
57
import org.jetbrains.jet.plugin.JetFileType;
58
import org.jetbrains.jet.rt.signature.JetSignatureAdapter;
59 60 61
import org.jetbrains.jet.rt.signature.JetSignatureExceptionsAdapter;
import org.jetbrains.jet.rt.signature.JetSignatureReader;
import org.jetbrains.jet.rt.signature.JetSignatureVisitor;
62

63 64 65 66 67 68
import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import java.util.List;
import java.util.Map;
import java.util.Set;
69 70 71 72 73

/**
 * @author abreslav
 */
public class JavaDescriptorResolver {
74 75
    
    public static String JAVA_ROOT = "<java_root>";
76

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

79 80
        @Override
        public DeclarationDescriptor substitute(TypeSubstitutor substitutor) {
81
            throw new UnsupportedOperationException();
82 83
        }

84 85
        @Override
        public <R, D> R accept(DeclarationDescriptorVisitor<R, D> visitor, D data) {
86
            return visitor.visitDeclarationDescriptor(this, data);
87 88 89
        }
    };

A
Andrey Breslav 已提交
90
    /*package*/ static final DeclarationDescriptor JAVA_CLASS_OBJECT = new DeclarationDescriptorImpl(null, Collections.<AnnotationDescriptor>emptyList(), "<java_class_object_emulation>") {
A
Andrey Breslav 已提交
91 92 93
        @NotNull
        @Override
        public DeclarationDescriptor substitute(TypeSubstitutor substitutor) {
94
            throw new UnsupportedOperationException();
A
Andrey Breslav 已提交
95 96 97 98 99 100 101
        }

        @Override
        public <R, D> R accept(DeclarationDescriptorVisitor<R, D> visitor, D data) {
            return visitor.visitDeclarationDescriptor(this, data);
        }
    };
102 103 104 105 106 107 108 109 110
    
    private enum TypeParameterDescriptorOrigin {
        JAVA,
        KOTLIN,
    }
    
    private static class TypeParameterDescriptorInitialization {
        private final TypeParameterDescriptorOrigin origin;
        private final TypeParameterDescriptor descriptor;
111 112 113 114
        @Nullable
        private final List<JetType> upperBoundsForKotlin;
        @Nullable
        private final List<JetType> lowerBoundsForKotlin;
115

116 117
        private TypeParameterDescriptorInitialization(TypeParameterDescriptor descriptor) {
            this.origin = TypeParameterDescriptorOrigin.JAVA;
118
            this.descriptor = descriptor;
119 120 121 122 123 124 125 126 127 128
            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;
129 130
        }
    }
131 132 133 134 135 136
    
    private static abstract class ResolverScopeData {
        @Nullable
        private Set<VariableDescriptor> properties;
        private boolean kotlin;
    }
A
Andrey Breslav 已提交
137

138
    private static class ResolverClassData extends ResolverScopeData {
139 140 141 142 143 144 145 146 147
        private JavaClassDescriptor classDescriptor;
        private boolean kotlin;

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

148
    private static class ResolverNamespaceData extends ResolverScopeData {
149 150 151 152 153 154 155 156 157
        private JavaNamespaceDescriptor namespaceDescriptor;
        private boolean kotlin;

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

158
    protected final Map<String, ResolverClassData> classDescriptorCache = Maps.newHashMap();
159 160 161
    protected final Map<String, ResolverNamespaceData> namespaceDescriptorCacheByFqn = Maps.newHashMap();
    protected final Map<PsiElement, ResolverNamespaceData> namespaceDescriptorCache = Maps.newHashMap();

162
    private final Map<PsiTypeParameter, TypeParameterDescriptorInitialization> typeParameterDescriptorCache = Maps.newHashMap();
A
Andrey Breslav 已提交
163
    protected final Map<PsiMethod, FunctionDescriptor> methodDescriptorCache = Maps.newHashMap();
A
Andrey Breslav 已提交
164
    protected final Map<PsiField, VariableDescriptor> fieldDescriptorCache = Maps.newHashMap();
165 166 167 168 169 170
    protected final JavaPsiFacade javaFacade;
    protected final GlobalSearchScope javaSearchScope;
    protected final JavaSemanticServices semanticServices;

    public JavaDescriptorResolver(Project project, JavaSemanticServices semanticServices) {
        this.javaFacade = JavaPsiFacade.getInstance(project);
171 172 173 174 175 176
        this.javaSearchScope = new DelegatingGlobalSearchScope(GlobalSearchScope.allScope(project)) {
            @Override
            public boolean contains(VirtualFile file) {
                return myBaseScope.contains(file) && file.getFileType() != JetFileType.INSTANCE;
            }
        };
177 178 179
        this.semanticServices = semanticServices;
    }

180
    @Nullable
181 182
    public ClassDescriptor resolveClass(@NotNull PsiClass psiClass) {
        String qualifiedName = psiClass.getQualifiedName();
183

184 185 186 187
        if (qualifiedName.endsWith(JvmAbi.TRAIT_IMPL_SUFFIX)) {
            // TODO: only if -$$TImpl class is created by Kotlin
            return null;
        }
188

189
        // First, let's check that this is a real Java class, not a Java's view on a Kotlin class:
190 191 192 193 194
        ClassDescriptor kotlinClassDescriptor = semanticServices.getKotlinClassDescriptor(qualifiedName);
        if (kotlinClassDescriptor != null) {
            return kotlinClassDescriptor;
        }

195
        // Not let's take a descriptor of a Java class
196 197 198 199
        ResolverClassData classData = classDescriptorCache.get(qualifiedName);
        if (classData == null) {
            classData = createJavaClassDescriptor(psiClass);
            classDescriptorCache.put(qualifiedName, classData);
200
        }
201
        return classData.getClassDescriptor();
202 203 204 205
    }

    @Nullable
    public ClassDescriptor resolveClass(@NotNull String qualifiedName) {
206

207 208 209 210 211
        if (qualifiedName.endsWith(JvmAbi.TRAIT_IMPL_SUFFIX)) {
            // TODO: only if -$$TImpl class is created by Kotlin
            return null;
        }
        
212
        // First, let's check that this is a real Java class, not a Java's view on a Kotlin class:
213 214 215 216 217
        ClassDescriptor kotlinClassDescriptor = semanticServices.getKotlinClassDescriptor(qualifiedName);
        if (kotlinClassDescriptor != null) {
            return kotlinClassDescriptor;
        }

218
        // Not let's take a descriptor of a Java class
219 220
        ResolverClassData classData = classDescriptorCache.get(qualifiedName);
        if (classData == null) {
221
            PsiClass psiClass = findClass(qualifiedName);
222 223 224
            if (psiClass == null) {
                return null;
            }
225
            classData = createJavaClassDescriptor(psiClass);
226
        }
227
        return classData.getClassDescriptor();
228 229
    }

230
    private ResolverClassData createJavaClassDescriptor(@NotNull final PsiClass psiClass) {
A
Andrey Breslav 已提交
231 232 233
        assert !classDescriptorCache.containsKey(psiClass.getQualifiedName()) : psiClass.getQualifiedName();
        classDescriptorCache.put(psiClass.getQualifiedName(), null); // TODO

234
        String name = psiClass.getName();
235 236
        ResolverClassData classData = new ResolverClassData();
        classData.classDescriptor = new JavaClassDescriptor(
237
                resolveParentDescriptor(psiClass), psiClass.isInterface() ? ClassKind.TRAIT : ClassKind.CLASS
238
        );
239
        classData.classDescriptor.setName(name);
240
        
241 242 243 244 245 246 247 248 249
        class OuterClassTypeVariableResolver implements TypeVariableResolver {

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

A
Andrey Breslav 已提交
250
        List<JetType> supertypes = new ArrayList<JetType>();
251 252 253
        List<TypeParameterDescriptor> typeParameters = resolveClassTypeParameters(psiClass, classData, new OuterClassTypeVariableResolver());
        classData.classDescriptor.setTypeConstructor(new TypeConstructorImpl(
                classData.classDescriptor,
A
Andrey Breslav 已提交
254
                Collections.<AnnotationDescriptor>emptyList(), // TODO
255
                // TODO
256
                psiClass.hasModifierProperty(PsiModifier.FINAL),
A
Andrey Breslav 已提交
257
                name,
A
Andrey Breslav 已提交
258
                typeParameters,
A
Andrey Breslav 已提交
259 260
                supertypes
        ));
261
        classData.classDescriptor.setModality(Modality.convertFromFlags(
262 263
                psiClass.hasModifierProperty(PsiModifier.ABSTRACT) || psiClass.isInterface(),
                !psiClass.hasModifierProperty(PsiModifier.FINAL))
A
Andrey Breslav 已提交
264
        );
265 266 267
        classData.classDescriptor.setVisibility(resolveVisibilityFromPsiModifiers(psiClass));
        classDescriptorCache.put(psiClass.getQualifiedName(), classData);
        classData.classDescriptor.setUnsubstitutedMemberScope(new JavaClassMembersScope(classData.classDescriptor, psiClass, semanticServices, false));
268

269 270
        // UGLY HACK (Andrey Breslav is not sure what did he mean)
        initializeTypeParameters(psiClass);
271

A
Andrey Breslav 已提交
272
        supertypes.addAll(getSupertypes(psiClass));
273
        if (psiClass.isInterface()) {
274
            classData.classDescriptor.setSuperclassType(JetStandardClasses.getAnyType()); // TODO : Make it java.lang.Object
275 276 277 278 279 280 281
        }
        else {
            PsiClassType[] extendsListTypes = psiClass.getExtendsListTypes();
            assert extendsListTypes.length == 0 || extendsListTypes.length == 1;
            JetType superclassType = extendsListTypes.length == 0
                                            ? JetStandardClasses.getAnyType()
                                            : semanticServices.getTypeTransformer().transformToType(extendsListTypes[0]);
282
            classData.classDescriptor.setSuperclassType(superclassType);
283
        }
A
Andrey Breslav 已提交
284 285

        PsiMethod[] psiConstructors = psiClass.getConstructors();
286 287

        if (psiConstructors.length == 0) {
A
Andrey Breslav 已提交
288 289 290 291 292
            // We need to create default constructors for classes and abstract classes.
            // Example:
            // class Kotlin() : Java() {}
            // abstract public class Java {}
            if (!psiClass.isInterface()) {
293
                ConstructorDescriptorImpl constructorDescriptor = new ConstructorDescriptorImpl(
294
                        classData.classDescriptor,
A
Andrey Breslav 已提交
295
                        Collections.<AnnotationDescriptor>emptyList(),
296
                        false);
297 298 299
                constructorDescriptor.initialize(typeParameters, Collections.<ValueParameterDescriptor>emptyList(), Modality.FINAL, classData.classDescriptor.getVisibility());
                constructorDescriptor.setReturnType(classData.classDescriptor.getDefaultType());
                classData.classDescriptor.addConstructor(constructorDescriptor);
300
                semanticServices.getTrace().record(BindingContext.CONSTRUCTOR, psiClass, constructorDescriptor);
301 302 303
            }
        }
        else {
304 305 306 307 308
            for (PsiMethod psiConstructor : psiConstructors) {
                PsiMethodWrapper constructor = new PsiMethodWrapper(psiConstructor);

                if (constructor.getJetConstructor().hidden()) {
                    continue;
309 310
                }

311
                ConstructorDescriptorImpl constructorDescriptor = new ConstructorDescriptorImpl(
312
                        classData.classDescriptor,
A
Andrey Breslav 已提交
313
                        Collections.<AnnotationDescriptor>emptyList(), // TODO
314
                        false);
315
                ValueParameterDescriptors valueParameterDescriptors = resolveParameterDescriptors(constructorDescriptor,
316
                        constructor.getParameters(),
317 318
                        new TypeParameterListTypeVariableResolver(typeParameters) // TODO: outer too
                    );
319 320 321 322
                if (valueParameterDescriptors.receiverType != null) {
                    throw new IllegalStateException();
                }
                constructorDescriptor.initialize(typeParameters, valueParameterDescriptors.descriptors, Modality.FINAL,
323
                                                 resolveVisibilityFromPsiModifiers(psiConstructor));
324 325
                constructorDescriptor.setReturnType(classData.classDescriptor.getDefaultType());
                classData.classDescriptor.addConstructor(constructorDescriptor);
326
                semanticServices.getTrace().record(BindingContext.CONSTRUCTOR, psiConstructor, constructorDescriptor);
327
            }
A
Andrey Breslav 已提交
328
        }
329

330
        semanticServices.getTrace().record(BindingContext.CLASS, psiClass, classData.classDescriptor);
331

332
        return classData;
333 334
    }

335
    private List<TypeParameterDescriptor> resolveClassTypeParameters(PsiClass psiClass, ResolverClassData classData, TypeVariableResolver typeVariableResolver) {
336 337 338 339 340 341
        JetClassAnnotation jetClassAnnotation = JetClassAnnotation.get(psiClass);
        classData.kotlin = jetClassAnnotation.isDefined();
        
        if (jetClassAnnotation.signature().length() > 0) {
            return resolveClassTypeParametersFromJetSignature(
                    jetClassAnnotation.signature(), psiClass, classData.classDescriptor, typeVariableResolver);
342
        }
343

344
        return makeUninitializedTypeParameters(classData.classDescriptor, psiClass.getTypeParameters());
345 346
    }

347
    @NotNull
348
    private PsiTypeParameter getPsiTypeParameterByName(PsiTypeParameterListOwner clazz, String name) {
349 350 351 352 353
        for (PsiTypeParameter typeParameter : clazz.getTypeParameters()) {
            if (typeParameter.getName().equals(name)) {
                return typeParameter; 
            }
        }
354 355 356
        throw new IllegalStateException("PsiTypeParameter '" + name + "' is not found");
    }

S
Stepan Koltsov 已提交
357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373

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


374 375 376 377 378
    private abstract class JetSignatureTypeParameterVisitor extends JetSignatureExceptionsAdapter {
        
        private final DeclarationDescriptor containingDeclaration;
        private final PsiTypeParameterListOwner psiOwner;
        private final String name;
379
        private final int index;
380
        private final TypeInfoVariance variance;
381
        private final TypeVariableResolver typeVariableResolver;
382 383

        protected JetSignatureTypeParameterVisitor(DeclarationDescriptor containingDeclaration, PsiTypeParameterListOwner psiOwner,
384
                String name, int index, TypeInfoVariance variance, TypeVariableResolver typeVariableResolver)
385
        {
386 387 388 389
            if (name.isEmpty()) {
                throw new IllegalStateException();
            }
            
390 391 392
            this.containingDeclaration = containingDeclaration;
            this.psiOwner = psiOwner;
            this.name = name;
393
            this.index = index;
394
            this.variance = variance;
395
            this.typeVariableResolver = typeVariableResolver;
396 397 398 399
        }

        List<JetType> upperBounds = new ArrayList<JetType>();
        List<JetType> lowerBounds = new ArrayList<JetType>();
S
Stepan Koltsov 已提交
400
        
401 402
        @Override
        public JetSignatureVisitor visitClassBound() {
403
            return new JetTypeJetSignatureReader(semanticServices, semanticServices.getJetSemanticServices().getStandardLibrary(), typeVariableResolver) {
404 405
                @Override
                protected void done(@NotNull JetType jetType) {
S
Stepan Koltsov 已提交
406 407 408
                    if (isJavaLangObject(jetType)) {
                        return;
                    }
409 410 411 412 413 414 415
                    upperBounds.add(jetType);
                }
            };
        }

        @Override
        public JetSignatureVisitor visitInterfaceBound() {
416
            return new JetTypeJetSignatureReader(semanticServices, semanticServices.getJetSemanticServices().getStandardLibrary(), typeVariableResolver) {
417 418 419 420 421 422 423 424 425 426 427 428 429 430 431
                @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,
432
                    index);
433 434 435 436 437 438
            PsiTypeParameter psiTypeParameter = getPsiTypeParameterByName(psiOwner, name);
            typeParameterDescriptorCache.put(psiTypeParameter, new TypeParameterDescriptorInitialization(typeParameter, upperBounds, lowerBounds));
            done(typeParameter);
        }
        
        protected abstract void done(TypeParameterDescriptor typeParameterDescriptor);
439 440
    }

441 442 443
    /**
     * @see #resolveMethodTypeParametersFromJetSignature(String, FunctionDescriptor)
     */
444 445
    private List<TypeParameterDescriptor> resolveClassTypeParametersFromJetSignature(String jetSignature, final PsiClass clazz,
            final JavaClassDescriptor classDescriptor, final TypeVariableResolver outerClassTypeVariableResolver) {
446
        final List<TypeParameterDescriptor> r = new ArrayList<TypeParameterDescriptor>();
447 448 449 450 451 452 453 454 455 456 457 458 459 460 461
        
        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);
            }
        }
        
462
        new JetSignatureReader(jetSignature).accept(new JetSignatureExceptionsAdapter() {
463 464
            private int formalTypeParameterIndex = 0;
            
465 466
            @Override
            public JetSignatureVisitor visitFormalTypeParameter(final String name, final TypeInfoVariance variance) {
467
                return new JetSignatureTypeParameterVisitor(classDescriptor, clazz, name, formalTypeParameterIndex++, variance, new MyTypeVariableResolver()) {
468
                    @Override
469 470
                    protected void done(TypeParameterDescriptor typeParameterDescriptor) {
                        r.add(typeParameterDescriptor);
471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489
                    }
                };
            }

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

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

490 491 492
    private DeclarationDescriptor resolveParentDescriptor(PsiClass psiClass) {
        PsiClass containingClass = psiClass.getContainingClass();
        if (containingClass != null) {
493
            return resolveClass(containingClass);
494 495 496 497 498 499 500
        }
        
        PsiJavaFile containingFile = (PsiJavaFile) psiClass.getContainingFile();
        String packageName = containingFile.getPackageName();
        return resolveNamespace(packageName);
    }

501
    private List<TypeParameterDescriptor> makeUninitializedTypeParameters(@NotNull DeclarationDescriptor containingDeclaration, @NotNull PsiTypeParameter[] typeParameters) {
502 503
        List<TypeParameterDescriptor> result = Lists.newArrayList();
        for (PsiTypeParameter typeParameter : typeParameters) {
504
            TypeParameterDescriptor typeParameterDescriptor = makeUninitializedTypeParameter(containingDeclaration, typeParameter);
A
Andrey Breslav 已提交
505
            result.add(typeParameterDescriptor);
506 507 508 509
        }
        return result;
    }

510 511 512
    @NotNull
    private TypeParameterDescriptor makeUninitializedTypeParameter(@NotNull DeclarationDescriptor containingDeclaration, @NotNull PsiTypeParameter psiTypeParameter) {
        assert typeParameterDescriptorCache.get(psiTypeParameter) == null : psiTypeParameter.getText();
513
        TypeParameterDescriptor typeParameterDescriptor = TypeParameterDescriptor.createForFurtherModification(
514
                containingDeclaration,
A
Andrey Breslav 已提交
515
                Collections.<AnnotationDescriptor>emptyList(), // TODO
A
Andrey Breslav 已提交
516
                false,
517
                Variance.INVARIANT,
518 519
                psiTypeParameter.getName(),
                psiTypeParameter.getIndex()
520
        );
521
        typeParameterDescriptorCache.put(psiTypeParameter, new TypeParameterDescriptorInitialization(typeParameterDescriptor));
522 523 524
        return typeParameterDescriptor;
    }

525 526 527
    private void initializeTypeParameter(PsiTypeParameter typeParameter, TypeParameterDescriptorInitialization typeParameterDescriptorInitialization) {
        TypeParameterDescriptor typeParameterDescriptor = typeParameterDescriptorInitialization.descriptor;
        if (typeParameterDescriptorInitialization.origin == TypeParameterDescriptorOrigin.KOTLIN) {
528 529 530 531 532 533 534 535 536 537
            List<?> upperBounds = typeParameterDescriptorInitialization.upperBoundsForKotlin;
            if (upperBounds.size() == 0){
                typeParameterDescriptor.addUpperBound(JetStandardClasses.getNullableAnyType());
            } else {
                for (JetType upperBound : typeParameterDescriptorInitialization.upperBoundsForKotlin) {
                    typeParameterDescriptor.addUpperBound(upperBound);
                }
            }

            // TODO: lower bounds
538 539 540 541 542 543 544 545 546 547 548 549
        } 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 已提交
550 551
            }
        }
552
        typeParameterDescriptor.setInitialized();
553 554 555 556
    }

    private void initializeTypeParameters(PsiTypeParameterListOwner typeParameterListOwner) {
        for (PsiTypeParameter psiTypeParameter : typeParameterListOwner.getTypeParameters()) {
557
            initializeTypeParameter(psiTypeParameter, resolveTypeParameterInitialization(psiTypeParameter));
558
        }
A
Andrey Breslav 已提交
559 560 561
    }

    @NotNull
562 563
    private TypeParameterDescriptorInitialization resolveTypeParameter(@NotNull DeclarationDescriptor containingDeclaration, @NotNull PsiTypeParameter psiTypeParameter) {
        TypeParameterDescriptorInitialization typeParameterDescriptor = typeParameterDescriptorCache.get(psiTypeParameter);
S
Stepan Koltsov 已提交
564 565 566 567
        if (typeParameterDescriptor == null) {
            // TODO: report properly without crashing compiler
            throw new IllegalStateException("failed to resolve type parameter: " + psiTypeParameter.getName());
        }
A
Andrey Breslav 已提交
568 569 570
        return typeParameterDescriptor;
    }

A
Andrey Breslav 已提交
571 572
    private Collection<? extends JetType> getSupertypes(PsiClass psiClass) {
        List<JetType> result = new ArrayList<JetType>();
573 574 575 576 577 578
        result.add(JetStandardClasses.getAnyType());
        transformSupertypeList(result, psiClass.getExtendsListTypes());
        transformSupertypeList(result, psiClass.getImplementsListTypes());
        return result;
    }

A
Andrey Breslav 已提交
579
    private void transformSupertypeList(List<JetType> result, PsiClassType[] extendsListTypes) {
580
        for (PsiClassType type : extendsListTypes) {
A
Andrey Breslav 已提交
581
            JetType transform = semanticServices.getTypeTransformer().transformToType(type);
582 583 584 585 586

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

587
    public NamespaceDescriptor resolveNamespace(String qualifiedName) {
588
        PsiPackage psiPackage = findPackage(qualifiedName);
589
        if (psiPackage == null) {
590
            PsiClass psiClass = findClass(qualifiedName);
A
Andrey Breslav 已提交
591 592
            if (psiClass == null) return null;
            return resolveNamespace(psiClass);
593 594 595 596
        }
        return resolveNamespace(psiPackage);
    }

597 598 599 600
    private PsiClass findClass(String qualifiedName) {
        return javaFacade.findClass(qualifiedName, javaSearchScope);
    }

601
    /*package*/ PsiPackage findPackage(String qualifiedName) {
602 603 604
        return javaFacade.findPackage(qualifiedName);
    }

605
    private NamespaceDescriptor resolveNamespace(@NotNull PsiPackage psiPackage) {
606 607 608 609 610
        ResolverNamespaceData namespaceData = namespaceDescriptorCache.get(psiPackage);
        if (namespaceData == null) {
            namespaceData = createJavaNamespaceDescriptor(psiPackage);
            namespaceDescriptorCache.put(psiPackage, namespaceData);
            namespaceDescriptorCacheByFqn.put(psiPackage.getQualifiedName(), namespaceData);
611
        }
612
        return namespaceData.namespaceDescriptor;
613 614
    }

A
Andrey Breslav 已提交
615
    private NamespaceDescriptor resolveNamespace(@NotNull PsiClass psiClass) {
616 617 618 619 620
        ResolverNamespaceData namespaceData = namespaceDescriptorCache.get(psiClass);
        if (namespaceData == null) {
            namespaceData = createJavaNamespaceDescriptor(psiClass);
            namespaceDescriptorCache.put(psiClass, namespaceData);
            namespaceDescriptorCacheByFqn.put(psiClass.getQualifiedName(), namespaceData);
A
Andrey Breslav 已提交
621
        }
622
        return namespaceData.namespaceDescriptor;
A
Andrey Breslav 已提交
623 624
    }

625 626
    private ResolverNamespaceData createJavaNamespaceDescriptor(@NotNull PsiPackage psiPackage) {
        ResolverNamespaceData namespaceData = new ResolverNamespaceData();
627
        String name = psiPackage.getName();
628
        namespaceData.namespaceDescriptor = new JavaNamespaceDescriptor(
629
                resolveParentDescriptor(psiPackage),
A
Andrey Breslav 已提交
630
                Collections.<AnnotationDescriptor>emptyList(), // TODO
631 632
                name == null ? JAVA_ROOT : name,
                name == null ? JAVA_ROOT : psiPackage.getQualifiedName()
633
        );
634

635 636 637 638 639
        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;
640 641
    }

642 643 644 645 646 647 648 649
    private DeclarationDescriptor resolveParentDescriptor(@NotNull PsiPackage psiPackage) {
        PsiPackage parentPackage = psiPackage.getParentPackage();
        if (parentPackage == null) {
            return null;
        }
        return resolveNamespace(parentPackage);
    }

650 651 652
    private ResolverNamespaceData createJavaNamespaceDescriptor(@NotNull final PsiClass psiClass) {
        ResolverNamespaceData namespaceData = new ResolverNamespaceData();
        namespaceData.namespaceDescriptor = new JavaNamespaceDescriptor(
653
                resolveParentDescriptor(psiClass),
A
Andrey Breslav 已提交
654
                Collections.<AnnotationDescriptor>emptyList(), // TODO
655 656
                psiClass.getName(),
                psiClass.getQualifiedName()
657
        );
658 659 660
        namespaceData.namespaceDescriptor.setMemberScope(new JavaClassMembersScope(namespaceData.namespaceDescriptor, psiClass, semanticServices, true));
        semanticServices.getTrace().record(BindingContext.NAMESPACE, psiClass, namespaceData.namespaceDescriptor);
        return namespaceData;
661
    }
662 663 664 665 666 667 668 669 670 671
    
    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;
        }
    }
672

673 674
    private ValueParameterDescriptors resolveParameterDescriptors(DeclarationDescriptor containingDeclaration,
            List<PsiParameterWrapper> parameters, TypeVariableResolver typeVariableResolver) {
675
        List<ValueParameterDescriptor> result = new ArrayList<ValueParameterDescriptor>();
676
        JetType receiverType = null;
677
        int indexDelta = 0;
678 679
        for (int i = 0, parametersLength = parameters.size(); i < parametersLength; i++) {
            PsiParameterWrapper parameter = parameters.get(i);
680
            JvmMethodParameterMeaning meaning = resolveParameterDescriptor(containingDeclaration, i + indexDelta, parameter, typeVariableResolver);
681 682
            if (meaning.kind == JvmMethodParameterKind.TYPE_INFO) {
                // TODO
683
                --indexDelta;
684 685 686 687 688 689
            } 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");
                }
690
                --indexDelta;
691
                receiverType = meaning.receiverType;
S
Stepan Koltsov 已提交
692
            }
693
        }
694
        return new ValueParameterDescriptors(receiverType, result);
695
    }
A
Andrey Breslav 已提交
696

697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729
    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
730
    private JvmMethodParameterMeaning resolveParameterDescriptor(DeclarationDescriptor containingDeclaration, int i,
731 732 733 734 735 736 737
            PsiParameterWrapper parameter, TypeVariableResolver typeVariableResolver) {

        if (parameter.getJetTypeParameter().isDefined()) {
            return JvmMethodParameterMeaning.typeInfo(new Object());
        }

        PsiType psiType = parameter.getPsiParameter().getType();
738 739 740 741 742 743 744 745 746

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

748
        boolean nullable = parameter.getJetValueParameter().nullable();
749

750 751
        // TODO: must be very slow, make it lazy?
        String name = parameter.getPsiParameter().getName() != null ? parameter.getPsiParameter().getName() : "p" + i;
752

753 754
        if (parameter.getJetValueParameter().name().length() > 0) {
            name = parameter.getJetValueParameter().name();
755 756
        }
        
757 758 759 760
        String typeFromAnnotation = parameter.getJetValueParameter().type();
        boolean receiver = parameter.getJetValueParameter().receiver();
        boolean hasDefaultValue = parameter.getJetValueParameter().hasDefaultValue();

S
Stepan Koltsov 已提交
761
        JetType outType;
762
        if (typeFromAnnotation.length() > 0) {
763
            outType = semanticServices.getTypeTransformer().transformToType(typeFromAnnotation, typeVariableResolver);
S
Stepan Koltsov 已提交
764 765 766
        } else {
            outType = semanticServices.getTypeTransformer().transformToType(psiType);
        }
767 768 769 770 771 772 773 774
        if (receiver) {
            return JvmMethodParameterMeaning.receiver(outType);
        } else {
            return JvmMethodParameterMeaning.regular(new ValueParameterDescriptorImpl(
                    containingDeclaration,
                    i,
                    Collections.<AnnotationDescriptor>emptyList(), // TODO
                    name,
S
Stepan Koltsov 已提交
775
                    false,
776
                    nullable ? TypeUtils.makeNullableAsSpecified(outType, nullable) : outType,
777
                    hasDefaultValue,
778 779 780
                    varargElementType
            ));
        }
781 782
    }

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

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

        @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;
829 830 831
            //if (receiverType != null ? !receiverType.equals(that.receiverType) : that.receiverType != null)
            //    return false;
            //if (!type.equals(that.type)) return false;
832 833 834 835 836 837 838

            return true;
        }

        @Override
        public int hashCode() {
            int result = name.hashCode();
839 840
            //result = 31 * result + type.hashCode();
            //result = 31 * result + (receiverType != null ? receiverType.hashCode() : 0);
841 842 843 844 845
            return result;
        }
    }

    private static class MembersForProperty {
846 847 848 849 850 851
        private PsiFieldWrapper field;
        private PsiMethodWrapper setter;
        private PsiMethodWrapper getter;

        private PsiType type;
        private PsiType receiverType;
852 853 854 855 856 857 858 859 860 861 862 863 864 865 866
    }
    
    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();
867 868 869
                members.field = new PsiFieldWrapper(field);
                members.type = field.getType();
                membersMap.put(new PropertyKey(field.getName() /*, field.getType(), null*/), members);
870 871 872
            }
        }
        
873 874 875 876
        for (PsiMethod psiMethod : clazz.getMethods()) {
            PsiMethodWrapper method = new PsiMethodWrapper(psiMethod);

            if (method.isStatic() != staticMembers) {
877 878 879
                continue;
            }

880
            if (method.isPrivate()) {
881 882 883 884
                continue;
            }

            // TODO: "is" prefix
885
            // TODO: remove getJavaClass
886 887
            if (psiMethod.getName().startsWith(JvmAbi.GETTER_PREFIX)) {

888
                // TODO: some java properties too
889
                if (method.getJetProperty().isDefined()) {
890 891 892 893 894 895 896

                    if (psiMethod.getName().equals(JvmStdlibNames.JET_OBJECT_GET_TYPEINFO_METHOD)) {
                        continue;
                    }

                    int i = 0;

897
                    PsiType receiverType;
898 899 900
                    if (i < method.getParameters().size() && method.getParameter(i).getJetValueParameter().receiver()) {
                        receiverType = method.getParameter(i).getPsiParameter().getType();
                        ++i;
901
                    } else {
902
                        receiverType = null;
903
                    }
904
                    
905 906 907
                    while (i < method.getParameters().size() && method.getParameter(i).getJetTypeParameter().isDefined()) {
                        // TODO: store is reified
                        ++i;
908
                    }
909 910 911 912 913 914
                    
                    if (i != method.getParameters().size()) {
                        // TODO: report error properly
                        throw new IllegalStateException();
                    }
                    
915
                    String propertyName = StringUtil.decapitalize(psiMethod.getName().substring(JvmAbi.GETTER_PREFIX.length()));
916
                    PropertyKey key = new PropertyKey(propertyName /*, psiMethod.getReturnType(), receiverType*/);
917 918 919 920 921
                    MembersForProperty members = membersMap.get(key);
                    if (members == null) {
                        members = new MembersForProperty();
                        membersMap.put(key, members);
                    }
922 923 924 925 926
                    members.getter = new PsiMethodWrapper(psiMethod);

                    // TODO: check conflicts with setter
                    members.type = psiMethod.getReturnType();
                    members.receiverType = receiverType;
927
                }
928 929 930 931
            } else if (psiMethod.getName().startsWith(JvmAbi.SETTER_PREFIX)) {

                if (method.getJetProperty().isDefined()) {
                    if (psiMethod.getParameterList().getParametersCount() == 0) {
932
                        // TODO: report error properly
933 934 935 936 937 938
                        throw new IllegalStateException();
                    }

                    int i = 0;

                    PsiType receiverType = null;
939 940 941 942
                    PsiParameterWrapper p1 = method.getParameter(0);
                    if (p1.getJetValueParameter().receiver()) {
                        receiverType = p1.getPsiParameter().getType();
                        ++i;
943
                    }
944
                    
945
                    while (i < method.getParameters().size() && method.getParameter(i).getJetTypeParameter().isDefined()) {
946 947 948
                        ++i;
                    }
                    
949
                    if (i + 1 != psiMethod.getParameterList().getParametersCount()) {
950 951 952
                        throw new IllegalStateException();
                    }
                    
953
                    PsiType propertyType = psiMethod.getParameterList().getParameters()[i].getType();
954

955
                    String propertyName = StringUtil.decapitalize(psiMethod.getName().substring(JvmAbi.SETTER_PREFIX.length()));
956
                    PropertyKey key = new PropertyKey(propertyName /*, propertyType, receiverType*/);
957 958 959 960 961
                    MembersForProperty members = membersMap.get(key);
                    if (members == null) {
                        members = new MembersForProperty();
                        membersMap.put(key, members);
                    }
962 963 964 965 966
                    members.setter = new PsiMethodWrapper(psiMethod);

                    // TODO: check conflicts with getter
                    members.type = propertyType;
                    members.receiverType = receiverType;
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 995 996 997 998 999 1000 1001 1002 1003 1004 1005
                }
            }
        }
        
        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();
1006 1007
        Map<PropertyKey, MembersForProperty> membersForProperties = getMembersForProperties(psiClass, staticMembers, scopeData.kotlin);
        for (Map.Entry<PropertyKey, MembersForProperty> entry : membersForProperties.entrySet()) {
1008 1009 1010 1011 1012
            //VariableDescriptor variableDescriptor = fieldDescriptorCache.get(field);
            //if (variableDescriptor != null) {
            //    return variableDescriptor;
            //}
            String propertyName = entry.getKey().name;
1013 1014
            PsiType propertyType = entry.getValue().type;
            PsiType receiverType = entry.getValue().receiverType;
1015 1016 1017 1018
            MembersForProperty members = entry.getValue();

            boolean isFinal;
            if (members.setter == null && members.getter == null) {
1019
                isFinal = false;
1020
            } else if (members.getter != null) {
1021
                isFinal = members.getter.isFinal();
1022
            } else if (members.setter != null) {
1023
                isFinal = members.setter.isFinal();
1024 1025 1026
            } else {
                isFinal = false;
            }
1027

1028
            PsiMemberWrapper anyMember;
1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049
            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
1050
                    resolveVisibilityFromPsiModifiers(anyMember.psiMember),
1051 1052
                    isVar,
                    false,
1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 1088 1089 1090 1091
                    propertyName);
            
            PropertyGetterDescriptor getterDescriptor = null;
            PropertySetterDescriptor setterDescriptor = null;
            if (members.getter != null) {
                getterDescriptor = new PropertyGetterDescriptor(propertyDescriptor, Collections.<AnnotationDescriptor>emptyList(), Modality.OPEN, Visibility.PUBLIC, true, false);
            }
            if (members.setter != null) {
                setterDescriptor = new PropertySetterDescriptor(propertyDescriptor, Collections.<AnnotationDescriptor>emptyList(), Modality.OPEN, Visibility.PUBLIC, true, false);
            }
            
            propertyDescriptor.initialize(getterDescriptor, setterDescriptor);

            final List<TypeParameterDescriptor> classTypeParameters;
            if (anyMember instanceof PsiMethodWrapper && !anyMember.isStatic()) {
                classTypeParameters = ((ClassDescriptor) owner).getTypeConstructor().getParameters();
            } else {
                classTypeParameters = new ArrayList<TypeParameterDescriptor>(0);
            }
            TypeParameterListTypeVariableResolver typeVariableResolver = new TypeParameterListTypeVariableResolver(classTypeParameters);

            List<TypeParameterDescriptor> typeParameters = new ArrayList<TypeParameterDescriptor>(0);

            if (members.setter != null) {
                // call ugly code with side effects
                typeParameters = resolveMethodTypeParameters(members.setter, propertyDescriptor.getSetter(), typeVariableResolver);
            }
            if (members.getter != null) {
                // call ugly code with side effects
                typeParameters = resolveMethodTypeParameters(members.getter, propertyDescriptor.getGetter(), typeVariableResolver);
            }

            JetType receiverJetType;
            if (receiverType == null) {
                receiverJetType = null;
            } else {
                receiverJetType = semanticServices.getTypeTransformer().transformToType(receiverType);
            }

1092 1093
            JetType type = semanticServices.getTypeTransformer().transformToType(propertyType);

1094 1095 1096
            propertyDescriptor.setType(
                    type,
                    typeParameters,
1097
                    DescriptorUtils.getExpectedThisObjectIfNeeded(owner),
1098 1099 1100 1101 1102 1103 1104 1105 1106 1107
                    receiverJetType
                );
            if (getterDescriptor != null) {
                getterDescriptor.initialize(type);
            }
            if (setterDescriptor != null) {
                // TODO: initialize
            }
            
            semanticServices.getTrace().record(BindingContext.VARIABLE, anyMember.psiMember, propertyDescriptor);
1108 1109 1110 1111 1112 1113
            //fieldDescriptorCache.put(field, propertyDescriptor);
            descriptors.add(propertyDescriptor);
        }
        scopeData.properties = descriptors;
        return descriptors;
    }
A
Andrey Breslav 已提交
1114

A
Andrey Breslav 已提交
1115
    @NotNull
A
Andrey Breslav 已提交
1116 1117
    public Set<FunctionDescriptor> resolveFunctionGroup(@NotNull DeclarationDescriptor owner, @NotNull PsiClass psiClass, @Nullable ClassDescriptor classDescriptor, @NotNull String methodName, boolean staticMembers) {
        Set<FunctionDescriptor> writableFunctionGroup = Sets.newLinkedHashSet();
1118
        final Collection<HierarchicalMethodSignature> signatures = psiClass.getVisibleSignatures();
A
Andrey Breslav 已提交
1119
        TypeSubstitutor typeSubstitutor = createSubstitutorForGenericSupertypes(classDescriptor);
1120
        for (HierarchicalMethodSignature signature: signatures) {
1121
            if (!methodName.equals(signature.getName())) {
A
Andrey Breslav 已提交
1122 1123 1124
                 continue;
            }

1125
            FunctionDescriptor substitutedFunctionDescriptor = resolveHierarchicalSignatureToFunction(owner, psiClass, staticMembers, typeSubstitutor, signature);
1126
            if (substitutedFunctionDescriptor != null) {
A
Andrey Breslav 已提交
1127
                writableFunctionGroup.add(substitutedFunctionDescriptor);
1128
            }
A
Andrey Breslav 已提交
1129 1130 1131
        }
        return writableFunctionGroup;
    }
A
Andrey Breslav 已提交
1132

1133 1134 1135 1136 1137 1138 1139 1140 1141 1142 1143 1144 1145 1146 1147
    @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 已提交
1148 1149 1150 1151 1152 1153 1154 1155 1156 1157 1158
    public TypeSubstitutor createSubstitutorForGenericSupertypes(ClassDescriptor classDescriptor) {
        TypeSubstitutor typeSubstitutor;
        if (classDescriptor != null) {
            typeSubstitutor = TypeUtils.buildDeepSubstitutor(classDescriptor.getDefaultType());
        }
        else {
            typeSubstitutor = TypeSubstitutor.EMPTY;
        }
        return typeSubstitutor;
    }

1159 1160 1161 1162 1163 1164 1165 1166 1167 1168 1169 1170 1171 1172 1173 1174 1175 1176 1177 1178
    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 已提交
1179
    @Nullable
1180 1181 1182 1183
    public FunctionDescriptor resolveMethodToFunctionDescriptor(DeclarationDescriptor owner, PsiClass psiClass, TypeSubstitutor typeSubstitutorForGenericSuperclasses, PsiMethod psiMethod) {
        PsiMethodWrapper method = new PsiMethodWrapper(psiMethod);
        
        PsiType returnType = psiMethod.getReturnType();
A
Andrey Breslav 已提交
1184 1185 1186
        if (returnType == null) {
            return null;
        }
1187
        FunctionDescriptor functionDescriptor = methodDescriptorCache.get(psiMethod);
A
Andrey Breslav 已提交
1188
        if (functionDescriptor != null) {
1189
            if (psiMethod.getContainingClass() != psiClass) {
A
Andrey Breslav 已提交
1190 1191 1192 1193
                functionDescriptor = functionDescriptor.substitute(typeSubstitutorForGenericSuperclasses);
            }
            return functionDescriptor;
        }
1194 1195 1196 1197 1198 1199 1200 1201 1202 1203 1204 1205 1206 1207 1208 1209 1210

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

1211
        // TODO: ugly
1212
        if (method.getJetProperty().isDefined()) {
1213
            return null;
1214
        }
1215

1216 1217
        DeclarationDescriptor classDescriptor;
        final List<TypeParameterDescriptor> classTypeParameters;
1218 1219
        if (method.isStatic()) {
            classDescriptor = resolveNamespace(psiMethod.getContainingClass());
1220 1221 1222
            classTypeParameters = Collections.emptyList();
        }
        else {
1223
            ClassDescriptor classClassDescriptor = resolveClass(psiMethod.getContainingClass());
1224 1225 1226
            classDescriptor = classClassDescriptor;
            classTypeParameters = classClassDescriptor.getTypeConstructor().getParameters();
        }
1227 1228 1229
        if (classDescriptor == null) {
            return null;
        }
S
Stepan Koltsov 已提交
1230
        NamedFunctionDescriptorImpl functionDescriptorImpl = new NamedFunctionDescriptorImpl(
A
Andrey Breslav 已提交
1231 1232
                owner,
                Collections.<AnnotationDescriptor>emptyList(), // TODO
1233
                psiMethod.getName()
A
Andrey Breslav 已提交
1234
        );
1235
        methodDescriptorCache.put(psiMethod, functionDescriptorImpl);
1236 1237 1238 1239

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

1240
        final List<TypeParameterDescriptor> methodTypeParameters = resolveMethodTypeParameters(new PsiMethodWrapper(psiMethod), functionDescriptorImpl, typeVariableResolverForParameters);
1241 1242 1243 1244 1245 1246 1247 1248 1249 1250 1251 1252 1253 1254 1255 1256 1257 1258 1259 1260 1261

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


1262
        ValueParameterDescriptors valueParameterDescriptors = resolveParameterDescriptors(functionDescriptorImpl, method.getParameters(), new MethodTypeVariableResolver());
A
Andrey Breslav 已提交
1263
        functionDescriptorImpl.initialize(
1264
                valueParameterDescriptors.receiverType,
A
Andrey Breslav 已提交
1265
                DescriptorUtils.getExpectedThisObjectIfNeeded(classDescriptor),
1266
                methodTypeParameters,
1267
                valueParameterDescriptors.descriptors,
1268
                makeReturnType(returnType, method, new MethodTypeVariableResolver()),
1269 1270
                Modality.convertFromFlags(psiMethod.hasModifierProperty(PsiModifier.ABSTRACT), !psiMethod.hasModifierProperty(PsiModifier.FINAL)),
                resolveVisibilityFromPsiModifiers(psiMethod)
A
Andrey Breslav 已提交
1271
        );
1272
        semanticServices.getTrace().record(BindingContext.FUNCTION, psiMethod, functionDescriptorImpl);
A
Andrey Breslav 已提交
1273
        FunctionDescriptor substitutedFunctionDescriptor = functionDescriptorImpl;
1274
        if (psiMethod.getContainingClass() != psiClass) {
A
Andrey Breslav 已提交
1275 1276 1277 1278
            substitutedFunctionDescriptor = functionDescriptorImpl.substitute(typeSubstitutorForGenericSuperclasses);
        }
        return substitutedFunctionDescriptor;
    }
1279

1280 1281 1282 1283 1284
    private List<TypeParameterDescriptor> resolveMethodTypeParameters(
            @NotNull PsiMethodWrapper method,
            @NotNull FunctionDescriptor functionDescriptor,
            @NotNull TypeVariableResolver classTypeVariableResolver) {
        if (method.getJetMethodOrProperty().typeParameters().length() > 0) {
1285
            List<TypeParameterDescriptor> r = resolveMethodTypeParametersFromJetSignature(
1286 1287
                    method.getJetMethodOrProperty().typeParameters(), method.getPsiMethod(), functionDescriptor, classTypeVariableResolver);
            initializeTypeParameters(method.getPsiMethod());
1288
            return r;
1289
        }
1290

1291 1292
        List<TypeParameterDescriptor> typeParameters = makeUninitializedTypeParameters(functionDescriptor, method.getPsiMethod().getTypeParameters());
        initializeTypeParameters(method.getPsiMethod());
1293 1294
        return typeParameters;
    }
1295 1296

    /**
1297
     * @see #resolveClassTypeParametersFromJetSignature(String, com.intellij.psi.PsiClass, JavaClassDescriptor) 
1298
     */
1299 1300 1301
    private List<TypeParameterDescriptor> resolveMethodTypeParametersFromJetSignature(String jetSignature, final PsiMethod method,
            final FunctionDescriptor functionDescriptor, final TypeVariableResolver classTypeVariableResolver)
    {
1302
        final List<TypeParameterDescriptor> r = new ArrayList<TypeParameterDescriptor>();
1303 1304 1305 1306 1307 1308 1309 1310 1311 1312 1313 1314 1315 1316 1317
        
        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);
            }
        }
        
1318
        new JetSignatureReader(jetSignature).acceptFormalTypeParametersOnly(new JetSignatureExceptionsAdapter() {
1319 1320
            private int formalTypeParameterIndex = 0;
            
1321
            @Override
S
Stepan Koltsov 已提交
1322
            public JetSignatureVisitor visitFormalTypeParameter(final String name, final TypeInfoVariance variance) {
1323
                
1324
                return new JetSignatureTypeParameterVisitor(functionDescriptor, method, name, formalTypeParameterIndex++, variance, new MyTypeVariableResolver()) {
1325
                    @Override
1326 1327
                    protected void done(TypeParameterDescriptor typeParameterDescriptor) {
                        r.add(typeParameterDescriptor);
1328 1329
                    }
                };
1330

1331 1332 1333 1334 1335
            }
        });
        return r;
    }

1336 1337 1338 1339
    private JetType makeReturnType(PsiType returnType, PsiMethodWrapper method, TypeVariableResolver typeVariableResolver) {

        String returnTypeFromAnnotation = method.getJetMethod().returnType();

S
Stepan Koltsov 已提交
1340
        JetType transformedType;
1341
        if (returnTypeFromAnnotation.length() > 0) {
1342
            transformedType = semanticServices.getTypeTransformer().transformToType(returnTypeFromAnnotation, typeVariableResolver);
S
Stepan Koltsov 已提交
1343 1344 1345
        } else {
            transformedType = semanticServices.getTypeTransformer().transformToType(returnType);
        }
1346 1347
        if (method.getJetMethod().returnTypeNullable()) {
            return TypeUtils.makeNullableAsSpecified(transformedType, true);
1348 1349 1350 1351 1352
        } else {
            return transformedType;
        }
    }

1353
    private static Visibility resolveVisibilityFromPsiModifiers(PsiModifierListOwner modifierListOwner) {
1354 1355 1356 1357 1358 1359
        //TODO report error
        return modifierListOwner.hasModifierProperty(PsiModifier.PUBLIC) ? Visibility.PUBLIC :
                                        (modifierListOwner.hasModifierProperty(PsiModifier.PRIVATE) ? Visibility.PRIVATE :
                                        (modifierListOwner.hasModifierProperty(PsiModifier.PROTECTED) ? Visibility.PROTECTED : Visibility.INTERNAL));
    }

1360 1361
    @NotNull
    private TypeParameterDescriptorInitialization resolveTypeParameterInitialization(PsiTypeParameter typeParameter) {
1362 1363 1364 1365 1366 1367 1368 1369 1370 1371 1372 1373 1374 1375 1376 1377 1378 1379 1380 1381 1382 1383 1384 1385
        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);
    }
1386 1387 1388 1389

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