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.codegen;
018    
019    import com.intellij.openapi.util.Condition;
020    import com.intellij.openapi.util.io.FileUtil;
021    import com.intellij.openapi.vfs.VirtualFile;
022    import com.intellij.util.containers.ContainerUtil;
023    import com.intellij.util.containers.Stack;
024    import org.jetbrains.annotations.NotNull;
025    import org.jetbrains.annotations.Nullable;
026    import org.jetbrains.jet.codegen.binding.CalculatedClosure;
027    import org.jetbrains.jet.codegen.context.CodegenContext;
028    import org.jetbrains.jet.codegen.context.PackageContext;
029    import org.jetbrains.jet.codegen.signature.BothSignatureWriter;
030    import org.jetbrains.jet.codegen.signature.JvmMethodParameterKind;
031    import org.jetbrains.jet.codegen.signature.JvmMethodSignature;
032    import org.jetbrains.jet.codegen.state.JetTypeMapper;
033    import org.jetbrains.jet.lang.descriptors.*;
034    import org.jetbrains.jet.lang.descriptors.annotations.AnnotationDescriptor;
035    import org.jetbrains.jet.lang.descriptors.impl.SimpleFunctionDescriptorImpl;
036    import org.jetbrains.jet.lang.descriptors.impl.TypeParameterDescriptorImpl;
037    import org.jetbrains.jet.lang.resolve.DescriptorUtils;
038    import org.jetbrains.jet.lang.resolve.calls.CallResolverUtil;
039    import org.jetbrains.jet.lang.resolve.name.Name;
040    import org.jetbrains.jet.lang.types.JetType;
041    import org.jetbrains.jet.lang.types.TypeUtils;
042    import org.jetbrains.jet.lang.types.lang.KotlinBuiltIns;
043    
044    import java.util.*;
045    
046    import static org.jetbrains.jet.lang.descriptors.Modality.ABSTRACT;
047    import static org.jetbrains.jet.lang.resolve.java.AsmTypeConstants.OBJECT_TYPE;
048    
049    public class CodegenUtil {
050    
051        private CodegenUtil() {
052        }
053    
054        public static boolean isInterface(DeclarationDescriptor descriptor) {
055            if (descriptor instanceof ClassDescriptor) {
056                ClassKind kind = ((ClassDescriptor) descriptor).getKind();
057                return kind == ClassKind.TRAIT || kind == ClassKind.ANNOTATION_CLASS;
058            }
059            return false;
060        }
061    
062        public static boolean isInterface(JetType type) {
063            return isInterface(type.getConstructor().getDeclarationDescriptor());
064        }
065    
066        public static SimpleFunctionDescriptor createInvoke(FunctionDescriptor fd) {
067            int arity = fd.getValueParameters().size();
068            SimpleFunctionDescriptorImpl invokeDescriptor = new SimpleFunctionDescriptorImpl(
069                    fd.getExpectedThisObject() != null
070                    ? KotlinBuiltIns.getInstance().getExtensionFunction(arity) : KotlinBuiltIns.getInstance().getFunction(arity),
071                    Collections.<AnnotationDescriptor>emptyList(),
072                    Name.identifier("invoke"),
073                    CallableMemberDescriptor.Kind.DECLARATION);
074    
075            invokeDescriptor.initialize(DescriptorUtils.getReceiverParameterType(fd.getReceiverParameter()),
076                                        fd.getExpectedThisObject(),
077                                        Collections.<TypeParameterDescriptorImpl>emptyList(),
078                                        fd.getValueParameters(),
079                                        fd.getReturnType(),
080                                        Modality.FINAL,
081                                        Visibilities.PUBLIC
082            );
083            return invokeDescriptor;
084        }
085    
086        public static JvmMethodSignature erasedInvokeSignature(FunctionDescriptor fd) {
087            BothSignatureWriter signatureWriter = new BothSignatureWriter(BothSignatureWriter.Mode.METHOD, false);
088    
089            boolean isExtensionFunction = fd.getReceiverParameter() != null;
090            int paramCount = fd.getValueParameters().size();
091            if (isExtensionFunction) {
092                paramCount++;
093            }
094    
095            signatureWriter.writeParametersStart();
096    
097            for (int i = 0; i < paramCount; ++i) {
098                signatureWriter.writeParameterType(JvmMethodParameterKind.VALUE);
099                signatureWriter.writeAsmType(OBJECT_TYPE);
100                signatureWriter.writeParameterTypeEnd();
101            }
102    
103            signatureWriter.writeReturnType();
104            signatureWriter.writeAsmType(OBJECT_TYPE);
105            signatureWriter.writeReturnTypeEnd();
106    
107            return signatureWriter.makeJvmMethodSignature("invoke");
108        }
109    
110        public static boolean isConst(@NotNull CalculatedClosure closure) {
111            return closure.getCaptureThis() == null && closure.getCaptureReceiverType() == null && closure.getCaptureVariables().isEmpty();
112        }
113    
114        public static <T> T peekFromStack(Stack<T> stack) {
115            return stack.empty() ? null : stack.peek();
116        }
117    
118        public static JetType getSuperClass(ClassDescriptor classDescriptor) {
119            List<ClassDescriptor> superclassDescriptors = DescriptorUtils.getSuperclassDescriptors(classDescriptor);
120            for (ClassDescriptor descriptor : superclassDescriptors) {
121                if (descriptor.getKind() != ClassKind.TRAIT) {
122                    return descriptor.getDefaultType();
123                }
124            }
125            return KotlinBuiltIns.getInstance().getAnyType();
126        }
127    
128        @NotNull
129        public static <T extends CallableMemberDescriptor> T unwrapFakeOverride(T member) {
130            while (member.getKind() == CallableMemberDescriptor.Kind.FAKE_OVERRIDE) {
131                //noinspection unchecked
132                member = (T) member.getOverriddenDescriptors().iterator().next();
133            }
134            return member;
135        }
136    
137        @Nullable
138        public static FunctionDescriptor getDeclaredFunctionByRawSignature(
139                @NotNull ClassDescriptor owner,
140                @NotNull Name name,
141                @NotNull ClassifierDescriptor returnedClassifier,
142                @NotNull ClassifierDescriptor... valueParameterClassifiers
143        ) {
144            Collection<FunctionDescriptor> functions = owner.getDefaultType().getMemberScope().getFunctions(name);
145            for (FunctionDescriptor function : functions) {
146                if (!CallResolverUtil.isOrOverridesSynthesized(function)
147                    && function.getTypeParameters().isEmpty()
148                    && valueParameterClassesMatch(function.getValueParameters(), Arrays.asList(valueParameterClassifiers))
149                    && rawTypeMatches(function.getReturnType(), returnedClassifier)) {
150                    return function;
151                }
152            }
153            return null;
154        }
155    
156        private static boolean valueParameterClassesMatch(
157                @NotNull List<ValueParameterDescriptor> parameters,
158                @NotNull List<ClassifierDescriptor> classifiers) {
159            if (parameters.size() != classifiers.size()) return false;
160            for (int i = 0; i < parameters.size(); i++) {
161                ValueParameterDescriptor parameterDescriptor = parameters.get(i);
162                ClassifierDescriptor classDescriptor = classifiers.get(i);
163                if (!rawTypeMatches(parameterDescriptor.getType(), classDescriptor)) {
164                    return false;
165                }
166            }
167            return true;
168        }
169    
170        private static boolean rawTypeMatches(JetType type, ClassifierDescriptor classifier) {
171            return type.getConstructor().getDeclarationDescriptor().getOriginal() == classifier.getOriginal();
172        }
173    
174        public static boolean isCallInsideSameClassAsDeclared(CallableMemberDescriptor declarationDescriptor, CodegenContext context) {
175            boolean isFakeOverride = declarationDescriptor.getKind() == CallableMemberDescriptor.Kind.FAKE_OVERRIDE;
176            boolean isDelegate = declarationDescriptor.getKind() == CallableMemberDescriptor.Kind.DELEGATION;
177    
178            DeclarationDescriptor containingDeclaration = declarationDescriptor.getContainingDeclaration();
179            containingDeclaration = containingDeclaration.getOriginal();
180    
181            return !isFakeOverride && !isDelegate &&
182                   (((context.hasThisDescriptor() && containingDeclaration == context.getThisDescriptor()) ||
183                     (context.getParentContext() instanceof PackageContext && context.getParentContext().getContextDescriptor() == containingDeclaration))
184                    && context.getContextKind() != OwnerKind.TRAIT_IMPL);
185        }
186    
187        public static boolean isCallInsideSameModuleAsDeclared(CallableMemberDescriptor declarationDescriptor, CodegenContext context) {
188            if (context == CodegenContext.STATIC) {
189                return true;
190            }
191            DeclarationDescriptor contextDescriptor = context.getContextDescriptor();
192            return DescriptorUtils.areInSameModule(declarationDescriptor, contextDescriptor);
193        }
194    
195        public static boolean hasAbstractMembers(@NotNull ClassDescriptor classDescriptor) {
196            return ContainerUtil.exists(classDescriptor.getDefaultType().getMemberScope().getAllDescriptors(),
197                                        new Condition<DeclarationDescriptor>() {
198                                            @Override
199                                            public boolean value(DeclarationDescriptor declaration) {
200                                                if (!(declaration instanceof MemberDescriptor)) {
201                                                    return false;
202                                                }
203                                                return ((MemberDescriptor) declaration).getModality() == ABSTRACT;
204                                            }
205                                        });
206        }
207    
208        /**
209         * A work-around of the generic nullability problem in the type checker
210         * @return true if a value of this type can be null
211         */
212        public static boolean isNullableType(@NotNull JetType type) {
213            if (type.isNullable()) {
214                return true;
215            }
216            if (type.getConstructor().getDeclarationDescriptor() instanceof TypeParameterDescriptor) {
217                return TypeUtils.hasNullableSuperType(type);
218            }
219            return false;
220        }
221    
222        public static boolean couldUseDirectAccessToProperty(@NotNull PropertyDescriptor propertyDescriptor, boolean forGetter, boolean isInsideClass, boolean isDelegated) {
223            PropertyAccessorDescriptor accessorDescriptor = forGetter ? propertyDescriptor.getGetter() : propertyDescriptor.getSetter();
224            boolean isExtensionProperty = propertyDescriptor.getReceiverParameter() != null;
225            boolean specialTypeProperty = isDelegated ||
226                                          isExtensionProperty ||
227                                          DescriptorUtils.isClassObject(propertyDescriptor.getContainingDeclaration()) ||
228                                          JetTypeMapper.isAccessor(propertyDescriptor);
229            return isInsideClass &&
230                   !specialTypeProperty &&
231                   (accessorDescriptor == null ||
232                    accessorDescriptor.isDefault() &&
233                    (!isExternallyAccessible(propertyDescriptor) || accessorDescriptor.getModality() == Modality.FINAL));
234        }
235    
236        private static boolean isExternallyAccessible(@NotNull PropertyDescriptor propertyDescriptor) {
237            return propertyDescriptor.getVisibility() != Visibilities.PRIVATE ||
238                   DescriptorUtils.isClassObject(propertyDescriptor.getContainingDeclaration()) ||
239                   DescriptorUtils.isTopLevelDeclaration(propertyDescriptor);
240        }
241    
242        @NotNull
243        public static ImplementationBodyCodegen getParentBodyCodegen(@Nullable MemberCodegen classBodyCodegen) {
244            assert classBodyCodegen != null &&
245                   classBodyCodegen
246                           .getParentCodegen() instanceof ImplementationBodyCodegen : "Class object should have appropriate parent BodyCodegen";
247    
248            return ((ImplementationBodyCodegen) classBodyCodegen.getParentCodegen());
249        }
250    
251        static int getPathHashCode(@NotNull VirtualFile file) {
252            // Conversion to system-dependent name seems to be unnecessary, but it's hard to check now:
253            // it was introduced when fixing KT-2839, which appeared again (KT-3639).
254            // If you try to remove it, run tests on Windows.
255            return FileUtil.toSystemDependentName(file.getPath()).hashCode();
256        }
257    
258        @Nullable
259        public static ClassDescriptor getExpectedThisObjectForConstructorCall(
260                @NotNull ConstructorDescriptor descriptor,
261                @Nullable CalculatedClosure closure
262        ) {
263            //for compilation against sources
264            if (closure != null) {
265                return closure.getCaptureThis();
266            }
267    
268            //for compilation against binaries
269            //TODO: It's best to use this code also for compilation against sources
270            // but sometimes structures that have expectedThisObject (bug?) mapped to static classes
271            ReceiverParameterDescriptor expectedThisObject = descriptor.getExpectedThisObject();
272            if (expectedThisObject != null) {
273                ClassDescriptor expectedThisClass = (ClassDescriptor) expectedThisObject.getContainingDeclaration();
274                if (!expectedThisClass.getKind().isSingleton()) {
275                    return expectedThisClass;
276                }
277            }
278    
279            return null;
280        }
281    }