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

3
import com.google.common.collect.Lists;
A
Andrey Breslav 已提交
4
import com.google.common.collect.Maps;
A
Andrey Breslav 已提交
5
import com.google.common.collect.Sets;
6
import com.intellij.openapi.project.Project;
7
import com.intellij.openapi.vfs.VirtualFile;
8
import com.intellij.psi.*;
9
import com.intellij.psi.search.DelegatingGlobalSearchScope;
10
import com.intellij.psi.search.GlobalSearchScope;
11
import jet.typeinfo.TypeInfoVariance;
12 13
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
A
Andrey Breslav 已提交
14
import org.jetbrains.jet.lang.descriptors.*;
A
Andrey Breslav 已提交
15
import org.jetbrains.jet.lang.descriptors.annotations.AnnotationDescriptor;
16
import org.jetbrains.jet.lang.resolve.BindingContext;
17
import org.jetbrains.jet.lang.resolve.DescriptorUtils;
18
import org.jetbrains.jet.lang.types.*;
19
import org.jetbrains.jet.plugin.JetFileType;
20
import org.jetbrains.jet.rt.signature.JetSignatureAdapter;
21 22 23
import org.jetbrains.jet.rt.signature.JetSignatureExceptionsAdapter;
import org.jetbrains.jet.rt.signature.JetSignatureReader;
import org.jetbrains.jet.rt.signature.JetSignatureVisitor;
24 25 26 27 28 29 30

import java.util.*;

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

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

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

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

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

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

73 74
        private TypeParameterDescriptorInitialization(TypeParameterDescriptor descriptor) {
            this.origin = TypeParameterDescriptorOrigin.JAVA;
75
            this.descriptor = descriptor;
76 77 78 79 80 81 82 83 84 85
            this.upperBoundsForKotlin = null;
            this.lowerBoundsForKotlin = null;
        }

        private TypeParameterDescriptorInitialization(TypeParameterDescriptor descriptor,
                List<JetType> upperBoundsForKotlin, List<JetType> lowerBoundsForKotlin) {
            this.origin = TypeParameterDescriptorOrigin.KOTLIN;
            this.descriptor = descriptor;
            this.upperBoundsForKotlin = upperBoundsForKotlin;
            this.lowerBoundsForKotlin = lowerBoundsForKotlin;
86 87
        }
    }
A
Andrey Breslav 已提交
88

89
    protected final Map<String, ClassDescriptor> classDescriptorCache = Maps.newHashMap();
90
    protected final Map<PsiTypeParameter, TypeParameterDescriptorInitialization> typeParameterDescriptorCache = Maps.newHashMap();
A
Andrey Breslav 已提交
91
    protected final Map<PsiMethod, FunctionDescriptor> methodDescriptorCache = Maps.newHashMap();
A
Andrey Breslav 已提交
92
    protected final Map<PsiField, VariableDescriptor> fieldDescriptorCache = Maps.newHashMap();
A
Andrey Breslav 已提交
93
    protected final Map<PsiElement, NamespaceDescriptor> namespaceDescriptorCache = Maps.newHashMap();
94 95 96 97 98 99
    protected final JavaPsiFacade javaFacade;
    protected final GlobalSearchScope javaSearchScope;
    protected final JavaSemanticServices semanticServices;

    public JavaDescriptorResolver(Project project, JavaSemanticServices semanticServices) {
        this.javaFacade = JavaPsiFacade.getInstance(project);
100 101 102 103 104 105
        this.javaSearchScope = new DelegatingGlobalSearchScope(GlobalSearchScope.allScope(project)) {
            @Override
            public boolean contains(VirtualFile file) {
                return myBaseScope.contains(file) && file.getFileType() != JetFileType.INSTANCE;
            }
        };
106 107 108 109 110 111
        this.semanticServices = semanticServices;
    }

    @NotNull
    public ClassDescriptor resolveClass(@NotNull PsiClass psiClass) {
        String qualifiedName = psiClass.getQualifiedName();
112

113
        // First, let's check that this is a real Java class, not a Java's view on a Kotlin class:
114 115 116 117 118
        ClassDescriptor kotlinClassDescriptor = semanticServices.getKotlinClassDescriptor(qualifiedName);
        if (kotlinClassDescriptor != null) {
            return kotlinClassDescriptor;
        }

119
        // Not let's take a descriptor of a Java class
120 121 122 123 124 125 126 127 128 129
        ClassDescriptor classDescriptor = classDescriptorCache.get(qualifiedName);
        if (classDescriptor == null) {
            classDescriptor = createJavaClassDescriptor(psiClass);
            classDescriptorCache.put(qualifiedName, classDescriptor);
        }
        return classDescriptor;
    }

    @Nullable
    public ClassDescriptor resolveClass(@NotNull String qualifiedName) {
130
        // First, let's check that this is a real Java class, not a Java's view on a Kotlin class:
131 132 133 134 135
        ClassDescriptor kotlinClassDescriptor = semanticServices.getKotlinClassDescriptor(qualifiedName);
        if (kotlinClassDescriptor != null) {
            return kotlinClassDescriptor;
        }

136
        // Not let's take a descriptor of a Java class
137 138
        ClassDescriptor classDescriptor = classDescriptorCache.get(qualifiedName);
        if (classDescriptor == null) {
139
            PsiClass psiClass = findClass(qualifiedName);
140 141 142 143 144 145 146 147
            if (psiClass == null) {
                return null;
            }
            classDescriptor = createJavaClassDescriptor(psiClass);
        }
        return classDescriptor;
    }

