JavaDescriptorResolver.java 37.0 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 59
        }

        @Override
        public <R, D> R accept(DeclarationDescriptorVisitor<R, D> visitor, D data) {
            return visitor.visitDeclarationDescriptor(this, data);
        }
    };

60
    protected final Map<String, ClassDescriptor> classDescriptorCache = Maps.newHashMap();
A
Andrey Breslav 已提交
61
    protected final Map<PsiTypeParameter, TypeParameterDescriptor> typeParameterDescriptorCache = Maps.newHashMap();
A
Andrey Breslav 已提交
62
    protected final Map<PsiMethod, FunctionDescriptor> methodDescriptorCache = Maps.newHashMap();
A
Andrey Breslav 已提交
63
    protected final Map<PsiField, VariableDescriptor> fieldDescriptorCache = Maps.newHashMap();
A
Andrey Breslav 已提交
64
    protected final Map<PsiElement, NamespaceDescriptor> namespaceDescriptorCache = Maps.newHashMap();
65 66 67 68 69 70
    protected final JavaPsiFacade javaFacade;
    protected final GlobalSearchScope javaSearchScope;
    protected final JavaSemanticServices semanticServices;

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

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

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

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

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

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

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

123
        String name = psiClass.getName();
124
        JavaClassDescriptor classDescriptor = new JavaClassDescriptor(
125
                resolveParentDescriptor(psiClass), psiClass.isInterface() ? ClassKind.TRAIT : ClassKind.CLASS
126
        );
A
Andrey Breslav 已提交
127
        classDescriptor.setName(name);
128
        
A
Andrey Breslav 已提交
129
        List<JetType> supertypes = new ArrayList<JetType>();
130
        List<TypeParameterDescriptor> typeParameters = resolveClassTypeParameters(psiClass, classDescriptor);
A
Andrey Breslav 已提交
131 132
        classDescriptor.setTypeConstructor(new TypeConstructorImpl(
                classDescriptor,
A
Andrey Breslav 已提交
133
                Collections.<AnnotationDescriptor>emptyList(), // TODO
134
                // TODO
135
                psiClass.hasModifierProperty(PsiModifier.FINAL),
A
Andrey Breslav 已提交
136
                name,
A
Andrey Breslav 已提交
137
                typeParameters,
A
Andrey Breslav 已提交
138 139
                supertypes
        ));
140 141 142
        classDescriptor.setModality(Modality.convertFromFlags(
                psiClass.hasModifierProperty(PsiModifier.ABSTRACT) || psiClass.isInterface(),
                !psiClass.hasModifierProperty(PsiModifier.FINAL))
A
Andrey Breslav 已提交
143
        );
144
        classDescriptor.setVisibility(resolveVisibilityFromPsiModifiers(psiClass));
A
Andrey Breslav 已提交
145
        classDescriptorCache.put(psiClass.getQualifiedName(), classDescriptor);
146
        classDescriptor.setUnsubstitutedMemberScope(new JavaClassMembersScope(classDescriptor, psiClass, semanticServices, false));
147

148 149
        // UGLY HACK (Andrey Breslav is not sure what did he mean)
        initializeTypeParameters(psiClass);
150

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

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

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

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

198 199 200
        return classDescriptor;
    }

201 202 203 204 205 206 207
    private List<TypeParameterDescriptor> resolveClassTypeParameters(PsiClass psiClass, JavaClassDescriptor classDescriptor) {
        for (PsiAnnotation annotation : psiClass.getModifierList().getAnnotations()) {
            if (annotation.getQualifiedName().equals(StdlibNames.JET_CLASS.getFqName())) {
                PsiLiteralExpression attributeValue = (PsiLiteralExpression) annotation.findAttributeValue(StdlibNames.JET_CLASS_SIGNATURE);
                if (attributeValue != null) {
                    String typeParametersString = (String) attributeValue.getValue();
                    if (typeParametersString != null) {
208
                        return resolveClassTypeParametersFromJetSignature(typeParametersString, psiClass, classDescriptor);
209 210 211 212 213 214 215
                    }
                }
            }
        }
        return makeUninitializedTypeParameters(classDescriptor, psiClass.getTypeParameters());
    }

