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

3
import com.google.common.collect.Lists;
A
Andrey Breslav 已提交
4
import com.google.common.collect.Maps;
A
Andrey Breslav 已提交
5
import com.google.common.collect.Sets;
6
import com.intellij.openapi.project.Project;
7
import com.intellij.openapi.util.text.StringUtil;
8
import com.intellij.openapi.vfs.VirtualFile;
9 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 589 590 591 592 593
        // First, let's check that there is no Kotlin package:
        NamespaceDescriptor kotlinNamespaceDescriptor = semanticServices.getKotlinNamespaceDescriptor(qualifiedName);
        if (kotlinNamespaceDescriptor != null) {
            return kotlinNamespaceDescriptor;
        }

594
        PsiPackage psiPackage = findPackage(qualifiedName);
595
        if (psiPackage == null) {
596
            PsiClass psiClass = findClass(qualifiedName);
A
Andrey Breslav 已提交
597 598
            if (psiClass == null) return null;
            return resolveNamespace(psiClass);
599 600 601 602
        }
        return resolveNamespace(psiPackage);
    }

603 604 605 606
    private PsiClass findClass(String qualifiedName) {
        return javaFacade.findClass(qualifiedName, javaSearchScope);
    }

607
    /*package*/ PsiPackage findPackage(String qualifiedName) {
608 609 610
        return javaFacade.findPackage(qualifiedName);
    }

611
    private NamespaceDescriptor resolveNamespace(@NotNull PsiPackage psiPackage) {
612 613 614 615 616
        ResolverNamespaceData namespaceData = namespaceDescriptorCache.get(psiPackage);
        if (namespaceData == null) {
            namespaceData = createJavaNamespaceDescriptor(psiPackage);
            namespaceDescriptorCache.put(psiPackage, namespaceData);
            namespaceDescriptorCacheByFqn.put(psiPackage.getQualifiedName(), namespaceData);
617
        }
618
        return namespaceData.namespaceDescriptor;
619 620
    }

A
Andrey Breslav 已提交
621
    private NamespaceDescriptor resolveNamespace(@NotNull PsiClass psiClass) {
622 623 624 625 626
        ResolverNamespaceData namespaceData = namespaceDescriptorCache.get(psiClass);
        if (namespaceData == null) {
            namespaceData = createJavaNamespaceDescriptor(psiClass);
            namespaceDescriptorCache.put(psiClass, namespaceData);
            namespaceDescriptorCacheByFqn.put(psiClass.getQualifiedName(), namespaceData);
A
Andrey Breslav 已提交
627
        }
628
        return namespaceData.namespaceDescriptor;
A
Andrey Breslav 已提交
629 630
    }

631 632
    private ResolverNamespaceData createJavaNamespaceDescriptor(@NotNull PsiPackage psiPackage) {
        ResolverNamespaceData namespaceData = new ResolverNamespaceData();
633
        String name = psiPackage.getName();
634
        namespaceData.namespaceDescriptor = new JavaNamespaceDescriptor(
635
                resolveParentDescriptor(psiPackage),
A
Andrey Breslav 已提交
636
                Collections.<AnnotationDescriptor>emptyList(), // TODO
637 638
                name == null ? JAVA_ROOT : name,
                name == null ? JAVA_ROOT : psiPackage.getQualifiedName()
639
        );
640

641 642 643 644 645
        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;
646 647
    }

648 649 650 651 652 653 654 655
    private DeclarationDescriptor resolveParentDescriptor(@NotNull PsiPackage psiPackage) {
        PsiPackage parentPackage = psiPackage.getParentPackage();
        if (parentPackage == null) {
            return null;
        }
        return resolveNamespace(parentPackage);
    }

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

679 680
    private ValueParameterDescriptors resolveParameterDescriptors(DeclarationDescriptor containingDeclaration,
            List<PsiParameterWrapper> parameters, TypeVariableResolver typeVariableResolver) {
681
        List<ValueParameterDescriptor> result = new ArrayList<ValueParameterDescriptor>();
682
        JetType receiverType = null;
683
        int indexDelta = 0;
684 685
        for (int i = 0, parametersLength = parameters.size(); i < parametersLength; i++) {
            PsiParameterWrapper parameter = parameters.get(i);
686
            JvmMethodParameterMeaning meaning = resolveParameterDescriptor(containingDeclaration, i + indexDelta, parameter, typeVariableResolver);
687 688
            if (meaning.kind == JvmMethodParameterKind.TYPE_INFO) {
                // TODO
689
                --indexDelta;
690 691 692 693 694 695
            } 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");
                }
696
                --indexDelta;
697
                receiverType = meaning.receiverType;
S
Stepan Koltsov 已提交
698
            }