148
    private ClassDescriptor createJavaClassDescriptor(@NotNull final PsiClass psiClass) {
A
Andrey Breslav 已提交
149 150 151
        assert !classDescriptorCache.containsKey(psiClass.getQualifiedName()) : psiClass.getQualifiedName();
        classDescriptorCache.put(psiClass.getQualifiedName(), null); // TODO

152
        String name = psiClass.getName();
153
        JavaClassDescriptor classDescriptor = new JavaClassDescriptor(
154
                resolveParentDescriptor(psiClass), psiClass.isInterface() ? ClassKind.TRAIT : ClassKind.CLASS
155
        );
A
Andrey Breslav 已提交
156
        classDescriptor.setName(name);
157
        
A
Andrey Breslav 已提交
158
        List<JetType> supertypes = new ArrayList<JetType>();
159
        List<TypeParameterDescriptor> typeParameters = resolveClassTypeParameters(psiClass, classDescriptor);
A
Andrey Breslav 已提交
160 161
        classDescriptor.setTypeConstructor(new TypeConstructorImpl(
                classDescriptor,
A
Andrey Breslav 已提交
162
                Collections.<AnnotationDescriptor>emptyList(), // TODO
163
                // TODO
164
                psiClass.hasModifierProperty(PsiModifier.FINAL),
A
Andrey Breslav 已提交
165
                name,
A
Andrey Breslav 已提交
166
                typeParameters,
A
Andrey Breslav 已提交
167 168
                supertypes
        ));
169 170 171
        classDescriptor.setModality(Modality.convertFromFlags(
                psiClass.hasModifierProperty(PsiModifier.ABSTRACT) || psiClass.isInterface(),
                !psiClass.hasModifierProperty(PsiModifier.FINAL))
A
Andrey Breslav 已提交
172
        );
173
        classDescriptor.setVisibility(resolveVisibilityFromPsiModifiers(psiClass));
A
Andrey Breslav 已提交
174
        classDescriptorCache.put(psiClass.getQualifiedName(), classDescriptor);
175
        classDescriptor.setUnsubstitutedMemberScope(new JavaClassMembersScope(classDescriptor, psiClass, semanticServices, false));
176

177 178
        // UGLY HACK (Andrey Breslav is not sure what did he mean)
        initializeTypeParameters(psiClass);
179

A
Andrey Breslav 已提交
180
        supertypes.addAll(getSupertypes(psiClass));
181 182 183 184 185 186 187 188 189 190 191
        if (psiClass.isInterface()) {
            classDescriptor.setSuperclassType(JetStandardClasses.getAnyType()); // TODO : Make it java.lang.Object
        }
        else {
            PsiClassType[] extendsListTypes = psiClass.getExtendsListTypes();
            assert extendsListTypes.length == 0 || extendsListTypes.length == 1;
            JetType superclassType = extendsListTypes.length == 0
                                            ? JetStandardClasses.getAnyType()
                                            : semanticServices.getTypeTransformer().transformToType(extendsListTypes[0]);
            classDescriptor.setSuperclassType(superclassType);
        }
A
Andrey Breslav 已提交
192 193

        PsiMethod[] psiConstructors = psiClass.getConstructors();
194 195

        if (psiConstructors.length == 0) {
A
Andrey Breslav 已提交
196 197 198 199 200
            // We need to create default constructors for classes and abstract classes.
            // Example:
            // class Kotlin() : Java() {}
            // abstract public class Java {}
            if (!psiClass.isInterface()) {
201 202
                ConstructorDescriptorImpl constructorDescriptor = new ConstructorDescriptorImpl(
                        classDescriptor,
A
Andrey Breslav 已提交
203
                        Collections.<AnnotationDescriptor>emptyList(),
204
                        false);
205
                constructorDescriptor.initialize(typeParameters, Collections.<ValueParameterDescriptor>emptyList(), Modality.FINAL, classDescriptor.getVisibility());
206
                constructorDescriptor.setReturnType(classDescriptor.getDefaultType());
207
                classDescriptor.addConstructor(constructorDescriptor);
208
                semanticServices.getTrace().record(BindingContext.CONSTRUCTOR, psiClass, constructorDescriptor);
209 210 211 212 213 214
            }
        }
        else {
            for (PsiMethod constructor : psiConstructors) {
                ConstructorDescriptorImpl constructorDescriptor = new ConstructorDescriptorImpl(
                        classDescriptor,
A
Andrey Breslav 已提交
215
                        Collections.<AnnotationDescriptor>emptyList(), // TODO
216
                        false);
217 218 219 220 221
                ValueParameterDescriptors valueParameterDescriptors = resolveParameterDescriptors(constructorDescriptor, constructor.getParameterList().getParameters());
                if (valueParameterDescriptors.receiverType != null) {
                    throw new IllegalStateException();
                }
                constructorDescriptor.initialize(typeParameters, valueParameterDescriptors.descriptors, Modality.FINAL,
222
                                                 resolveVisibilityFromPsiModifiers(constructor));
223
                constructorDescriptor.setReturnType(classDescriptor.getDefaultType());
224
                classDescriptor.addConstructor(constructorDescriptor);
225
                semanticServices.getTrace().record(BindingContext.CONSTRUCTOR, constructor, constructorDescriptor);
226
            }
A
Andrey Breslav 已提交
227
        }
228

229
        semanticServices.getTrace().record(BindingContext.CLASS, psiClass, classDescriptor);
230

231 232 233
        return classDescriptor;
    }