216 217 218 219 220 221 222 223 224 225
    @NotNull
    private PsiTypeParameter getPsiTypeParameterByName(PsiTypeParameterListOwner clazz, String ownerName, String name) {
        for (PsiTypeParameter typeParameter : clazz.getTypeParameters()) {
            if (typeParameter.getName().equals(name)) {
                return typeParameter; 
            }
        }
        throw new IllegalStateException("PsiTypeParameter '" + name + "' is not found in '" + ownerName + "'");
    }

226 227 228
    /**
     * @see #resolveMethodTypeParametersFromJetSignature(String, FunctionDescriptor)
     */
229
    private List<TypeParameterDescriptor> resolveClassTypeParametersFromJetSignature(String jetSignature, final PsiClass clazz, final JavaClassDescriptor classDescriptor) {
230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265
        final List<TypeParameterDescriptor> r = new ArrayList<TypeParameterDescriptor>();
        new JetSignatureReader(jetSignature).accept(new JetSignatureExceptionsAdapter() {
            @Override
            public JetSignatureVisitor visitFormalTypeParameter(final String name, final TypeInfoVariance variance) {
                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(
                                classDescriptor,
                                Collections.<AnnotationDescriptor>emptyList(), // TODO: wrong
                                true, // TODO: wrong
                                JetSignatureUtils.translateVariance(variance),
                                name,
                                ++index);
266 267
                        PsiTypeParameter psiTypeParameter = getPsiTypeParameterByName(clazz, clazz.getQualifiedName(), name);
                        typeParameterDescriptorCache.put(psiTypeParameter, typeParameter);
268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288
                        r.add(typeParameter);
                    }

                };
            }

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

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

289 290 291
    private DeclarationDescriptor resolveParentDescriptor(PsiClass psiClass) {
        PsiClass containingClass = psiClass.getContainingClass();
        if (containingClass != null) {
292
            return resolveClass(containingClass);
293 294 295 296 297 298 299
        }
        
        PsiJavaFile containingFile = (PsiJavaFile) psiClass.getContainingFile();
        String packageName = containingFile.getPackageName();
        return resolveNamespace(packageName);
    }

300
    private List<TypeParameterDescriptor> makeUninitializedTypeParameters(@NotNull DeclarationDescriptor containingDeclaration, @NotNull PsiTypeParameter[] typeParameters) {
301 302
        List<TypeParameterDescriptor> result = Lists.newArrayList();
        for (PsiTypeParameter typeParameter : typeParameters) {
303
            TypeParameterDescriptor typeParameterDescriptor = makeUninitializedTypeParameter(containingDeclaration, typeParameter);
A
Andrey Breslav 已提交
304
            result.add(typeParameterDescriptor);
305 306 307 308
        }
        return result;
    }

309 310 311
    @NotNull
    private TypeParameterDescriptor makeUninitializedTypeParameter(@NotNull DeclarationDescriptor containingDeclaration, @NotNull PsiTypeParameter psiTypeParameter) {
        assert typeParameterDescriptorCache.get(psiTypeParameter) == null : psiTypeParameter.getText();
312
        TypeParameterDescriptor typeParameterDescriptor = TypeParameterDescriptor.createForFurtherModification(
313
                containingDeclaration,
A
Andrey Breslav 已提交
314
                Collections.<AnnotationDescriptor>emptyList(), // TODO
A
Andrey Breslav 已提交
315
                false,
316
                Variance.INVARIANT,
317 318
                psiTypeParameter.getName(),
                psiTypeParameter.getIndex()
319
        );
320 321 322 323 324
        typeParameterDescriptorCache.put(psiTypeParameter, typeParameterDescriptor);
        return typeParameterDescriptor;
    }

    private void initializeTypeParameter(PsiTypeParameter typeParameter, TypeParameterDescriptor typeParameterDescriptor) {
A
Andrey Breslav 已提交
325 326
        PsiClassType[] referencedTypes = typeParameter.getExtendsList().getReferencedTypes();
        if (referencedTypes.length == 0){
327
            typeParameterDescriptor.addUpperBound(JetStandardClasses.getNullableAnyType());
A
Andrey Breslav 已提交
328 329
        }
        else if (referencedTypes.length == 1) {
330
            typeParameterDescriptor.addUpperBound(semanticServices.getTypeTransformer().transformToType(referencedTypes[0]));
A
Andrey Breslav 已提交
331 332 333
        }
        else {
            for (PsiClassType referencedType : referencedTypes) {
334
                typeParameterDescriptor.addUpperBound(semanticServices.getTypeTransformer().transformToType(referencedType));
A
Andrey Breslav 已提交
335 336
            }
        }
337 338 339 340 341 342
    }

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

    @NotNull
346
    private TypeParameterDescriptor resolveTypeParameter(@NotNull DeclarationDescriptor containingDeclaration, @NotNull PsiTypeParameter psiTypeParameter) {
A
Andrey Breslav 已提交
347
        TypeParameterDescriptor typeParameterDescriptor = typeParameterDescriptorCache.get(psiTypeParameter);
348
        assert typeParameterDescriptor != null : psiTypeParameter.getText();
A
Andrey Breslav 已提交
349 350 351
        return typeParameterDescriptor;
    }

A
Andrey Breslav 已提交
352 353
    private Collection<? extends JetType> getSupertypes(PsiClass psiClass) {
        List<JetType> result = new ArrayList<JetType>();
354 355 356 357 358 359
        result.add(JetStandardClasses.getAnyType());
        transformSupertypeList(result, psiClass.getExtendsListTypes());
        transformSupertypeList(result, psiClass.getImplementsListTypes());
        return result;
    }

A
Andrey Breslav 已提交
360
    private void transformSupertypeList(List<JetType> result, PsiClassType[] extendsListTypes) {
361
        for (PsiClassType type : extendsListTypes) {
A
Andrey Breslav 已提交
362
            JetType transform = semanticServices.getTypeTransformer().transformToType(type);
363 364 365 366 367

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

368
    public NamespaceDescriptor resolveNamespace(String qualifiedName) {
369
        PsiPackage psiPackage = findPackage(qualifiedName);
370
        if (psiPackage == null) {
371
            PsiClass psiClass = findClass(qualifiedName);
A
Andrey Breslav 已提交
372 373
            if (psiClass == null) return null;
            return resolveNamespace(psiClass);
374 375 376 377
        }
        return resolveNamespace(psiPackage);
    }

378 379 380 381
    private PsiClass findClass(String qualifiedName) {
        return javaFacade.findClass(qualifiedName, javaSearchScope);
    }

382
    /*package*/ PsiPackage findPackage(String qualifiedName) {
383 384 385
        return javaFacade.findPackage(qualifiedName);
    }

386 387
    private NamespaceDescriptor resolveNamespace(@NotNull PsiPackage psiPackage) {
        NamespaceDescriptor namespaceDescriptor = namespaceDescriptorCache.get(psiPackage);
388
        if (namespaceDescriptor == null) {
A
Andrey Breslav 已提交
389
            namespaceDescriptor = createJavaNamespaceDescriptor(psiPackage);
390
            namespaceDescriptorCache.put(psiPackage, namespaceDescriptor);
391 392 393 394
        }
        return namespaceDescriptor;
    }

A
Andrey Breslav 已提交
395 396 397 398 399 400 401 402 403
    private NamespaceDescriptor resolveNamespace(@NotNull PsiClass psiClass) {
        NamespaceDescriptor namespaceDescriptor = namespaceDescriptorCache.get(psiClass);
        if (namespaceDescriptor == null) {
            namespaceDescriptor = createJavaNamespaceDescriptor(psiClass);
            namespaceDescriptorCache.put(psiClass, namespaceDescriptor);
        }
        return namespaceDescriptor;
    }

404 405
    private NamespaceDescriptor createJavaNamespaceDescriptor(@NotNull PsiPackage psiPackage) {
        String name = psiPackage.getName();
406
        JavaNamespaceDescriptor namespaceDescriptor = new JavaNamespaceDescriptor(
407
                resolveParentDescriptor(psiPackage),
A
Andrey Breslav 已提交
408
                Collections.<AnnotationDescriptor>emptyList(), // TODO
409
                name == null ? JAVA_ROOT : name
410
        );
411

412
        namespaceDescriptor.setMemberScope(new JavaPackageScope(psiPackage.getQualifiedName(), namespaceDescriptor, semanticServices));
413
        semanticServices.getTrace().record(BindingContext.NAMESPACE, psiPackage, namespaceDescriptor);
414 415 416
        return namespaceDescriptor;
    }

417 418 419 420 421 422 423 424
    private DeclarationDescriptor resolveParentDescriptor(@NotNull PsiPackage psiPackage) {
        PsiPackage parentPackage = psiPackage.getParentPackage();
        if (parentPackage == null) {
            return null;
        }
        return resolveNamespace(parentPackage);
    }

425
    private NamespaceDescriptor createJavaNamespaceDescriptor(@NotNull final PsiClass psiClass) {
426
        JavaNamespaceDescriptor namespaceDescriptor = new JavaNamespaceDescriptor(
427
                resolveParentDescriptor(psiClass),
A
Andrey Breslav 已提交
428
                Collections.<AnnotationDescriptor>emptyList(), // TODO
429
                psiClass.getName()
430
        );
431
        namespaceDescriptor.setMemberScope(new JavaClassMembersScope(namespaceDescriptor, psiClass, semanticServices, true));
432
        semanticServices.getTrace().record(BindingContext.NAMESPACE, psiClass, namespaceDescriptor);
433 434 435
        return namespaceDescriptor;
    }

436
    public List<ValueParameterDescriptor> resolveParameterDescriptors(DeclarationDescriptor containingDeclaration, PsiParameter[] parameters) {
437 438 439
        List<ValueParameterDescriptor> result = new ArrayList<ValueParameterDescriptor>();
        for (int i = 0, parametersLength = parameters.length; i < parametersLength; i++) {
            PsiParameter parameter = parameters[i];
440
            ValueParameterDescriptor valueParameterDescriptor = resolveParameterDescriptor(containingDeclaration, i, parameter);
S
Stepan Koltsov 已提交
441 442 443
            if (valueParameterDescriptor != null) {
                result.add(valueParameterDescriptor);
            }
444 445 446
        }
        return result;
    }
A
Andrey Breslav 已提交
447

S
Stepan Koltsov 已提交
448
    @Nullable
449 450 451 452 453 454 455 456 457 458 459
    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;
        }
460 461 462

        boolean changeNullable = false;
        boolean nullable = true;
S
Stepan Koltsov 已提交
463
        String typeFromAnnotation = null;
464 465 466 467 468 469 470 471 472
        
        // 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();

473
            if (annotation.getQualifiedName().equals(StdlibNames.JET_VALUE_PARAMETER.getFqName())) {
474
                PsiLiteralExpression nameExpression = (PsiLiteralExpression) annotation.findAttributeValue(StdlibNames.JET_VALUE_PARAMETER_NAME_FIELD);
475 476 477 478
                if (nameExpression != null) {
                    name = (String) nameExpression.getValue();
                }
                
479
                PsiLiteralExpression nullableExpression = (PsiLiteralExpression) annotation.findAttributeValue(StdlibNames.JET_VALUE_PARAMETER_NULLABLE_FIELD);
480 481 482 483 484 485 486
                if (nullableExpression != null) {
                    nullable = (Boolean) nullableExpression.getValue();
                } else {
                    // default value of parameter
                    nullable = false;
                    changeNullable = true;
                }
S
Stepan Koltsov 已提交
487 488 489 490 491
                
                PsiLiteralExpression signatureExpression = (PsiLiteralExpression) annotation.findAttributeValue(StdlibNames.JET_VALUE_PARAMETER_TYPE_FIELD);
                if (signatureExpression != null) {
                    typeFromAnnotation = (String) signatureExpression.getValue();
                }
492
            } else if (annotation.getQualifiedName().equals(StdlibNames.JET_TYPE_PARAMETER.getFqName())) {
S
Stepan Koltsov 已提交
493
                return null;
494 495 496
            }
        }
        
S
Stepan Koltsov 已提交
497 498 499 500 501 502
        JetType outType;
        if (typeFromAnnotation != null) {
            outType = semanticServices.getTypeTransformer().transformToType(typeFromAnnotation);
        } else {
            outType = semanticServices.getTypeTransformer().transformToType(psiType);
        }
503 504 505 506
        return new ValueParameterDescriptorImpl(
                containingDeclaration,
                i,
                Collections.<AnnotationDescriptor>emptyList(), // TODO
507
                name,
508
                null, // TODO : review
509
                changeNullable ? TypeUtils.makeNullableAsSpecified(outType, nullable) : outType,
510 511 512 513 514
                false,
                varargElementType
        );
    }