699
        }
700
        return new ValueParameterDescriptors(receiverType, result);
701
    }
A
Andrey Breslav 已提交
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 730 731 732 733 734 735
    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
736
    private JvmMethodParameterMeaning resolveParameterDescriptor(DeclarationDescriptor containingDeclaration, int i,
737 738 739 740 741 742 743
            PsiParameterWrapper parameter, TypeVariableResolver typeVariableResolver) {

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

        PsiType psiType = parameter.getPsiParameter().getType();
744 745 746 747 748 749 750 751 752

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

754
        boolean nullable = parameter.getJetValueParameter().nullable();
755

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

759 760
        if (parameter.getJetValueParameter().name().length() > 0) {
            name = parameter.getJetValueParameter().name();
761 762
        }
        
763 764 765 766
        String typeFromAnnotation = parameter.getJetValueParameter().type();
        boolean receiver = parameter.getJetValueParameter().receiver();
        boolean hasDefaultValue = parameter.getJetValueParameter().hasDefaultValue();

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

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

821
        private PropertyKey(@NotNull String name /*, @NotNull PsiType type, @Nullable PsiType receiverType */) {
822
            this.name = name;
823 824
            //this.type = type;
            //this.receiverType = receiverType;
825 826 827 828 829 830 831 832 833 834
        }

        @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;
835 836 837
            //if (receiverType != null ? !receiverType.equals(that.receiverType) : that.receiverType != null)
            //    return false;
            //if (!type.equals(that.type)) return false;
838 839 840 841 842 843 844

            return true;
        }

        @Override
        public int hashCode() {
            int result = name.hashCode();
845 846
            //result = 31 * result + type.hashCode();
            //result = 31 * result + (receiverType != null ? receiverType.hashCode() : 0);
847 848 849 850 851
            return result;
        }
    }

    private static class MembersForProperty {
852 853 854 855 856 857
        private PsiFieldWrapper field;
        private PsiMethodWrapper setter;
        private PsiMethodWrapper getter;

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

            if (method.isStatic() != staticMembers) {
883 884 885
                continue;
            }

886
            if (method.isPrivate()) {
887 888 889 890
                continue;
            }

            // TODO: "is" prefix
891
            // TODO: remove getJavaClass
892 893
            if (psiMethod.getName().startsWith(JvmAbi.GETTER_PREFIX)) {

894
                // TODO: some java properties too
895
                if (method.getJetProperty().isDefined()) {
896 897 898 899 900 901 902

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

                    int i = 0;

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

                    // TODO: check conflicts with setter
                    members.type = psiMethod.getReturnType();
                    members.receiverType = receiverType;
933
                }
934 935 936 937
            } else if (psiMethod.getName().startsWith(JvmAbi.SETTER_PREFIX)) {

                if (method.getJetProperty().isDefined()) {
                    if (psiMethod.getParameterList().getParametersCount() == 0) {
938
                        // TODO: report error properly
939 940 941 942 943 944
                        throw new IllegalStateException();
                    }

                    int i = 0;

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

961
                    String propertyName = StringUtil.decapitalize(psiMethod.getName().substring(JvmAbi.SETTER_PREFIX.length()));
962
                    PropertyKey key = new PropertyKey(propertyName /*, propertyType, receiverType*/);
963 964 965 966 967
                    MembersForProperty members = membersMap.get(key);
                    if (members == null) {
                        members = new MembersForProperty();
                        membersMap.put(key, members);
                    }
968 969 970 971 972
                    members.setter = new PsiMethodWrapper(psiMethod);

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

            boolean isFinal;
            if (members.setter == null && members.getter == null) {
1025
                isFinal = false;
1026
            } else if (members.getter != null) {
1027
                isFinal = members.getter.isFinal();
1028
            } else if (members.setter != null) {
1029
                isFinal = members.setter.isFinal();
1030 1031 1032
            } else {
                isFinal = false;
            }
1033

1034
            PsiMemberWrapper anyMember;
1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055
            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
1056
                    resolveVisibilityFromPsiModifiers(anyMember.psiMember),
1057 1058
                    isVar,
                    false,
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 1092 1093 1094 1095 1096 1097
                    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);
            }

1098 1099
            JetType type = semanticServices.getTypeTransformer().transformToType(propertyType);

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

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

1131
            FunctionDescriptor substitutedFunctionDescriptor = resolveHierarchicalSignatureToFunction(owner, psiClass, staticMembers, typeSubstitutor, signature);
1132
            if (substitutedFunctionDescriptor != null) {
A
Andrey Breslav 已提交
1133
                writableFunctionGroup.add(substitutedFunctionDescriptor);
1134
            }
A
Andrey Breslav 已提交
1135 1136 1137
        }
        return writableFunctionGroup;
    }