234 235
    private List<TypeParameterDescriptor> resolveClassTypeParameters(PsiClass psiClass, JavaClassDescriptor classDescriptor) {
        for (PsiAnnotation annotation : psiClass.getModifierList().getAnnotations()) {
S
Stepan Koltsov 已提交
236 237
            if (annotation.getQualifiedName().equals(JvmStdlibNames.JET_CLASS.getFqName())) {
                PsiLiteralExpression attributeValue = (PsiLiteralExpression) annotation.findAttributeValue(JvmStdlibNames.JET_CLASS_SIGNATURE);
238 239 240
                if (attributeValue != null) {
                    String typeParametersString = (String) attributeValue.getValue();
                    if (typeParametersString != null) {
241
                        return resolveClassTypeParametersFromJetSignature(typeParametersString, psiClass, classDescriptor);
242 243 244 245 246 247 248
                    }
                }
            }
        }
        return makeUninitializedTypeParameters(classDescriptor, psiClass.getTypeParameters());
    }

249
    @NotNull
250
    private PsiTypeParameter getPsiTypeParameterByName(PsiTypeParameterListOwner clazz, String name) {
251 252 253 254 255
        for (PsiTypeParameter typeParameter : clazz.getTypeParameters()) {
            if (typeParameter.getName().equals(name)) {
                return typeParameter; 
            }
        }
256 257 258
        throw new IllegalStateException("PsiTypeParameter '" + name + "' is not found");
    }

S
Stepan Koltsov 已提交
259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275

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


276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295
    private abstract class JetSignatureTypeParameterVisitor extends JetSignatureExceptionsAdapter {
        
        private final DeclarationDescriptor containingDeclaration;
        private final PsiTypeParameterListOwner psiOwner;
        private final String name;
        private final TypeInfoVariance variance;

        protected JetSignatureTypeParameterVisitor(DeclarationDescriptor containingDeclaration, PsiTypeParameterListOwner psiOwner,
                String name, TypeInfoVariance variance)
        {
            this.containingDeclaration = containingDeclaration;
            this.psiOwner = psiOwner;
            this.name = name;
            this.variance = variance;
        }

        int index = 0;

        List<JetType> upperBounds = new ArrayList<JetType>();
        List<JetType> lowerBounds = new ArrayList<JetType>();
S
Stepan Koltsov 已提交
296
        
297 298 299 300 301
        @Override
        public JetSignatureVisitor visitClassBound() {
            return new JetTypeJetSignatureReader(JavaDescriptorResolver.this, semanticServices.getJetSemanticServices().getStandardLibrary()) {
                @Override
                protected void done(@NotNull JetType jetType) {
S
Stepan Koltsov 已提交
302 303 304
                    if (isJavaLangObject(jetType)) {
                        return;
                    }
305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334
                    upperBounds.add(jetType);
                }
            };
        }

        @Override
        public JetSignatureVisitor visitInterfaceBound() {
            return new JetTypeJetSignatureReader(JavaDescriptorResolver.this, semanticServices.getJetSemanticServices().getStandardLibrary()) {
                @Override
                protected void done(@NotNull JetType jetType) {
                    upperBounds.add(jetType);
                }
            };
        }

        @Override
        public void visitFormalTypeParameterEnd() {
            TypeParameterDescriptor typeParameter = TypeParameterDescriptor.createForFurtherModification(
                    containingDeclaration,
                    Collections.<AnnotationDescriptor>emptyList(), // TODO: wrong
                    true, // TODO: wrong
                    JetSignatureUtils.translateVariance(variance),
                    name,
                    ++index);
            PsiTypeParameter psiTypeParameter = getPsiTypeParameterByName(psiOwner, name);
            typeParameterDescriptorCache.put(psiTypeParameter, new TypeParameterDescriptorInitialization(typeParameter, upperBounds, lowerBounds));
            done(typeParameter);
        }
        
        protected abstract void done(TypeParameterDescriptor typeParameterDescriptor);
335 336
    }

337 338 339
    /**
     * @see #resolveMethodTypeParametersFromJetSignature(String, FunctionDescriptor)
     */