A
Andrey Breslav 已提交
515 516 517 518 519 520 521 522 523
    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 已提交
524
                Collections.<AnnotationDescriptor>emptyList(),
525
                Modality.FINAL,
526
                resolveVisibilityFromPsiModifiers(field),
A
Andrey Breslav 已提交
527 528
                !isFinal,
                null,
529
                DescriptorUtils.getExpectedThisObjectIfNeeded(containingDeclaration),
A
Andrey Breslav 已提交
530 531 532
                field.getName(),
                isFinal ? null : type,
                type);
533
        semanticServices.getTrace().record(BindingContext.VARIABLE, field, propertyDescriptor);
A
Andrey Breslav 已提交
534 535 536 537
        fieldDescriptorCache.put(field, propertyDescriptor);
        return propertyDescriptor;
    }

A
Andrey Breslav 已提交
538
    @NotNull
A
Andrey Breslav 已提交
539 540
    public Set<FunctionDescriptor> resolveFunctionGroup(@NotNull DeclarationDescriptor owner, @NotNull PsiClass psiClass, @Nullable ClassDescriptor classDescriptor, @NotNull String methodName, boolean staticMembers) {
        Set<FunctionDescriptor> writableFunctionGroup = Sets.newLinkedHashSet();
541
        final Collection<HierarchicalMethodSignature> signatures = psiClass.getVisibleSignatures();
A
Andrey Breslav 已提交
542
        TypeSubstitutor typeSubstitutor = createSubstitutorForGenericSupertypes(classDescriptor);
543
        for (HierarchicalMethodSignature signature: signatures) {
544
            if (!methodName.equals(signature.getName())) {
A
Andrey Breslav 已提交
545 546 547
                 continue;
            }

548
            FunctionDescriptor substitutedFunctionDescriptor = resolveHierarchicalSignatureToFunction(owner, psiClass, staticMembers, typeSubstitutor, signature);
549
            if (substitutedFunctionDescriptor != null) {
A
Andrey Breslav 已提交
550
                writableFunctionGroup.add(substitutedFunctionDescriptor);
551
            }
A
Andrey Breslav 已提交
552 553 554
        }
        return writableFunctionGroup;
    }
