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

3
import com.google.common.collect.Lists;
A
Andrey Breslav 已提交
4
import com.google.common.collect.Maps;
A
Andrey Breslav 已提交
5
import com.google.common.collect.Sets;
6
import com.intellij.openapi.project.Project;
7
import com.intellij.openapi.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 21 22
import org.jetbrains.jet.rt.signature.JetSignatureExceptionsAdapter;
import org.jetbrains.jet.rt.signature.JetSignatureReader;
import org.jetbrains.jet.rt.signature.JetSignatureVisitor;
23 24 25 26 27 28 29

import java.util.*;

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

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

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

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

A
Andrey Breslav 已提交
46
    /*package*/ static final DeclarationDescriptor JAVA_CLASS_OBJECT = new DeclarationDescriptorImpl(null, Collections.<AnnotationDescriptor>emptyList(), "<java_class_object_emulation>") {
A
Andrey Breslav 已提交
47 48 49
        @NotNull
        @Override
        public DeclarationDescriptor substitute(TypeSubstitutor substitutor) {
50
            throw new UnsupportedOperationException();
A
Andrey Breslav 已提交
51 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
    protected final Map<String, ClassDescriptor> classDescriptorCache = Maps.newHashMap();
A
Andrey Breslav 已提交
60
    protected final Map<PsiTypeParameter, TypeParameterDescriptor> typeParameterDescriptorCache = Maps.newHashMap();
A
Andrey Breslav 已提交
61
    protected final Map<PsiMethod, FunctionDescriptor> methodDescriptorCache = Maps.newHashMap();
A
Andrey Breslav 已提交
62
    protected final Map<PsiField, VariableDescriptor> fieldDescriptorCache = Maps.newHashMap();
A
Andrey Breslav 已提交
63
    protected final Map<PsiElement, NamespaceDescriptor> namespaceDescriptorCache = Maps.newHashMap();
64 65 66 67 68 69
    protected final JavaPsiFacade javaFacade;
    protected final GlobalSearchScope javaSearchScope;
    protected final JavaSemanticServices semanticServices;

    public JavaDescriptorResolver(Project project, JavaSemanticServices semanticServices) {
        this.javaFacade = JavaPsiFacade.getInstance(project);
70 71 72 73 74 75
        this.javaSearchScope = new DelegatingGlobalSearchScope(GlobalSearchScope.allScope(project)) {
            @Override
            public boolean contains(VirtualFile file) {
                return myBaseScope.contains(file) && file.getFileType() != JetFileType.INSTANCE;
            }
        };
76 77 78 79 80 81
        this.semanticServices = semanticServices;
    }

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

83
        // First, let's check that this is a real Java class, not a Java's view on a Kotlin class:
84 85 86 87 88
        ClassDescriptor kotlinClassDescriptor = semanticServices.getKotlinClassDescriptor(qualifiedName);
        if (kotlinClassDescriptor != null) {
            return kotlinClassDescriptor;
        }

89
        // Not let's take a descriptor of a Java class
90 91 92 93 94 95 96 97 98 99
        ClassDescriptor classDescriptor = classDescriptorCache.get(qualifiedName);
        if (classDescriptor == null) {
            classDescriptor = createJavaClassDescriptor(psiClass);
            classDescriptorCache.put(qualifiedName, classDescriptor);
        }
        return classDescriptor;
    }

    @Nullable
    public ClassDescriptor resolveClass(@NotNull String qualifiedName) {
100
        // First, let's check that this is a real Java class, not a Java's view on a Kotlin class:
101 102 103 104 105
        ClassDescriptor kotlinClassDescriptor = semanticServices.getKotlinClassDescriptor(qualifiedName);
        if (kotlinClassDescriptor != null) {
            return kotlinClassDescriptor;
        }

106
        // Not let's take a descriptor of a Java class
107 108
        ClassDescriptor classDescriptor = classDescriptorCache.get(qualifiedName);
        if (classDescriptor == null) {
109
            PsiClass psiClass = findClass(qualifiedName);
110 111 112 113 114 115 116 117
            if (psiClass == null) {
                return null;
            }
            classDescriptor = createJavaClassDescriptor(psiClass);
        }
        return classDescriptor;
    }

118
    private ClassDescriptor createJavaClassDescriptor(@NotNull final PsiClass psiClass) {
A
Andrey Breslav 已提交
119 120 121
        assert !classDescriptorCache.containsKey(psiClass.getQualifiedName()) : psiClass.getQualifiedName();
        classDescriptorCache.put(psiClass.getQualifiedName(), null); // TODO

122
        String name = psiClass.getName();
123
        JavaClassDescriptor classDescriptor = new JavaClassDescriptor(
124
                resolveParentDescriptor(psiClass), psiClass.isInterface() ? ClassKind.TRAIT : ClassKind.CLASS
125
        );
A
Andrey Breslav 已提交
126
        classDescriptor.setName(name);
A
Andrey Breslav 已提交
127

A
Andrey Breslav 已提交
128
        List<JetType> supertypes = new ArrayList<JetType>();
129
        List<TypeParameterDescriptor> typeParameters = makeUninitializedTypeParameters(classDescriptor, psiClass.getTypeParameters());
A
Andrey Breslav 已提交
130 131
        classDescriptor.setTypeConstructor(new TypeConstructorImpl(
                classDescriptor,
A
Andrey Breslav 已提交
132
                Collections.<AnnotationDescriptor>emptyList(), // TODO
133
                // TODO
134
                psiClass.hasModifierProperty(PsiModifier.FINAL),
A
Andrey Breslav 已提交
135
                name,
A
Andrey Breslav 已提交
136
                typeParameters,
A
Andrey Breslav 已提交
137 138
                supertypes
        ));
139 140 141
        classDescriptor.setModality(Modality.convertFromFlags(
                psiClass.hasModifierProperty(PsiModifier.ABSTRACT) || psiClass.isInterface(),
                !psiClass.hasModifierProperty(PsiModifier.FINAL))
A
Andrey Breslav 已提交
142
        );
143
        classDescriptor.setVisibility(resolveVisibilityFromPsiModifiers(psiClass));
A
Andrey Breslav 已提交
144
        classDescriptorCache.put(psiClass.getQualifiedName(), classDescriptor);
145
        classDescriptor.setUnsubstitutedMemberScope(new JavaClassMembersScope(classDescriptor, psiClass, semanticServices, false));
146

A
Andrey Breslav 已提交
147
        // UGLY HACK
148 149
        initializeTypeParameters(psiClass);

A
Andrey Breslav 已提交
150
        supertypes.addAll(getSupertypes(psiClass));
151 152 153 154 155 156 157 158 159 160 161
        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 已提交
162 163

        PsiMethod[] psiConstructors = psiClass.getConstructors();
164 165

        if (psiConstructors.length == 0) {
A
Andrey Breslav 已提交
166 167 168 169 170
            // We need to create default constructors for classes and abstract classes.
            // Example:
            // class Kotlin() : Java() {}
            // abstract public class Java {}
            if (!psiClass.isInterface()) {
171 172
                ConstructorDescriptorImpl constructorDescriptor = new ConstructorDescriptorImpl(
                        classDescriptor,
A
Andrey Breslav 已提交
173
                        Collections.<AnnotationDescriptor>emptyList(),
174
                        false);
175
                constructorDescriptor.initialize(typeParameters, Collections.<ValueParameterDescriptor>emptyList(), Modality.FINAL, classDescriptor.getVisibility());
176
                constructorDescriptor.setReturnType(classDescriptor.getDefaultType());
177
                classDescriptor.addConstructor(constructorDescriptor);
178
                semanticServices.getTrace().record(BindingContext.CONSTRUCTOR, psiClass, constructorDescriptor);
179 180 181 182 183 184
            }
        }
        else {
            for (PsiMethod constructor : psiConstructors) {
                ConstructorDescriptorImpl constructorDescriptor = new ConstructorDescriptorImpl(
                        classDescriptor,
A
Andrey Breslav 已提交
185
                        Collections.<AnnotationDescriptor>emptyList(), // TODO
186
                        false);
187
                constructorDescriptor.initialize(typeParameters, resolveParameterDescriptors(constructorDescriptor, constructor.getParameterList().getParameters()), Modality.FINAL,
188
                                                 resolveVisibilityFromPsiModifiers(constructor));
189
                constructorDescriptor.setReturnType(classDescriptor.getDefaultType());
190
                classDescriptor.addConstructor(constructorDescriptor);
191
                semanticServices.getTrace().record(BindingContext.CONSTRUCTOR, constructor, constructorDescriptor);
192
            }
A
Andrey Breslav 已提交
193
        }
194

195
        semanticServices.getTrace().record(BindingContext.CLASS, psiClass, classDescriptor);
196

197 198 199
        return classDescriptor;
    }

200 201 202
    private DeclarationDescriptor resolveParentDescriptor(PsiClass psiClass) {
        PsiClass containingClass = psiClass.getContainingClass();
        if (containingClass != null) {
203
            return resolveClass(containingClass);
204 205 206 207 208 209 210
        }
        
        PsiJavaFile containingFile = (PsiJavaFile) psiClass.getContainingFile();
        String packageName = containingFile.getPackageName();
        return resolveNamespace(packageName);
    }

211
    private List<TypeParameterDescriptor> makeUninitializedTypeParameters(@NotNull DeclarationDescriptor containingDeclaration, @NotNull PsiTypeParameter[] typeParameters) {
212 213
        List<TypeParameterDescriptor> result = Lists.newArrayList();
        for (PsiTypeParameter typeParameter : typeParameters) {
214
            TypeParameterDescriptor typeParameterDescriptor = makeUninitializedTypeParameter(containingDeclaration, typeParameter);
A
Andrey Breslav 已提交
215
            result.add(typeParameterDescriptor);
216 217 218 219
        }
        return result;
    }

220 221 222
    @NotNull
    private TypeParameterDescriptor makeUninitializedTypeParameter(@NotNull DeclarationDescriptor containingDeclaration, @NotNull PsiTypeParameter psiTypeParameter) {
        assert typeParameterDescriptorCache.get(psiTypeParameter) == null : psiTypeParameter.getText();
223
        TypeParameterDescriptor typeParameterDescriptor = TypeParameterDescriptor.createForFurtherModification(
224
                containingDeclaration,
A
Andrey Breslav 已提交
225
                Collections.<AnnotationDescriptor>emptyList(), // TODO
A
Andrey Breslav 已提交
226
                false,
227
                Variance.INVARIANT,
228 229
                psiTypeParameter.getName(),
                psiTypeParameter.getIndex()
230
        );
231 232 233 234 235
        typeParameterDescriptorCache.put(psiTypeParameter, typeParameterDescriptor);
        return typeParameterDescriptor;
    }

    private void initializeTypeParameter(PsiTypeParameter typeParameter, TypeParameterDescriptor typeParameterDescriptor) {
A
Andrey Breslav 已提交
236 237
        PsiClassType[] referencedTypes = typeParameter.getExtendsList().getReferencedTypes();
        if (referencedTypes.length == 0){
238
            typeParameterDescriptor.addUpperBound(JetStandardClasses.getNullableAnyType());
A
Andrey Breslav 已提交
239 240
        }
        else if (referencedTypes.length == 1) {
241
            typeParameterDescriptor.addUpperBound(semanticServices.getTypeTransformer().transformToType(referencedTypes[0]));
A
Andrey Breslav 已提交
242 243 244
        }
        else {
            for (PsiClassType referencedType : referencedTypes) {
245
                typeParameterDescriptor.addUpperBound(semanticServices.getTypeTransformer().transformToType(referencedType));
A
Andrey Breslav 已提交
246 247
            }
        }
248 249 250 251 252 253
    }

    private void initializeTypeParameters(PsiTypeParameterListOwner typeParameterListOwner) {
        for (PsiTypeParameter psiTypeParameter : typeParameterListOwner.getTypeParameters()) {
            initializeTypeParameter(psiTypeParameter, resolveTypeParameter(psiTypeParameter));
        }
A
Andrey Breslav 已提交
254 255 256
    }

    @NotNull
257
    private TypeParameterDescriptor resolveTypeParameter(@NotNull DeclarationDescriptor containingDeclaration, @NotNull PsiTypeParameter psiTypeParameter) {
A
Andrey Breslav 已提交
258
        TypeParameterDescriptor typeParameterDescriptor = typeParameterDescriptorCache.get(psiTypeParameter);
259
        assert typeParameterDescriptor != null : psiTypeParameter.getText();
A
Andrey Breslav 已提交
260 261 262
        return typeParameterDescriptor;
    }

A
Andrey Breslav 已提交
263 264
    private Collection<? extends JetType> getSupertypes(PsiClass psiClass) {
        List<JetType> result = new ArrayList<JetType>();
265 266 267 268 269 270
        result.add(JetStandardClasses.getAnyType());
        transformSupertypeList(result, psiClass.getExtendsListTypes());
        transformSupertypeList(result, psiClass.getImplementsListTypes());
        return result;
    }

A
Andrey Breslav 已提交
271
    private void transformSupertypeList(List<JetType> result, PsiClassType[] extendsListTypes) {
272
        for (PsiClassType type : extendsListTypes) {
A
Andrey Breslav 已提交
273
            JetType transform = semanticServices.getTypeTransformer().transformToType(type);
274 275 276 277 278

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

279
    public NamespaceDescriptor resolveNamespace(String qualifiedName) {
280
        PsiPackage psiPackage = findPackage(qualifiedName);
281
        if (psiPackage == null) {
282
            PsiClass psiClass = findClass(qualifiedName);
A
Andrey Breslav 已提交
283 284
            if (psiClass == null) return null;
            return resolveNamespace(psiClass);
285 286 287 288
        }
        return resolveNamespace(psiPackage);
    }

289 290 291 292
    private PsiClass findClass(String qualifiedName) {
        return javaFacade.findClass(qualifiedName, javaSearchScope);
    }

293
    /*package*/ PsiPackage findPackage(String qualifiedName) {
294 295 296
        return javaFacade.findPackage(qualifiedName);
    }

297 298
    private NamespaceDescriptor resolveNamespace(@NotNull PsiPackage psiPackage) {
        NamespaceDescriptor namespaceDescriptor = namespaceDescriptorCache.get(psiPackage);
299
        if (namespaceDescriptor == null) {
A
Andrey Breslav 已提交
300
            namespaceDescriptor = createJavaNamespaceDescriptor(psiPackage);
301
            namespaceDescriptorCache.put(psiPackage, namespaceDescriptor);
302 303 304 305
        }
        return namespaceDescriptor;
    }

A
Andrey Breslav 已提交
306 307 308 309 310 311 312 313 314
    private NamespaceDescriptor resolveNamespace(@NotNull PsiClass psiClass) {
        NamespaceDescriptor namespaceDescriptor = namespaceDescriptorCache.get(psiClass);
        if (namespaceDescriptor == null) {
            namespaceDescriptor = createJavaNamespaceDescriptor(psiClass);
            namespaceDescriptorCache.put(psiClass, namespaceDescriptor);
        }
        return namespaceDescriptor;
    }

315 316
    private NamespaceDescriptor createJavaNamespaceDescriptor(@NotNull PsiPackage psiPackage) {
        String name = psiPackage.getName();
317
        JavaNamespaceDescriptor namespaceDescriptor = new JavaNamespaceDescriptor(
318
                resolveParentDescriptor(psiPackage),
A
Andrey Breslav 已提交
319
                Collections.<AnnotationDescriptor>emptyList(), // TODO
320
                name == null ? JAVA_ROOT : name
321
        );
322

323
        namespaceDescriptor.setMemberScope(new JavaPackageScope(psiPackage.getQualifiedName(), namespaceDescriptor, semanticServices));
324
        semanticServices.getTrace().record(BindingContext.NAMESPACE, psiPackage, namespaceDescriptor);
325 326 327
        return namespaceDescriptor;
    }

328 329 330 331 332 333 334 335
    private DeclarationDescriptor resolveParentDescriptor(@NotNull PsiPackage psiPackage) {
        PsiPackage parentPackage = psiPackage.getParentPackage();
        if (parentPackage == null) {
            return null;
        }
        return resolveNamespace(parentPackage);
    }

336
    private NamespaceDescriptor createJavaNamespaceDescriptor(@NotNull final PsiClass psiClass) {
337
        JavaNamespaceDescriptor namespaceDescriptor = new JavaNamespaceDescriptor(
338
                resolveParentDescriptor(psiClass),
A
Andrey Breslav 已提交
339
                Collections.<AnnotationDescriptor>emptyList(), // TODO
340
                psiClass.getName()
341
        );
342
        namespaceDescriptor.setMemberScope(new JavaClassMembersScope(namespaceDescriptor, psiClass, semanticServices, true));
343
        semanticServices.getTrace().record(BindingContext.NAMESPACE, psiClass, namespaceDescriptor);
344 345 346
        return namespaceDescriptor;
    }

347
    public List<ValueParameterDescriptor> resolveParameterDescriptors(DeclarationDescriptor containingDeclaration, PsiParameter[] parameters) {
348 349 350
        List<ValueParameterDescriptor> result = new ArrayList<ValueParameterDescriptor>();
        for (int i = 0, parametersLength = parameters.length; i < parametersLength; i++) {
            PsiParameter parameter = parameters[i];
351
            ValueParameterDescriptor valueParameterDescriptor = resolveParameterDescriptor(containingDeclaration, i, parameter);
S
Stepan Koltsov 已提交
352 353 354
            if (valueParameterDescriptor != null) {
                result.add(valueParameterDescriptor);
            }
355 356 357
        }
        return result;
    }
A
Andrey Breslav 已提交
358

S
Stepan Koltsov 已提交
359
    @Nullable
360 361 362 363 364 365 366 367 368 369 370
    private ValueParameterDescriptor resolveParameterDescriptor(DeclarationDescriptor containingDeclaration, int i, PsiParameter parameter) {
        PsiType psiType = parameter.getType();

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

        boolean changeNullable = false;
        boolean nullable = true;
S
Stepan Koltsov 已提交
374
        String typeFromAnnotation = null;
375 376 377 378 379 380 381 382 383
        
        // TODO: must be very slow, make it lazy?
        String name = parameter.getName() != null ? parameter.getName() : "p" + i;
        for (PsiAnnotation annotation : parameter.getModifierList().getAnnotations()) {
            // TODO: softcode annotation name

            PsiNameValuePair[] attributes = annotation.getParameterList().getAttributes();
            attributes.toString();

384
            if (annotation.getQualifiedName().equals(StdlibNames.JET_VALUE_PARAMETER.getFqName())) {
385
                PsiLiteralExpression nameExpression = (PsiLiteralExpression) annotation.findAttributeValue(StdlibNames.JET_VALUE_PARAMETER_NAME_FIELD);
386 387 388 389
                if (nameExpression != null) {
                    name = (String) nameExpression.getValue();
                }
                
390
                PsiLiteralExpression nullableExpression = (PsiLiteralExpression) annotation.findAttributeValue(StdlibNames.JET_VALUE_PARAMETER_NULLABLE_FIELD);
391 392 393 394 395 396 397
                if (nullableExpression != null) {
                    nullable = (Boolean) nullableExpression.getValue();
                } else {
                    // default value of parameter
                    nullable = false;
                    changeNullable = true;
                }
S
Stepan Koltsov 已提交
398 399 400 401 402
                
                PsiLiteralExpression signatureExpression = (PsiLiteralExpression) annotation.findAttributeValue(StdlibNames.JET_VALUE_PARAMETER_TYPE_FIELD);
                if (signatureExpression != null) {
                    typeFromAnnotation = (String) signatureExpression.getValue();
                }
403
            } else if (annotation.getQualifiedName().equals(StdlibNames.JET_TYPE_PARAMETER.getFqName())) {
S
Stepan Koltsov 已提交
404
                return null;
405 406 407
            }
        }
        
S
Stepan Koltsov 已提交
408 409 410 411 412 413
        JetType outType;
        if (typeFromAnnotation != null) {
            outType = semanticServices.getTypeTransformer().transformToType(typeFromAnnotation);
        } else {
            outType = semanticServices.getTypeTransformer().transformToType(psiType);
        }
414 415 416 417
        return new ValueParameterDescriptorImpl(
                containingDeclaration,
                i,
                Collections.<AnnotationDescriptor>emptyList(), // TODO
418
                name,
419
                null, // TODO : review
420
                changeNullable ? TypeUtils.makeNullableAsSpecified(outType, nullable) : outType,
421 422 423 424 425
                false,
                varargElementType
        );
    }

A
Andrey Breslav 已提交
426 427 428 429 430 431 432 433 434
    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 已提交
435
                Collections.<AnnotationDescriptor>emptyList(),
436
                Modality.FINAL,
437
                resolveVisibilityFromPsiModifiers(field),
A
Andrey Breslav 已提交
438 439
                !isFinal,
                null,
440
                DescriptorUtils.getExpectedThisObjectIfNeeded(containingDeclaration),
A
Andrey Breslav 已提交
441 442 443
                field.getName(),
                isFinal ? null : type,
                type);
444
        semanticServices.getTrace().record(BindingContext.VARIABLE, field, propertyDescriptor);
A
Andrey Breslav 已提交
445 446 447 448
        fieldDescriptorCache.put(field, propertyDescriptor);
        return propertyDescriptor;
    }

A
Andrey Breslav 已提交
449
    @NotNull
A
Andrey Breslav 已提交
450 451
    public Set<FunctionDescriptor> resolveFunctionGroup(@NotNull DeclarationDescriptor owner, @NotNull PsiClass psiClass, @Nullable ClassDescriptor classDescriptor, @NotNull String methodName, boolean staticMembers) {
        Set<FunctionDescriptor> writableFunctionGroup = Sets.newLinkedHashSet();
452
        final Collection<HierarchicalMethodSignature> signatures = psiClass.getVisibleSignatures();
A
Andrey Breslav 已提交
453
        TypeSubstitutor typeSubstitutor = createSubstitutorForGenericSupertypes(classDescriptor);
454
        for (HierarchicalMethodSignature signature: signatures) {
455
            if (!methodName.equals(signature.getName())) {
A
Andrey Breslav 已提交
456 457 458
                 continue;
            }

459
            FunctionDescriptor substitutedFunctionDescriptor = resolveHierarchicalSignatureToFunction(owner, psiClass, staticMembers, typeSubstitutor, signature);
460
            if (substitutedFunctionDescriptor != null) {
A
Andrey Breslav 已提交
461
                writableFunctionGroup.add(substitutedFunctionDescriptor);
462
            }
A
Andrey Breslav 已提交
463 464 465
        }
        return writableFunctionGroup;
    }
A
Andrey Breslav 已提交
466

467 468 469 470 471 472 473 474 475 476 477 478 479 480 481
    @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 已提交
482 483 484 485 486 487 488 489 490 491 492 493
    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 已提交
494
    public FunctionDescriptor resolveMethodToFunctionDescriptor(DeclarationDescriptor owner, PsiClass psiClass, TypeSubstitutor typeSubstitutorForGenericSuperclasses, PsiMethod method) {
A
Andrey Breslav 已提交
495 496 497 498 499 500 501 502 503 504 505
        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 已提交
506
        DeclarationDescriptor classDescriptor = method.hasModifierProperty(PsiModifier.STATIC) ? resolveNamespace(method.getContainingClass()) : resolveClass(method.getContainingClass());
A
Andrey Breslav 已提交
507 508
        PsiParameter[] parameters = method.getParameterList().getParameters();
        FunctionDescriptorImpl functionDescriptorImpl = new FunctionDescriptorImpl(
A
Andrey Breslav 已提交
509 510
                owner,
                Collections.<AnnotationDescriptor>emptyList(), // TODO
A
Andrey Breslav 已提交
511 512 513
                method.getName()
        );
        methodDescriptorCache.put(method, functionDescriptorImpl);
514
        List<TypeParameterDescriptor> typeParameters = resolveMethodTypeParameters(method, functionDescriptorImpl);
A
Andrey Breslav 已提交
515 516
        functionDescriptorImpl.initialize(
                null,
A
Andrey Breslav 已提交
517
                DescriptorUtils.getExpectedThisObjectIfNeeded(classDescriptor),
518
                typeParameters,
A
Andrey Breslav 已提交
519
                semanticServices.getDescriptorResolver().resolveParameterDescriptors(functionDescriptorImpl, parameters),
520
                semanticServices.getDescriptorResolver().makeReturnType(returnType, method),
521
                Modality.convertFromFlags(method.hasModifierProperty(PsiModifier.ABSTRACT), !method.hasModifierProperty(PsiModifier.FINAL)),
522
                resolveVisibilityFromPsiModifiers(method)
A
Andrey Breslav 已提交
523
        );
524
        semanticServices.getTrace().record(BindingContext.FUNCTION, method, functionDescriptorImpl);
A
Andrey Breslav 已提交
525 526 527 528 529 530
        FunctionDescriptor substitutedFunctionDescriptor = functionDescriptorImpl;
        if (method.getContainingClass() != psiClass) {
            substitutedFunctionDescriptor = functionDescriptorImpl.substitute(typeSubstitutorForGenericSuperclasses);
        }
        return substitutedFunctionDescriptor;
    }
531

532 533
    private List<TypeParameterDescriptor> resolveMethodTypeParameters(PsiMethod method, FunctionDescriptorImpl functionDescriptorImpl) {
        for (PsiAnnotation annotation : method.getModifierList().getAnnotations()) {
534
            if (annotation.getQualifiedName().equals(StdlibNames.JET_METHOD.getFqName())) {
535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553
                PsiLiteralExpression attributeValue = (PsiLiteralExpression) annotation.findAttributeValue(StdlibNames.JET_METHOD_TYPE_PARAMETERS_FIELD);
                if (attributeValue != null) {
                    String typeParametersString = (String) attributeValue.getValue();
                    if (typeParametersString != null) {
                        return resolveMethodTypeParametersFromJetSignature(typeParametersString, functionDescriptorImpl);
                    }
                }
            }
        }
        
        List<TypeParameterDescriptor> typeParameters = makeUninitializedTypeParameters(functionDescriptorImpl, method.getTypeParameters());
        initializeTypeParameters(method);
        return typeParameters;
    }
    
    private List<TypeParameterDescriptor> resolveMethodTypeParametersFromJetSignature(String jetSignature, final FunctionDescriptor functionDescriptor) {
        final List<TypeParameterDescriptor> r = new ArrayList<TypeParameterDescriptor>();
        new JetSignatureReader(jetSignature).acceptFormalTypeParametersOnly(new JetSignatureExceptionsAdapter() {
            @Override
S
Stepan Koltsov 已提交
554
            public JetSignatureVisitor visitFormalTypeParameter(final String name, final TypeInfoVariance variance) {
555 556 557 558 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

                return new JetSignatureExceptionsAdapter() {
                    int index = 0;

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

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

                    @Override
                    public void visitFormalTypeParameterEnd() {
                        TypeParameterDescriptor typeParameter = TypeParameterDescriptor.createForFurtherModification(
                                functionDescriptor,
                                Collections.<AnnotationDescriptor>emptyList(), // TODO: wrong
                                true, // TODO: wrong
S
Stepan Koltsov 已提交
585
                                JetSignatureUtils.translateVariance(variance),
586 587 588 589 590 591 592 593 594 595
                                name,
                                ++index);
                        r.add(typeParameter);
                    }
                };
            }
        });
        return r;
    }

596 597 598
    private JetType makeReturnType(PsiType returnType, PsiMethod method) {
        boolean changeNullable = false;
        boolean nullable = true;
S
Stepan Koltsov 已提交
599 600
        
        String returnTypeFromAnnotation = null;
601 602

        for (PsiAnnotation annotation : method.getModifierList().getAnnotations()) {
603
            if (annotation.getQualifiedName().equals(StdlibNames.JET_METHOD.getFqName())) {
S
Stepan Koltsov 已提交
604
                PsiLiteralExpression nullableExpression = (PsiLiteralExpression) annotation.findAttributeValue(StdlibNames.JET_METHOD_NULLABLE_RETURN_TYPE_FIELD);
605 606 607 608 609 610 611
                if (nullableExpression != null) {
                    nullable = (Boolean) nullableExpression.getValue();
                } else {
                    // default value of parameter
                    nullable = false;
                    changeNullable = true;
                }
S
Stepan Koltsov 已提交
612 613 614 615 616
                
                PsiLiteralExpression returnTypeExpression = (PsiLiteralExpression) annotation.findAttributeValue(StdlibNames.JET_METHOD_RETURN_TYPE_FIELD);
                if (returnTypeExpression != null) {
                    returnTypeFromAnnotation = (String) returnTypeExpression.getValue();
                }
617 618
            }
        }
S
Stepan Koltsov 已提交
619 620 621 622 623 624
        JetType transformedType;
        if (returnTypeFromAnnotation != null) {
            transformedType = semanticServices.getTypeTransformer().transformToType(returnTypeFromAnnotation);
        } else {
            transformedType = semanticServices.getTypeTransformer().transformToType(returnType);
        }
625 626 627 628 629 630 631
        if (changeNullable) {
            return TypeUtils.makeNullableAsSpecified(transformedType, nullable);
        } else {
            return transformedType;
        }
    }

632
    private static Visibility resolveVisibilityFromPsiModifiers(PsiModifierListOwner modifierListOwner) {
633 634 635 636 637 638
        //TODO report error
        return modifierListOwner.hasModifierProperty(PsiModifier.PUBLIC) ? Visibility.PUBLIC :
                                        (modifierListOwner.hasModifierProperty(PsiModifier.PRIVATE) ? Visibility.PRIVATE :
                                        (modifierListOwner.hasModifierProperty(PsiModifier.PROTECTED) ? Visibility.PROTECTED : Visibility.INTERNAL));
    }

639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663
    public TypeParameterDescriptor resolveTypeParameter(PsiTypeParameter typeParameter) {
        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);
    }
664
}