340
    private List<TypeParameterDescriptor> resolveClassTypeParametersFromJetSignature(String jetSignature, final PsiClass clazz, final JavaClassDescriptor classDescriptor) {
341 342 343 344
        final List<TypeParameterDescriptor> r = new ArrayList<TypeParameterDescriptor>();
        new JetSignatureReader(jetSignature).accept(new JetSignatureExceptionsAdapter() {
            @Override
            public JetSignatureVisitor visitFormalTypeParameter(final String name, final TypeInfoVariance variance) {
345
                return new JetSignatureTypeParameterVisitor(classDescriptor, clazz, name, variance) {
346
                    @Override
347 348
                    protected void done(TypeParameterDescriptor typeParameterDescriptor) {
                        r.add(typeParameterDescriptor);
349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367
                    }
                };
            }

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

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

368 369 370
    private DeclarationDescriptor resolveParentDescriptor(PsiClass psiClass) {
        PsiClass containingClass = psiClass.getContainingClass();
        if (containingClass != null) {
371
            return resolveClass(containingClass);
372 373 374 375 376 377 378
        }
        
        PsiJavaFile containingFile = (PsiJavaFile) psiClass.getContainingFile();
        String packageName = containingFile.getPackageName();
        return resolveNamespace(packageName);
    }

379
    private List<TypeParameterDescriptor> makeUninitializedTypeParameters(@NotNull DeclarationDescriptor containingDeclaration, @NotNull PsiTypeParameter[] typeParameters) {
380 381
        List<TypeParameterDescriptor> result = Lists.newArrayList();
        for (PsiTypeParameter typeParameter : typeParameters) {
382
            TypeParameterDescriptor typeParameterDescriptor = makeUninitializedTypeParameter(containingDeclaration, typeParameter);
A
Andrey Breslav 已提交
383
            result.add(typeParameterDescriptor);
384 385 386 387
        }
        return result;
    }

388 389 390
    @NotNull
    private TypeParameterDescriptor makeUninitializedTypeParameter(@NotNull DeclarationDescriptor containingDeclaration, @NotNull PsiTypeParameter psiTypeParameter) {
        assert typeParameterDescriptorCache.get(psiTypeParameter) == null : psiTypeParameter.getText();
391
        TypeParameterDescriptor typeParameterDescriptor = TypeParameterDescriptor.createForFurtherModification(
392
                containingDeclaration,
A
Andrey Breslav 已提交
393
                Collections.<AnnotationDescriptor>emptyList(), // TODO
A
Andrey Breslav 已提交
394
                false,
395
                Variance.INVARIANT,
396 397
                psiTypeParameter.getName(),
                psiTypeParameter.getIndex()
398
        );
399
        typeParameterDescriptorCache.put(psiTypeParameter, new TypeParameterDescriptorInitialization(typeParameterDescriptor));
400 401 402
        return typeParameterDescriptor;
    }

403 404 405
    private void initializeTypeParameter(PsiTypeParameter typeParameter, TypeParameterDescriptorInitialization typeParameterDescriptorInitialization) {
        TypeParameterDescriptor typeParameterDescriptor = typeParameterDescriptorInitialization.descriptor;
        if (typeParameterDescriptorInitialization.origin == TypeParameterDescriptorOrigin.KOTLIN) {
406 407 408 409 410 411 412 413 414 415
            List<?> upperBounds = typeParameterDescriptorInitialization.upperBoundsForKotlin;
            if (upperBounds.size() == 0){
                typeParameterDescriptor.addUpperBound(JetStandardClasses.getNullableAnyType());
            } else {
                for (JetType upperBound : typeParameterDescriptorInitialization.upperBoundsForKotlin) {
                    typeParameterDescriptor.addUpperBound(upperBound);
                }
            }

            // TODO: lower bounds
416 417 418 419 420 421 422 423 424 425 426 427
        } 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 已提交
428 429
            }
        }
430
        typeParameterDescriptor.setInitialized();
431 432 433 434
    }

    private void initializeTypeParameters(PsiTypeParameterListOwner typeParameterListOwner) {
        for (PsiTypeParameter psiTypeParameter : typeParameterListOwner.getTypeParameters()) {
435
            initializeTypeParameter(psiTypeParameter, resolveTypeParameterInitialization(psiTypeParameter));
436
        }
A
Andrey Breslav 已提交
437 438 439
    }

    @NotNull
440 441
    private TypeParameterDescriptorInitialization resolveTypeParameter(@NotNull DeclarationDescriptor containingDeclaration, @NotNull PsiTypeParameter psiTypeParameter) {
        TypeParameterDescriptorInitialization typeParameterDescriptor = typeParameterDescriptorCache.get(psiTypeParameter);
442
        assert typeParameterDescriptor != null : psiTypeParameter.getText();
A
Andrey Breslav 已提交
443 444 445
        return typeParameterDescriptor;
    }

A
Andrey Breslav 已提交
446 447
    private Collection<? extends JetType> getSupertypes(PsiClass psiClass) {
        List<JetType> result = new ArrayList<JetType>();
448 449 450 451 452 453
        result.add(JetStandardClasses.getAnyType());
        transformSupertypeList(result, psiClass.getExtendsListTypes());
        transformSupertypeList(result, psiClass.getImplementsListTypes());
        return result;
    }

A
Andrey Breslav 已提交
454
    private void transformSupertypeList(List<JetType> result, PsiClassType[] extendsListTypes) {
455
        for (PsiClassType type : extendsListTypes) {
A
Andrey Breslav 已提交
456
            JetType transform = semanticServices.getTypeTransformer().transformToType(type);
457 458 459 460 461

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

462
    public NamespaceDescriptor resolveNamespace(String qualifiedName) {
463
        PsiPackage psiPackage = findPackage(qualifiedName);
464
        if (psiPackage == null) {
465
            PsiClass psiClass = findClass(qualifiedName);
A
Andrey Breslav 已提交
466 467
            if (psiClass == null) return null;
            return resolveNamespace(psiClass);
468 469 470 471
        }
        return resolveNamespace(psiPackage);
    }

472 473 474 475
    private PsiClass findClass(String qualifiedName) {
        return javaFacade.findClass(qualifiedName, javaSearchScope);
    }

476
    /*package*/ PsiPackage findPackage(String qualifiedName) {
477 478 479
        return javaFacade.findPackage(qualifiedName);
    }

480 481
    private NamespaceDescriptor resolveNamespace(@NotNull PsiPackage psiPackage) {
        NamespaceDescriptor namespaceDescriptor = namespaceDescriptorCache.get(psiPackage);
482
        if (namespaceDescriptor == null) {
A
Andrey Breslav 已提交
483
            namespaceDescriptor = createJavaNamespaceDescriptor(psiPackage);
484
            namespaceDescriptorCache.put(psiPackage, namespaceDescriptor);
485 486 487 488
        }
        return namespaceDescriptor;
    }

A
Andrey Breslav 已提交
489 490 491 492 493 494 495 496 497
    private NamespaceDescriptor resolveNamespace(@NotNull PsiClass psiClass) {
        NamespaceDescriptor namespaceDescriptor = namespaceDescriptorCache.get(psiClass);
        if (namespaceDescriptor == null) {
            namespaceDescriptor = createJavaNamespaceDescriptor(psiClass);
            namespaceDescriptorCache.put(psiClass, namespaceDescriptor);
        }
        return namespaceDescriptor;
    }

498 499
    private NamespaceDescriptor createJavaNamespaceDescriptor(@NotNull PsiPackage psiPackage) {
        String name = psiPackage.getName();
500
        JavaNamespaceDescriptor namespaceDescriptor = new JavaNamespaceDescriptor(
501
                resolveParentDescriptor(psiPackage),
A
Andrey Breslav 已提交
502
                Collections.<AnnotationDescriptor>emptyList(), // TODO
503
                name == null ? JAVA_ROOT : name
504
        );
505

506
        namespaceDescriptor.setMemberScope(new JavaPackageScope(psiPackage.getQualifiedName(), namespaceDescriptor, semanticServices));
507
        semanticServices.getTrace().record(BindingContext.NAMESPACE, psiPackage, namespaceDescriptor);
508 509 510
        return namespaceDescriptor;
    }

511 512 513 514 515 516 517 518
    private DeclarationDescriptor resolveParentDescriptor(@NotNull PsiPackage psiPackage) {
        PsiPackage parentPackage = psiPackage.getParentPackage();
        if (parentPackage == null) {
            return null;
        }
        return resolveNamespace(parentPackage);
    }

519
    private NamespaceDescriptor createJavaNamespaceDescriptor(@NotNull final PsiClass psiClass) {
520
        JavaNamespaceDescriptor namespaceDescriptor = new JavaNamespaceDescriptor(
521
                resolveParentDescriptor(psiClass),
A
Andrey Breslav 已提交
522
                Collections.<AnnotationDescriptor>emptyList(), // TODO
523
                psiClass.getName()
524
        );
525
        namespaceDescriptor.setMemberScope(new JavaClassMembersScope(namespaceDescriptor, psiClass, semanticServices, true));
526
        semanticServices.getTrace().record(BindingContext.NAMESPACE, psiClass, namespaceDescriptor);
527 528
        return namespaceDescriptor;
    }
529 530 531 532 533 534 535 536 537 538
    
    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;
        }
    }
539

540
    public ValueParameterDescriptors resolveParameterDescriptors(DeclarationDescriptor containingDeclaration, PsiParameter[] parameters) {
541
        List<ValueParameterDescriptor> result = new ArrayList<ValueParameterDescriptor>();
542
        JetType receiverType = null;
543 544
        for (int i = 0, parametersLength = parameters.length; i < parametersLength; i++) {
            PsiParameter parameter = parameters[i];
545 546 547 548 549 550 551 552 553 554
            JvmMethodParameterMeaning meaning = resolveParameterDescriptor(containingDeclaration, i, parameter);
            if (meaning.kind == JvmMethodParameterKind.TYPE_INFO) {
                // TODO
            } else if (meaning.kind == JvmMethodParameterKind.REGULAR) {
                result.add(meaning.valueParameterDescriptor);
            } else if (meaning.kind == JvmMethodParameterKind.RECEIVER) {
                if (receiverType != null) {
                    throw new IllegalStateException("more then one receiver");
                }
                receiverType = meaning.receiverType;
S
Stepan Koltsov 已提交
555
            }
556
        }
557
        return new ValueParameterDescriptors(receiverType, result);
558
    }
A
Andrey Breslav 已提交
559

560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593
    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
    private JvmMethodParameterMeaning resolveParameterDescriptor(DeclarationDescriptor containingDeclaration, int i, PsiParameter parameter) {
594 595 596 597 598 599 600 601 602 603
        PsiType psiType = parameter.getType();

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

        boolean changeNullable = false;
        boolean nullable = true;
S
Stepan Koltsov 已提交
607
        String typeFromAnnotation = null;
608
        
609
        boolean receiver = false;
610
        boolean hasDefaultValue = false;
611
        
612 613 614 615
        // TODO: must be very slow, make it lazy?
        String name = parameter.getName() != null ? parameter.getName() : "p" + i;
        for (PsiAnnotation annotation : parameter.getModifierList().getAnnotations()) {

S
Stepan Koltsov 已提交
616 617
            if (annotation.getQualifiedName().equals(JvmStdlibNames.JET_VALUE_PARAMETER.getFqName())) {
                PsiLiteralExpression nameExpression = (PsiLiteralExpression) annotation.findAttributeValue(JvmStdlibNames.JET_VALUE_PARAMETER_NAME_FIELD);
618 619 620 621
                if (nameExpression != null) {
                    name = (String) nameExpression.getValue();
                }
                
S
Stepan Koltsov 已提交
622
                PsiLiteralExpression nullableExpression = (PsiLiteralExpression) annotation.findAttributeValue(JvmStdlibNames.JET_VALUE_PARAMETER_NULLABLE_FIELD);
623 624 625 626 627 628 629
                if (nullableExpression != null) {
                    nullable = (Boolean) nullableExpression.getValue();
                } else {
                    // default value of parameter
                    nullable = false;
                    changeNullable = true;
                }
S
Stepan Koltsov 已提交
630
                
S
Stepan Koltsov 已提交
631
                PsiLiteralExpression signatureExpression = (PsiLiteralExpression) annotation.findAttributeValue(JvmStdlibNames.JET_VALUE_PARAMETER_TYPE_FIELD);
S
Stepan Koltsov 已提交
632 633 634
                if (signatureExpression != null) {
                    typeFromAnnotation = (String) signatureExpression.getValue();
                }
635 636


S
Stepan Koltsov 已提交
637
                PsiLiteralExpression receiverExpression = (PsiLiteralExpression) annotation.findAttributeValue(JvmStdlibNames.JET_VALUE_PARAMETER_RECEIVER_FIELD);
638
                if (receiverExpression != null) {
639
                    receiver = (Boolean) receiverExpression.getValue();
640
                }
641
                
S
Stepan Koltsov 已提交
642
                PsiLiteralExpression hasDefaultValueExpression = (PsiLiteralExpression) annotation.findAttributeValue(JvmStdlibNames.JET_VALUE_PARAMETER_HAS_DEFAULT_VALUE_FIELD);
643 644 645
                if (hasDefaultValueExpression != null) {
                    hasDefaultValue = (Boolean) hasDefaultValueExpression.getValue();
                }
646 647


S
Stepan Koltsov 已提交
648
            } else if (annotation.getQualifiedName().equals(JvmStdlibNames.JET_TYPE_PARAMETER.getFqName())) {
649
                return JvmMethodParameterMeaning.typeInfo(new Object());
650 651 652
            }
        }
        
S
Stepan Koltsov 已提交
653 654 655 656 657 658
        JetType outType;
        if (typeFromAnnotation != null) {
            outType = semanticServices.getTypeTransformer().transformToType(typeFromAnnotation);
        } else {
            outType = semanticServices.getTypeTransformer().transformToType(psiType);
        }
659 660 661 662 663 664 665 666 667 668
        if (receiver) {
            return JvmMethodParameterMeaning.receiver(outType);
        } else {
            return JvmMethodParameterMeaning.regular(new ValueParameterDescriptorImpl(
                    containingDeclaration,
                    i,
                    Collections.<AnnotationDescriptor>emptyList(), // TODO
                    name,
                    null, // TODO : review
                    changeNullable ? TypeUtils.makeNullableAsSpecified(outType, nullable) : outType,
669
                    hasDefaultValue,
670 671 672
                    varargElementType
            ));
        }
673 674
    }

A
Andrey Breslav 已提交
675 676 677 678 679 680 681 682 683
    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 已提交
684
                Collections.<AnnotationDescriptor>emptyList(),
685
                Modality.FINAL,
686
                resolveVisibilityFromPsiModifiers(field),
A
Andrey Breslav 已提交
687 688
                !isFinal,
                null,
689
                DescriptorUtils.getExpectedThisObjectIfNeeded(containingDeclaration),
A
Andrey Breslav 已提交
690 691 692
                field.getName(),
                isFinal ? null : type,
                type);