A
Andrey Breslav 已提交
555

556 557 558 559 560 561 562 563 564 565 566 567 568 569 570
    @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 已提交
571 572 573 574 575 576 577 578 579 580 581 582
    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 已提交
583
    public FunctionDescriptor resolveMethodToFunctionDescriptor(DeclarationDescriptor owner, PsiClass psiClass, TypeSubstitutor typeSubstitutorForGenericSuperclasses, PsiMethod method) {
A
Andrey Breslav 已提交
584 585 586 587 588 589 590 591 592 593 594
        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 已提交
595
        DeclarationDescriptor classDescriptor = method.hasModifierProperty(PsiModifier.STATIC) ? resolveNamespace(method.getContainingClass()) : resolveClass(method.getContainingClass());
A
Andrey Breslav 已提交
596 597
        PsiParameter[] parameters = method.getParameterList().getParameters();
        FunctionDescriptorImpl functionDescriptorImpl = new FunctionDescriptorImpl(
A
Andrey Breslav 已提交
598 599
                owner,
                Collections.<AnnotationDescriptor>emptyList(), // TODO
A
Andrey Breslav 已提交
600 601 602
                method.getName()
        );
        methodDescriptorCache.put(method, functionDescriptorImpl);
603
        List<TypeParameterDescriptor> typeParameters = resolveMethodTypeParameters(method, functionDescriptorImpl);
A
Andrey Breslav 已提交
604 605
        functionDescriptorImpl.initialize(
                null,
A
Andrey Breslav 已提交
606
                DescriptorUtils.getExpectedThisObjectIfNeeded(classDescriptor),
607
                typeParameters,
A
Andrey Breslav 已提交
608
                semanticServices.getDescriptorResolver().resolveParameterDescriptors(functionDescriptorImpl, parameters),
609
                semanticServices.getDescriptorResolver().makeReturnType(returnType, method),
610
                Modality.convertFromFlags(method.hasModifierProperty(PsiModifier.ABSTRACT), !method.hasModifierProperty(PsiModifier.FINAL)),
611
                resolveVisibilityFromPsiModifiers(method)
A
Andrey Breslav 已提交
612
        );
613
        semanticServices.getTrace().record(BindingContext.FUNCTION, method, functionDescriptorImpl);
A
Andrey Breslav 已提交
614 615 616 617 618 619
        FunctionDescriptor substitutedFunctionDescriptor = functionDescriptorImpl;
        if (method.getContainingClass() != psiClass) {
            substitutedFunctionDescriptor = functionDescriptorImpl.substitute(typeSubstitutorForGenericSuperclasses);
        }
        return substitutedFunctionDescriptor;
    }
