001    /*
002     * Copyright 2010-2013 JetBrains s.r.o.
003     *
004     * Licensed under the Apache License, Version 2.0 (the "License");
005     * you may not use this file except in compliance with the License.
006     * You may obtain a copy of the License at
007     *
008     * http://www.apache.org/licenses/LICENSE-2.0
009     *
010     * Unless required by applicable law or agreed to in writing, software
011     * distributed under the License is distributed on an "AS IS" BASIS,
012     * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
013     * See the License for the specific language governing permissions and
014     * limitations under the License.
015     */
016    
017    package org.jetbrains.jet.lang.types;
018    
019    import kotlin.Function1;
020    import org.jetbrains.annotations.NotNull;
021    import org.jetbrains.annotations.Nullable;
022    import org.jetbrains.jet.lang.PlatformToKotlinClassMap;
023    import org.jetbrains.jet.lang.descriptors.*;
024    import org.jetbrains.jet.lang.descriptors.annotations.Annotations;
025    import org.jetbrains.jet.lang.descriptors.impl.ClassDescriptorImpl;
026    import org.jetbrains.jet.lang.descriptors.impl.ConstructorDescriptorImpl;
027    import org.jetbrains.jet.lang.descriptors.impl.PropertyDescriptorImpl;
028    import org.jetbrains.jet.lang.descriptors.impl.TypeParameterDescriptorImpl;
029    import org.jetbrains.jet.lang.resolve.ImportPath;
030    import org.jetbrains.jet.lang.resolve.name.Name;
031    import org.jetbrains.jet.lang.resolve.scopes.JetScope;
032    import org.jetbrains.jet.lang.types.error.ErrorSimpleFunctionDescriptorImpl;
033    import org.jetbrains.jet.lang.types.lang.KotlinBuiltIns;
034    import org.jetbrains.jet.utils.Printer;
035    
036    import java.util.Collection;
037    import java.util.Collections;
038    import java.util.List;
039    import java.util.Set;
040    
041    public class ErrorUtils {
042    
043        private static final ModuleDescriptor ERROR_MODULE;
044        static {
045            ERROR_MODULE = new ModuleDescriptorImpl(
046                    Name.special("<ERROR MODULE>"),
047                    Collections.<ImportPath>emptyList(),
048                    PlatformToKotlinClassMap.EMPTY
049            );
050        }
051    
052        public static boolean containsErrorType(@NotNull FunctionDescriptor function) {
053            if (containsErrorType(function.getReturnType())) {
054                return true;
055            }
056            ReceiverParameterDescriptor receiverParameter = function.getReceiverParameter();
057            if (receiverParameter != null && containsErrorType(receiverParameter.getType())) {
058                return true;
059            }
060            for (ValueParameterDescriptor parameter : function.getValueParameters()) {
061                if (containsErrorType(parameter.getType())) {
062                    return true;
063                }
064            }
065            for (TypeParameterDescriptor parameter : function.getTypeParameters()) {
066                for (JetType upperBound : parameter.getUpperBounds()) {
067                    if (containsErrorType(upperBound)) {
068                        return true;
069                    }
070                }
071            }
072    
073            return false;
074        }
075    
076    
077        public static class ErrorScope implements JetScope {
078            private final String debugMessage;
079    
080            private ErrorScope(@NotNull String debugMessage) {
081                this.debugMessage = debugMessage;
082            }
083    
084            @Override
085            public ClassifierDescriptor getClassifier(@NotNull Name name) {
086                return createErrorClass(name.asString());
087            }
088    
089            @NotNull
090            @Override
091            public Set<VariableDescriptor> getProperties(@NotNull Name name) {
092                return ERROR_PROPERTY_GROUP;
093            }
094    
095            @Override
096            public VariableDescriptor getLocalVariable(@NotNull Name name) {
097                return ERROR_PROPERTY;
098            }
099    
100            @Override
101            public PackageViewDescriptor getPackage(@NotNull Name name) {
102                return null;
103            }
104    
105            @NotNull
106            @Override
107            public List<ReceiverParameterDescriptor> getImplicitReceiversHierarchy() {
108                return Collections.emptyList();
109            }
110    
111            @NotNull
112            @Override
113            public Set<FunctionDescriptor> getFunctions(@NotNull Name name) {
114                return Collections.<FunctionDescriptor>singleton(createErrorFunction(this));
115            }
116    
117            @NotNull
118            @Override
119            public DeclarationDescriptor getContainingDeclaration() {
120                return ERROR_MODULE;
121            }
122    
123            @NotNull
124            @Override
125            public Collection<DeclarationDescriptor> getDeclarationsByLabel(@NotNull Name labelName) {
126                return Collections.emptyList();
127            }
128    
129            @NotNull
130            @Override
131            public Collection<DeclarationDescriptor> getAllDescriptors() {
132                return Collections.emptyList();
133            }
134    
135            @NotNull
136            @Override
137            public Collection<DeclarationDescriptor> getOwnDeclaredDescriptors() {
138                return Collections.emptyList();
139            }
140    
141            @Override
142            public String toString() {
143                return "ErrorScope{" + debugMessage + '}';
144            }
145    
146            @Override
147            public void printScopeStructure(@NotNull Printer p) {
148                p.println(getClass().getSimpleName(), ": ", debugMessage);
149            }
150        }
151    
152        private static class ThrowingScope implements JetScope {
153            private final String debugMessage;
154    
155            private ThrowingScope(@NotNull String message) {
156                debugMessage = message;
157            }
158    
159            @Nullable
160            @Override
161            public ClassifierDescriptor getClassifier(@NotNull Name name) {
162                throw new IllegalStateException();
163            }
164    
165            @Nullable
166            @Override
167            public PackageViewDescriptor getPackage(@NotNull Name name) {
168                throw new IllegalStateException();
169            }
170    
171            @NotNull
172            @Override
173            public Collection<VariableDescriptor> getProperties(@NotNull Name name) {
174                throw new IllegalStateException();
175            }
176    
177            @Nullable
178            @Override
179            public VariableDescriptor getLocalVariable(@NotNull Name name) {
180                throw new IllegalStateException();
181            }
182    
183            @NotNull
184            @Override
185            public Collection<FunctionDescriptor> getFunctions(@NotNull Name name) {
186                throw new IllegalStateException();
187            }
188    
189            @NotNull
190            @Override
191            public DeclarationDescriptor getContainingDeclaration() {
192                return ERROR_MODULE;
193            }
194    
195            @NotNull
196            @Override
197            public Collection<DeclarationDescriptor> getDeclarationsByLabel(@NotNull Name labelName) {
198                throw new IllegalStateException();
199            }
200    
201            @NotNull
202            @Override
203            public Collection<DeclarationDescriptor> getAllDescriptors() {
204                throw new IllegalStateException();
205            }
206    
207            @NotNull
208            @Override
209            public List<ReceiverParameterDescriptor> getImplicitReceiversHierarchy() {
210                throw new IllegalStateException();
211            }
212    
213            @NotNull
214            @Override
215            public Collection<DeclarationDescriptor> getOwnDeclaredDescriptors() {
216                throw new IllegalStateException();
217            }
218    
219            @Override
220            public String toString() {
221                return "ThrowingScope{" + debugMessage + '}';
222            }
223    
224            @Override
225            public void printScopeStructure(@NotNull Printer p) {
226                p.println(getClass().getSimpleName(), ": ", debugMessage);
227            }
228        }
229    
230        private static final ErrorClassDescriptor ERROR_CLASS = new ErrorClassDescriptor(null);
231    
232        private static class ErrorClassDescriptor extends ClassDescriptorImpl {
233            public ErrorClassDescriptor(@Nullable String name) {
234                super(getErrorModule(), Name.special(name == null ? "<ERROR CLASS>" : "<ERROR CLASS: " + name + ">"),
235                      Modality.OPEN, Collections.<JetType>emptyList());
236    
237                ConstructorDescriptorImpl errorConstructor = ConstructorDescriptorImpl.create(this, Annotations.EMPTY, true);
238                errorConstructor.initialize(Collections.<TypeParameterDescriptor>emptyList(), Collections.<ValueParameterDescriptor>emptyList(),
239                                            Visibilities.INTERNAL, false);
240                JetScope memberScope = createErrorScope(getName().asString());
241                errorConstructor.setReturnType(
242                        new ErrorTypeImpl(
243                                TypeConstructorImpl.createForClass(
244                                        this, Annotations.EMPTY, false,
245                                        getName().asString(),
246                                        Collections.<TypeParameterDescriptorImpl>emptyList(),
247                                        Collections.singleton(KotlinBuiltIns.getInstance().getAnyType())
248                                ),
249                                memberScope
250                        )
251                );
252    
253                initialize(memberScope, Collections.<ConstructorDescriptor>singleton(errorConstructor), errorConstructor);
254            }
255    
256            @NotNull
257            @Override
258            public ClassDescriptor substitute(@NotNull TypeSubstitutor substitutor) {
259                return this;
260            }
261    
262            @Override
263            public String toString() {
264                return getName().asString();
265            }
266    
267            @NotNull
268            @Override
269            public JetScope getMemberScope(@NotNull List<? extends TypeProjection> typeArguments) {
270                return createErrorScope("Error scope for class " + getName() + " with arguments: " + typeArguments);
271            }
272        }
273    
274        @NotNull
275        public static ClassDescriptor createErrorClass(@NotNull String debugMessage) {
276            return new ErrorClassDescriptor(debugMessage);
277        }
278    
279        @NotNull
280        public static JetScope createErrorScope(@NotNull String debugMessage) {
281            return createErrorScope(debugMessage, false);
282        }
283    
284        @NotNull
285        public static JetScope createErrorScope(@NotNull String debugMessage, boolean throwExceptions) {
286            if (throwExceptions) {
287                return new ThrowingScope(debugMessage);
288            }
289            return new ErrorScope(debugMessage);
290        }
291    
292        private static final JetType ERROR_PROPERTY_TYPE = createErrorType("<ERROR PROPERTY TYPE>");
293        private static final VariableDescriptor ERROR_PROPERTY = createErrorProperty();
294    
295        private static final Set<VariableDescriptor> ERROR_PROPERTY_GROUP = Collections.singleton(ERROR_PROPERTY);
296    
297        @NotNull
298        private static PropertyDescriptorImpl createErrorProperty() {
299            PropertyDescriptorImpl descriptor = PropertyDescriptorImpl.create(
300                    ERROR_CLASS,
301                    Annotations.EMPTY,
302                    Modality.OPEN,
303                    Visibilities.INTERNAL,
304                    true,
305                    Name.special("<ERROR PROPERTY>"),
306                    CallableMemberDescriptor.Kind.DECLARATION
307            );
308            descriptor.setType(ERROR_PROPERTY_TYPE,
309                               Collections.<TypeParameterDescriptor>emptyList(),
310                               ReceiverParameterDescriptor.NO_RECEIVER_PARAMETER,
311                               (JetType) null
312            );
313    
314            return descriptor;
315        }
316    
317        @NotNull
318        private static SimpleFunctionDescriptor createErrorFunction(@NotNull ErrorScope ownerScope) {
319            ErrorSimpleFunctionDescriptorImpl function = new ErrorSimpleFunctionDescriptorImpl(ERROR_CLASS, ownerScope);
320            function.initialize(
321                    null,
322                    ReceiverParameterDescriptor.NO_RECEIVER_PARAMETER,
323                    Collections.<TypeParameterDescriptorImpl>emptyList(), // TODO
324                    Collections.<ValueParameterDescriptor>emptyList(), // TODO
325                    createErrorType("<ERROR FUNCTION RETURN TYPE>"),
326                    Modality.OPEN,
327                    Visibilities.INTERNAL
328            );
329            return function;
330        }
331    
332        @NotNull
333        public static JetType createErrorType(@NotNull String debugMessage) {
334            return new ErrorTypeImpl(createErrorTypeConstructor(debugMessage), createErrorScope(debugMessage));
335        }
336    
337        @NotNull
338        public static JetType createErrorTypeWithCustomDebugName(@NotNull String debugName) {
339            return new ErrorTypeImpl(createErrorTypeConstructorWithCustomDebugName(debugName), createErrorScope(debugName));
340        }
341    
342        @NotNull
343        public static TypeConstructor createErrorTypeConstructor(@NotNull String debugMessage) {
344            return createErrorTypeConstructorWithCustomDebugName("[ERROR : " + debugMessage + "]");
345        }
346    
347        @NotNull
348        private static TypeConstructor createErrorTypeConstructorWithCustomDebugName(@NotNull String debugName) {
349            return TypeConstructorImpl.createForClass(ERROR_CLASS, Annotations.EMPTY, false, debugName,
350                                    Collections.<TypeParameterDescriptorImpl>emptyList(),
351                                    Collections.singleton(KotlinBuiltIns.getInstance().getAnyType()));
352        }
353    
354        public static boolean containsErrorType(@Nullable JetType type) {
355            if (type == null) return false;
356            if (type instanceof PackageType) return false;
357            if (type.isError()) return true;
358            for (TypeProjection projection : type.getArguments()) {
359                if (containsErrorType(projection.getType())) return true;
360            }
361            return false;
362        }
363    
364        public static boolean isError(@NotNull DeclarationDescriptor candidate) {
365            return isErrorClass(candidate) || isErrorClass(candidate.getContainingDeclaration()) || candidate == ERROR_MODULE;
366        }
367    
368        private static boolean isErrorClass(@Nullable DeclarationDescriptor candidate) {
369            return candidate instanceof ErrorClassDescriptor;
370        }
371    
372        @NotNull
373        public static TypeParameterDescriptor createErrorTypeParameter(int index, @NotNull String debugMessage) {
374            return TypeParameterDescriptorImpl.createWithDefaultBound(
375                    ERROR_CLASS,
376                    Annotations.EMPTY,
377                    false,
378                    Variance.INVARIANT,
379                    Name.special("<ERROR: " + debugMessage + ">"),
380                    index
381            );
382        }
383    
384        private static class ErrorTypeImpl implements JetType {
385            private final TypeConstructor constructor;
386            private final JetScope memberScope;
387    
388            private ErrorTypeImpl(@NotNull TypeConstructor constructor, @NotNull JetScope memberScope) {
389                this.constructor = constructor;
390                this.memberScope = memberScope;
391            }
392    
393            @NotNull
394            @Override
395            public TypeConstructor getConstructor() {
396                return constructor;
397            }
398    
399            @NotNull
400            @Override
401            public List<TypeProjection> getArguments() {
402                return Collections.emptyList();
403            }
404    
405            @Override
406            public boolean isNullable() {
407                return false;
408            }
409    
410            @NotNull
411            @Override
412            public JetScope getMemberScope() {
413                return memberScope;
414            }
415    
416            @Override
417            public boolean isError() {
418                return true;
419            }
420    
421            @NotNull
422            @Override
423            public Annotations getAnnotations() {
424                return Annotations.EMPTY;
425            }
426    
427            @Override
428            public String toString() {
429                return constructor.toString();
430            }
431        }
432    
433        @NotNull
434        public static ModuleDescriptor getErrorModule() {
435            return ERROR_MODULE;
436        }
437    
438        public static boolean isUninferredParameter(@Nullable JetType type) {
439            return type instanceof UninferredParameterType;
440        }
441    
442        public static boolean containsUninferredParameter(@Nullable JetType type) {
443            return TypeUtils.containsSpecialType(type, new Function1<JetType, Boolean>() {
444                @Override
445                public Boolean invoke(JetType argumentType) {
446                    return isUninferredParameter(argumentType);
447                }
448            });
449        }
450    
451        public static UninferredParameterType createUninferredParameterType(@NotNull TypeParameterDescriptor typeParameterDescriptor) {
452            return new UninferredParameterType(typeParameterDescriptor);
453        }
454    
455        public static class UninferredParameterType extends ErrorTypeImpl {
456            private final TypeParameterDescriptor typeParameterDescriptor;
457    
458            private UninferredParameterType(
459                    @NotNull TypeParameterDescriptor descriptor
460            ) {
461                super(createErrorTypeConstructorWithCustomDebugName("CANT_INFER_TYPE_PARAMETER: " + descriptor.getName()),
462                      createErrorScope("Scope for error type for not inferred parameter: " + descriptor.getName()));
463                typeParameterDescriptor = descriptor;
464            }
465    
466            @NotNull
467            public TypeParameterDescriptor getTypeParameterDescriptor() {
468                return typeParameterDescriptor;
469            }
470        }
471    
472        private ErrorUtils() {}
473    }