693
        semanticServices.getTrace().record(BindingContext.VARIABLE, field, propertyDescriptor);
A
Andrey Breslav 已提交
694 695 696 697
        fieldDescriptorCache.put(field, propertyDescriptor);
        return propertyDescriptor;
    }

A
Andrey Breslav 已提交
698
    @NotNull
A
Andrey Breslav 已提交
699 700
    public Set<FunctionDescriptor> resolveFunctionGroup(@NotNull DeclarationDescriptor owner, @NotNull PsiClass psiClass, @Nullable ClassDescriptor classDescriptor, @NotNull String methodName, boolean staticMembers) {
        Set<FunctionDescriptor> writableFunctionGroup = Sets.newLinkedHashSet();
701
        final Collection<HierarchicalMethodSignature> signatures = psiClass.getVisibleSignatures();
A
Andrey Breslav 已提交
702
        TypeSubstitutor typeSubstitutor = createSubstitutorForGenericSupertypes(classDescriptor);
703
        for (HierarchicalMethodSignature signature: signatures) {
704
            if (!methodName.equals(signature.getName())) {
A
Andrey Breslav 已提交
705 706 707
                 continue;
            }

708
            FunctionDescriptor substitutedFunctionDescriptor = resolveHierarchicalSignatureToFunction(owner, psiClass, staticMembers, typeSubstitutor, signature);
709
            if (substitutedFunctionDescriptor != null) {
A
Andrey Breslav 已提交
710
                writableFunctionGroup.add(substitutedFunctionDescriptor);
711
            }
A
Andrey Breslav 已提交
712 713 714
        }
        return writableFunctionGroup;
    }