620

621 622
    private List<TypeParameterDescriptor> resolveMethodTypeParameters(PsiMethod method, FunctionDescriptorImpl functionDescriptorImpl) {
        for (PsiAnnotation annotation : method.getModifierList().getAnnotations()) {
623
            if (annotation.getQualifiedName().equals(StdlibNames.JET_METHOD.getFqName())) {
624 625 626 627 628 629 630 631 632 633 634 635 636 637
                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;
    }
638 639 640 641

    /**
     * @see #resolveClassTypeParametersFromJetSignature(String, JavaClassDescriptor)
     */
642 643 644 645
    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 已提交
646
            public JetSignatureVisitor visitFormalTypeParameter(final String name, final TypeInfoVariance variance) {
647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676

                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 已提交
677
                                JetSignatureUtils.translateVariance(variance),
678 679 680 681 682 683 684 685 686 687
                                name,
                                ++index);
                        r.add(typeParameter);
                    }
                };
            }
        });
        return r;
    }

688 689 690
    private JetType makeReturnType(PsiType returnType, PsiMethod method) {
        boolean changeNullable = false;
        boolean nullable = true;
S
Stepan Koltsov 已提交
691 692
        
        String returnTypeFromAnnotation = null;
693 694

        for (PsiAnnotation annotation : method.getModifierList().getAnnotations()) {
695
            if (annotation.getQualifiedName().equals(StdlibNames.JET_METHOD.getFqName())) {
S
Stepan Koltsov 已提交
696
                PsiLiteralExpression nullableExpression = (PsiLiteralExpression) annotation.findAttributeValue(StdlibNames.JET_METHOD_NULLABLE_RETURN_TYPE_FIELD);
697 698 699 700 701 702 703
                if (nullableExpression != null) {
                    nullable = (Boolean) nullableExpression.getValue();
                } else {
                    // default value of parameter
                    nullable = false;
                    changeNullable = true;
                }
S
Stepan Koltsov 已提交
704 705 706 707 708
                
                PsiLiteralExpression returnTypeExpression = (PsiLiteralExpression) annotation.findAttributeValue(StdlibNames.JET_METHOD_RETURN_TYPE_FIELD);
                if (returnTypeExpression != null) {
                    returnTypeFromAnnotation = (String) returnTypeExpression.getValue();
                }
709 710
            }
        }
S
Stepan Koltsov 已提交
711 712 713 714 715 716
        JetType transformedType;
        if (returnTypeFromAnnotation != null) {
            transformedType = semanticServices.getTypeTransformer().transformToType(returnTypeFromAnnotation);
        } else {
            transformedType = semanticServices.getTypeTransformer().transformToType(returnType);
        }
717 718 719 720 721 722 723
        if (changeNullable) {
            return TypeUtils.makeNullableAsSpecified(transformedType, nullable);
        } else {
            return transformedType;
        }
    }

724
    private static Visibility resolveVisibilityFromPsiModifiers(PsiModifierListOwner modifierListOwner) {
725 726 727 728 729 730
        //TODO report error
        return modifierListOwner.hasModifierProperty(PsiModifier.PUBLIC) ? Visibility.PUBLIC :
                                        (modifierListOwner.hasModifierProperty(PsiModifier.PRIVATE) ? Visibility.PRIVATE :
                                        (modifierListOwner.hasModifierProperty(PsiModifier.PROTECTED) ? Visibility.PROTECTED : Visibility.INTERNAL));
    }

731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755
    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);
    }
756
}