A
Andrey Breslav 已提交
1138

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

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

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

1217
        // TODO: ugly
1218
        if (method.getJetProperty().isDefined()) {
1219
            return null;
1220
        }
1221

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

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

1246
        final List<TypeParameterDescriptor> methodTypeParameters = resolveMethodTypeParameters(new PsiMethodWrapper(psiMethod), functionDescriptorImpl, typeVariableResolverForParameters);
1247 1248 1249 1250 1251 1252 1253 1254 1255 1256 1257 1258 1259 1260 1261 1262 1263 1264 1265 1266 1267

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


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

1286 1287 1288 1289 1290
    private List<TypeParameterDescriptor> resolveMethodTypeParameters(
            @NotNull PsiMethodWrapper method,
            @NotNull FunctionDescriptor functionDescriptor,
            @NotNull TypeVariableResolver classTypeVariableResolver) {
        if (method.getJetMethodOrProperty().typeParameters().length() > 0) {
1291
            List<TypeParameterDescriptor> r = resolveMethodTypeParametersFromJetSignature(
1292 1293
                    method.getJetMethodOrProperty().typeParameters(), method.getPsiMethod(), functionDescriptor, classTypeVariableResolver);
            initializeTypeParameters(method.getPsiMethod());
1294
            return r;
1295
        }
1296

1297 1298
        List<TypeParameterDescriptor> typeParameters = makeUninitializedTypeParameters(functionDescriptor, method.getPsiMethod().getTypeParameters());
        initializeTypeParameters(method.getPsiMethod());
1299 1300
        return typeParameters;
    }
1301 1302

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

1337 1338 1339 1340 1341
            }
        });
        return r;
    }

1342 1343 1344 1345
    private JetType makeReturnType(PsiType returnType, PsiMethodWrapper method, TypeVariableResolver typeVariableResolver) {

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

S
Stepan Koltsov 已提交
1346
        JetType transformedType;
1347
        if (returnTypeFromAnnotation.length() > 0) {
1348
            transformedType = semanticServices.getTypeTransformer().transformToType(returnTypeFromAnnotation, typeVariableResolver);
S
Stepan Koltsov 已提交
1349 1350 1351
        } else {
            transformedType = semanticServices.getTypeTransformer().transformToType(returnType);
        }
1352 1353
        if (method.getJetMethod().returnTypeNullable()) {
            return TypeUtils.makeNullableAsSpecified(transformedType, true);
1354 1355 1356 1357 1358
        } else {
            return transformedType;
        }
    }

1359
    private static Visibility resolveVisibilityFromPsiModifiers(PsiModifierListOwner modifierListOwner) {
1360 1361 1362 1363 1364 1365
        //TODO report error
        return modifierListOwner.hasModifierProperty(PsiModifier.PUBLIC) ? Visibility.PUBLIC :
                                        (modifierListOwner.hasModifierProperty(PsiModifier.PRIVATE) ? Visibility.PRIVATE :
                                        (modifierListOwner.hasModifierProperty(PsiModifier.PROTECTED) ? Visibility.PROTECTED : Visibility.INTERNAL));
    }

1366 1367
    @NotNull
    private TypeParameterDescriptorInitialization resolveTypeParameterInitialization(PsiTypeParameter typeParameter) {
1368 1369 1370 1371 1372 1373 1374 1375 1376 1377 1378 1379 1380 1381 1382 1383 1384 1385 1386 1387 1388 1389 1390 1391
        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);
    }
1392 1393 1394 1395

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