A
Andrey Breslav 已提交
715

716 717 718 719 720 721 722 723 724 725 726 727 728 729 730
    @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 已提交
731 732 733 734 735 736 737 738 739 740 741 742
    public TypeSubstitutor createSubstitutorForGenericSupertypes(ClassDescriptor classDescriptor) {
        TypeSubstitutor typeSubstitutor;
        if (classDescriptor != null) {
            typeSubstitutor = TypeUtils.buildDeepSubstitutor(classDescriptor.getDefaultType());
        }
        else {
            typeSubstitutor = TypeSubstitutor.EMPTY;
        }
        return typeSubstitutor;
    }

    @Nullable
A
Andrey Breslav 已提交
743
    public FunctionDescriptor resolveMethodToFunctionDescriptor(DeclarationDescriptor owner, PsiClass psiClass, TypeSubstitutor typeSubstitutorForGenericSuperclasses, PsiMethod method) {
A
Andrey Breslav 已提交
744 745 746 747 748 749 750 751 752 753 754
        PsiType returnType = method.getReturnType();
        if (returnType == null) {
            return null;
        }
        FunctionDescriptor functionDescriptor = methodDescriptorCache.get(method);
        if (functionDescriptor != null) {
            if (method.getContainingClass() != psiClass) {
                functionDescriptor = functionDescriptor.substitute(typeSubstitutorForGenericSuperclasses);
            }
            return functionDescriptor;
        }
A
Andrey Breslav 已提交
755
        DeclarationDescriptor classDescriptor = method.hasModifierProperty(PsiModifier.STATIC) ? resolveNamespace(method.getContainingClass()) : resolveClass(method.getContainingClass());
A
Andrey Breslav 已提交
756 757
        PsiParameter[] parameters = method.getParameterList().getParameters();
        FunctionDescriptorImpl functionDescriptorImpl = new FunctionDescriptorImpl(
A
Andrey Breslav 已提交
758 759
                owner,
                Collections.<AnnotationDescriptor>emptyList(), // TODO
A
Andrey Breslav 已提交
760 761 762
                method.getName()
        );
        methodDescriptorCache.put(method, functionDescriptorImpl);
763
        List<TypeParameterDescriptor> typeParameters = resolveMethodTypeParameters(method, functionDescriptorImpl);
764
        ValueParameterDescriptors valueParameterDescriptors = resolveParameterDescriptors(functionDescriptorImpl, parameters);
A
Andrey Breslav 已提交
765
        functionDescriptorImpl.initialize(
766
                valueParameterDescriptors.receiverType,
A
Andrey Breslav 已提交
767
                DescriptorUtils.getExpectedThisObjectIfNeeded(classDescriptor),
768
                typeParameters,
769
                valueParameterDescriptors.descriptors,
S
Stepan Koltsov 已提交
770
                makeReturnType(returnType, method),
771
                Modality.convertFromFlags(method.hasModifierProperty(PsiModifier.ABSTRACT), !method.hasModifierProperty(PsiModifier.FINAL)),
772
                resolveVisibilityFromPsiModifiers(method)
A
Andrey Breslav 已提交
773
        );
774
        semanticServices.getTrace().record(BindingContext.FUNCTION, method, functionDescriptorImpl);
A
Andrey Breslav 已提交
775 776 777 778 779 780
        FunctionDescriptor substitutedFunctionDescriptor = functionDescriptorImpl;
        if (method.getContainingClass() != psiClass) {
            substitutedFunctionDescriptor = functionDescriptorImpl.substitute(typeSubstitutorForGenericSuperclasses);
        }
        return substitutedFunctionDescriptor;
    }
781

782 783
    private List<TypeParameterDescriptor> resolveMethodTypeParameters(PsiMethod method, FunctionDescriptorImpl functionDescriptorImpl) {
        for (PsiAnnotation annotation : method.getModifierList().getAnnotations()) {
S
Stepan Koltsov 已提交
784 785
            if (annotation.getQualifiedName().equals(JvmStdlibNames.JET_METHOD.getFqName())) {
                PsiLiteralExpression attributeValue = (PsiLiteralExpression) annotation.findAttributeValue(JvmStdlibNames.JET_METHOD_TYPE_PARAMETERS_FIELD);
786 787 788
                if (attributeValue != null) {
                    String typeParametersString = (String) attributeValue.getValue();
                    if (typeParametersString != null) {
789 790 791
                        List<TypeParameterDescriptor> r = resolveMethodTypeParametersFromJetSignature(typeParametersString, method, functionDescriptorImpl);
                        initializeTypeParameters(method);
                        return r;
792 793 794 795 796 797 798 799 800
                    }
                }
            }
        }
        
        List<TypeParameterDescriptor> typeParameters = makeUninitializedTypeParameters(functionDescriptorImpl, method.getTypeParameters());
        initializeTypeParameters(method);
        return typeParameters;
    }
801 802

    /**
803
     * @see #resolveClassTypeParametersFromJetSignature(String, com.intellij.psi.PsiClass, JavaClassDescriptor) 
804
     */
805
    private List<TypeParameterDescriptor> resolveMethodTypeParametersFromJetSignature(String jetSignature, final PsiMethod method, final FunctionDescriptor functionDescriptor) {
806 807 808
        final List<TypeParameterDescriptor> r = new ArrayList<TypeParameterDescriptor>();
        new JetSignatureReader(jetSignature).acceptFormalTypeParametersOnly(new JetSignatureExceptionsAdapter() {
            @Override
S
Stepan Koltsov 已提交
809
            public JetSignatureVisitor visitFormalTypeParameter(final String name, final TypeInfoVariance variance) {
810 811
                
                return new JetSignatureTypeParameterVisitor(functionDescriptor, method, name, variance) {
812
                    @Override
813 814
                    protected void done(TypeParameterDescriptor typeParameterDescriptor) {
                        r.add(typeParameterDescriptor);
815 816
                    }
                };
817

818 819 820 821 822
            }
        });
        return r;
    }

823 824 825
    private JetType makeReturnType(PsiType returnType, PsiMethod method) {
        boolean changeNullable = false;
        boolean nullable = true;
S
Stepan Koltsov 已提交
826 827
        
        String returnTypeFromAnnotation = null;
828 829

        for (PsiAnnotation annotation : method.getModifierList().getAnnotations()) {
S
Stepan Koltsov 已提交
830 831
            if (annotation.getQualifiedName().equals(JvmStdlibNames.JET_METHOD.getFqName())) {
                PsiLiteralExpression nullableExpression = (PsiLiteralExpression) annotation.findAttributeValue(JvmStdlibNames.JET_METHOD_NULLABLE_RETURN_TYPE_FIELD);
832 833 834 835 836 837 838
                if (nullableExpression != null) {
                    nullable = (Boolean) nullableExpression.getValue();
                } else {
                    // default value of parameter
                    nullable = false;
                    changeNullable = true;
                }
S
Stepan Koltsov 已提交
839
                
S
Stepan Koltsov 已提交
840
                PsiLiteralExpression returnTypeExpression = (PsiLiteralExpression) annotation.findAttributeValue(JvmStdlibNames.JET_METHOD_RETURN_TYPE_FIELD);
S
Stepan Koltsov 已提交
841 842 843
                if (returnTypeExpression != null) {
                    returnTypeFromAnnotation = (String) returnTypeExpression.getValue();
                }
844 845
            }
        }
S
Stepan Koltsov 已提交
846 847 848 849 850 851
        JetType transformedType;
        if (returnTypeFromAnnotation != null) {
            transformedType = semanticServices.getTypeTransformer().transformToType(returnTypeFromAnnotation);
        } else {
            transformedType = semanticServices.getTypeTransformer().transformToType(returnType);
        }
852 853 854 855 856 857 858
        if (changeNullable) {
            return TypeUtils.makeNullableAsSpecified(transformedType, nullable);
        } else {
            return transformedType;
        }
    }

859
    private static Visibility resolveVisibilityFromPsiModifiers(PsiModifierListOwner modifierListOwner) {
860 861 862 863 864 865
        //TODO report error
        return modifierListOwner.hasModifierProperty(PsiModifier.PUBLIC) ? Visibility.PUBLIC :
                                        (modifierListOwner.hasModifierProperty(PsiModifier.PRIVATE) ? Visibility.PRIVATE :
                                        (modifierListOwner.hasModifierProperty(PsiModifier.PROTECTED) ? Visibility.PROTECTED : Visibility.INTERNAL));
    }

866 867
    @NotNull
    private TypeParameterDescriptorInitialization resolveTypeParameterInitialization(PsiTypeParameter typeParameter) {
868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891
        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);
    }
892 893 894 895

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