001    /*
002     * Copyright 2010-2015 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.kotlin.codegen;
018    
019    import com.google.common.collect.Lists;
020    import com.intellij.util.ArrayUtil;
021    import kotlin.Unit;
022    import kotlin.collections.CollectionsKt;
023    import kotlin.jvm.functions.Function1;
024    import org.jetbrains.annotations.NotNull;
025    import org.jetbrains.annotations.Nullable;
026    import org.jetbrains.kotlin.codegen.binding.CalculatedClosure;
027    import org.jetbrains.kotlin.codegen.context.ClosureContext;
028    import org.jetbrains.kotlin.codegen.inline.InlineCodegenUtil;
029    import org.jetbrains.kotlin.codegen.serialization.JvmSerializerExtension;
030    import org.jetbrains.kotlin.codegen.signature.BothSignatureWriter;
031    import org.jetbrains.kotlin.codegen.signature.JvmSignatureWriter;
032    import org.jetbrains.kotlin.codegen.state.GenerationState;
033    import org.jetbrains.kotlin.codegen.state.KotlinTypeMapper;
034    import org.jetbrains.kotlin.descriptors.*;
035    import org.jetbrains.kotlin.descriptors.impl.SimpleFunctionDescriptorImpl;
036    import org.jetbrains.kotlin.incremental.components.NoLookupLocation;
037    import org.jetbrains.kotlin.load.java.JvmAbi;
038    import org.jetbrains.kotlin.load.kotlin.header.KotlinClassHeader;
039    import org.jetbrains.kotlin.psi.KtElement;
040    import org.jetbrains.kotlin.resolve.BindingContext;
041    import org.jetbrains.kotlin.resolve.DescriptorUtils;
042    import org.jetbrains.kotlin.resolve.descriptorUtil.DescriptorUtilsKt;
043    import org.jetbrains.kotlin.resolve.jvm.diagnostics.JvmDeclarationOriginKt;
044    import org.jetbrains.kotlin.resolve.scopes.MemberScope;
045    import org.jetbrains.kotlin.serialization.DescriptorSerializer;
046    import org.jetbrains.kotlin.serialization.ProtoBuf;
047    import org.jetbrains.kotlin.types.KotlinType;
048    import org.jetbrains.kotlin.types.expressions.ExpressionTypingUtils;
049    import org.jetbrains.kotlin.util.OperatorNameConventions;
050    import org.jetbrains.org.objectweb.asm.AnnotationVisitor;
051    import org.jetbrains.org.objectweb.asm.MethodVisitor;
052    import org.jetbrains.org.objectweb.asm.Type;
053    import org.jetbrains.org.objectweb.asm.commons.InstructionAdapter;
054    import org.jetbrains.org.objectweb.asm.commons.Method;
055    
056    import java.util.ArrayList;
057    import java.util.Collections;
058    import java.util.List;
059    
060    import static org.jetbrains.kotlin.codegen.AsmUtil.*;
061    import static org.jetbrains.kotlin.codegen.ExpressionCodegen.generateClassLiteralReference;
062    import static org.jetbrains.kotlin.codegen.JvmCodegenUtil.isConst;
063    import static org.jetbrains.kotlin.codegen.binding.CodegenBinding.CLOSURE;
064    import static org.jetbrains.kotlin.codegen.binding.CodegenBinding.asmTypeForAnonymousClass;
065    import static org.jetbrains.kotlin.resolve.jvm.AsmTypes.*;
066    import static org.jetbrains.kotlin.resolve.jvm.diagnostics.JvmDeclarationOrigin.NO_ORIGIN;
067    import static org.jetbrains.org.objectweb.asm.Opcodes.*;
068    
069    public class ClosureCodegen extends MemberCodegen<KtElement> {
070        private final FunctionDescriptor funDescriptor;
071        private final ClassDescriptor classDescriptor;
072        private final SamType samType;
073        private final KotlinType superClassType;
074        private final List<KotlinType> superInterfaceTypes;
075        private final FunctionDescriptor functionReferenceTarget;
076        private final FunctionGenerationStrategy strategy;
077        private final CalculatedClosure closure;
078        private final Type asmType;
079        private final int visibilityFlag;
080    
081        private Method constructor;
082        private Type superClassAsmType;
083    
084        public ClosureCodegen(
085                @NotNull GenerationState state,
086                @NotNull KtElement element,
087                @Nullable SamType samType,
088                @NotNull ClosureContext context,
089                @Nullable FunctionDescriptor functionReferenceTarget,
090                @NotNull FunctionGenerationStrategy strategy,
091                @NotNull MemberCodegen<?> parentCodegen,
092                @NotNull ClassBuilder classBuilder
093        ) {
094            super(state, parentCodegen, context, element, classBuilder);
095    
096            this.funDescriptor = context.getFunctionDescriptor();
097            this.classDescriptor = context.getContextDescriptor();
098            this.samType = samType;
099            this.functionReferenceTarget = functionReferenceTarget;
100            this.strategy = strategy;
101    
102            if (samType == null) {
103                this.superInterfaceTypes = new ArrayList<KotlinType>();
104    
105                KotlinType superClassType = null;
106                for (KotlinType supertype : classDescriptor.getTypeConstructor().getSupertypes()) {
107                    ClassifierDescriptor classifier = supertype.getConstructor().getDeclarationDescriptor();
108                    if (DescriptorUtils.isInterface(classifier)) {
109                        superInterfaceTypes.add(supertype);
110                    }
111                    else {
112                        assert superClassType == null : "Closure class can't have more than one superclass: " + funDescriptor;
113                        superClassType = supertype;
114                    }
115                }
116                assert superClassType != null : "Closure class should have a superclass: " + funDescriptor;
117    
118                this.superClassType = superClassType;
119            }
120            else {
121                this.superInterfaceTypes = Collections.singletonList(samType.getType());
122                this.superClassType = DescriptorUtilsKt.getBuiltIns(funDescriptor).getAnyType();
123            }
124    
125            this.closure = bindingContext.get(CLOSURE, classDescriptor);
126            assert closure != null : "Closure must be calculated for class: " + classDescriptor;
127    
128            this.asmType = typeMapper.mapClass(classDescriptor);
129    
130            visibilityFlag = AsmUtil.getVisibilityAccessFlagForClass(classDescriptor);
131        }
132    
133        @Override
134        protected void generateDeclaration() {
135            JvmSignatureWriter sw = new BothSignatureWriter(BothSignatureWriter.Mode.CLASS);
136            if (samType != null) {
137                typeMapper.writeFormalTypeParameters(samType.getType().getConstructor().getParameters(), sw);
138            }
139            sw.writeSuperclass();
140            superClassAsmType = typeMapper.mapSupertype(superClassType, sw);
141            sw.writeSuperclassEnd();
142            String[] superInterfaceAsmTypes = new String[superInterfaceTypes.size()];
143            for (int i = 0; i < superInterfaceTypes.size(); i++) {
144                KotlinType superInterfaceType = superInterfaceTypes.get(i);
145                sw.writeInterface();
146                superInterfaceAsmTypes[i] = typeMapper.mapSupertype(superInterfaceType, sw).getInternalName();
147                sw.writeInterfaceEnd();
148            }
149    
150            v.defineClass(element,
151                          V1_6,
152                          ACC_FINAL | ACC_SUPER | visibilityFlag,
153                          asmType.getInternalName(),
154                          sw.makeJavaGenericSignature(),
155                          superClassAsmType.getInternalName(),
156                          superInterfaceAsmTypes
157            );
158    
159            InlineCodegenUtil.initDefaultSourceMappingIfNeeded(context, this, state);
160    
161            v.visitSource(element.getContainingFile().getName(), null);
162        }
163    
164        @Nullable
165        @Override
166        protected ClassDescriptor classForInnerClassRecord() {
167            return JvmCodegenUtil.isArgumentWhichWillBeInlined(bindingContext, funDescriptor) ? null : classDescriptor;
168        }
169    
170        @Override
171        protected void generateBody() {
172            FunctionDescriptor erasedInterfaceFunction;
173            if (samType == null) {
174                erasedInterfaceFunction = getErasedInvokeFunction(funDescriptor);
175            }
176            else {
177                erasedInterfaceFunction = samType.getAbstractMethod().getOriginal();
178            }
179    
180            generateBridge(
181                    typeMapper.mapAsmMethod(erasedInterfaceFunction),
182                    typeMapper.mapAsmMethod(funDescriptor)
183            );
184    
185            functionCodegen.generateMethod(JvmDeclarationOriginKt.OtherOrigin(element, funDescriptor), funDescriptor, strategy);
186    
187            //TODO: rewrite cause ugly hack
188            if (samType != null) {
189                SimpleFunctionDescriptorImpl descriptorForBridges = SimpleFunctionDescriptorImpl
190                        .create(funDescriptor.getContainingDeclaration(), funDescriptor.getAnnotations(),
191                                erasedInterfaceFunction.getName(),
192                                CallableMemberDescriptor.Kind.DECLARATION, funDescriptor.getSource());
193    
194                descriptorForBridges
195                        .initialize(null, erasedInterfaceFunction.getDispatchReceiverParameter(), erasedInterfaceFunction.getTypeParameters(),
196                                    erasedInterfaceFunction.getValueParameters(), erasedInterfaceFunction.getReturnType(),
197                                    Modality.OPEN, erasedInterfaceFunction.getVisibility());
198    
199                DescriptorUtilsKt.setSingleOverridden(descriptorForBridges, erasedInterfaceFunction);
200                functionCodegen.generateBridges(descriptorForBridges);
201            }
202    
203            if (functionReferenceTarget != null) {
204                generateFunctionReferenceMethods(functionReferenceTarget);
205            }
206    
207            functionCodegen.generateDefaultIfNeeded(
208                    context.intoFunction(funDescriptor), funDescriptor, context.getContextKind(), DefaultParameterValueLoader.DEFAULT, null
209            );
210    
211            this.constructor = generateConstructor();
212    
213            if (isConst(closure)) {
214                generateConstInstance(asmType, asmType);
215            }
216    
217            genClosureFields(closure, v, typeMapper);
218        }
219    
220        @Override
221        protected void generateKotlinMetadataAnnotation() {
222            final DescriptorSerializer serializer =
223                    DescriptorSerializer.createForLambda(new JvmSerializerExtension(v.getSerializationBindings(), state));
224    
225            final ProtoBuf.Function functionProto = serializer.functionProto(funDescriptor).build();
226    
227            WriteAnnotationUtilKt.writeKotlinMetadata(v, KotlinClassHeader.Kind.SYNTHETIC_CLASS, new Function1<AnnotationVisitor, Unit>() {
228                @Override
229                public Unit invoke(AnnotationVisitor av) {
230                    writeAnnotationData(av, serializer, functionProto);
231                    return Unit.INSTANCE;
232                }
233            });
234        }
235    
236        @Override
237        protected void done() {
238            writeOuterClassAndEnclosingMethod();
239            super.done();
240        }
241    
242        @NotNull
243        public StackValue putInstanceOnStack(@NotNull final ExpressionCodegen codegen) {
244            return StackValue.operation(
245                    functionReferenceTarget != null ? K_FUNCTION : asmType,
246                    new Function1<InstructionAdapter, Unit>() {
247                        @Override
248                        public Unit invoke(InstructionAdapter v) {
249                            if (isConst(closure)) {
250                                v.getstatic(asmType.getInternalName(), JvmAbi.INSTANCE_FIELD, asmType.getDescriptor());
251                            }
252                            else {
253                                v.anew(asmType);
254                                v.dup();
255    
256                                codegen.pushClosureOnStack(classDescriptor, true, codegen.defaultCallGenerator);
257                                v.invokespecial(asmType.getInternalName(), "<init>", constructor.getDescriptor(), false);
258                            }
259    
260                            return Unit.INSTANCE;
261                        }
262                    }
263            );
264        }
265    
266        private void generateBridge(@NotNull Method bridge, @NotNull Method delegate) {
267            if (bridge.equals(delegate)) return;
268    
269            MethodVisitor mv =
270                    v.newMethod(JvmDeclarationOriginKt.OtherOrigin(element, funDescriptor), ACC_PUBLIC | ACC_BRIDGE | ACC_SYNTHETIC,
271                                bridge.getName(), bridge.getDescriptor(), null, ArrayUtil.EMPTY_STRING_ARRAY);
272    
273            if (state.getClassBuilderMode() != ClassBuilderMode.FULL) return;
274    
275            mv.visitCode();
276    
277            InstructionAdapter iv = new InstructionAdapter(mv);
278            MemberCodegen.markLineNumberForDescriptor(DescriptorUtils.getParentOfType(funDescriptor, ClassDescriptor.class), iv);
279    
280            iv.load(0, asmType);
281    
282            Type[] myParameterTypes = bridge.getArgumentTypes();
283    
284            List<ParameterDescriptor> calleeParameters = CollectionsKt.plus(
285                    org.jetbrains.kotlin.utils.CollectionsKt.<ParameterDescriptor>singletonOrEmptyList(funDescriptor.getExtensionReceiverParameter()),
286                    funDescriptor.getValueParameters()
287            );
288    
289            int slot = 1;
290            for (int i = 0; i < calleeParameters.size(); i++) {
291                Type type = myParameterTypes[i];
292                StackValue.local(slot, type).put(typeMapper.mapType(calleeParameters.get(i)), iv);
293                slot += type.getSize();
294            }
295    
296            iv.invokevirtual(asmType.getInternalName(), delegate.getName(), delegate.getDescriptor(), false);
297            StackValue.onStack(delegate.getReturnType()).put(bridge.getReturnType(), iv);
298    
299            iv.areturn(bridge.getReturnType());
300    
301            FunctionCodegen.endVisit(mv, "bridge", element);
302        }
303    
304        // TODO: ImplementationBodyCodegen.markLineNumberForSyntheticFunction?
305        private void generateFunctionReferenceMethods(@NotNull FunctionDescriptor descriptor) {
306            int flags = ACC_PUBLIC | ACC_FINAL;
307            boolean generateBody = state.getClassBuilderMode() == ClassBuilderMode.FULL;
308    
309            {
310                MethodVisitor mv =
311                        v.newMethod(NO_ORIGIN, flags, "getOwner", Type.getMethodDescriptor(K_DECLARATION_CONTAINER_TYPE), null, null);
312                if (generateBody) {
313                    mv.visitCode();
314                    InstructionAdapter iv = new InstructionAdapter(mv);
315                    generateCallableReferenceDeclarationContainer(iv, descriptor, state);
316                    iv.areturn(K_DECLARATION_CONTAINER_TYPE);
317                    FunctionCodegen.endVisit(iv, "function reference getOwner", element);
318                }
319            }
320    
321            {
322                MethodVisitor mv =
323                        v.newMethod(NO_ORIGIN, flags, "getName", Type.getMethodDescriptor(JAVA_STRING_TYPE), null, null);
324                if (generateBody) {
325                    mv.visitCode();
326                    InstructionAdapter iv = new InstructionAdapter(mv);
327                    iv.aconst(descriptor.getName().asString());
328                    iv.areturn(JAVA_STRING_TYPE);
329                    FunctionCodegen.endVisit(iv, "function reference getName", element);
330                }
331            }
332    
333            {
334                MethodVisitor mv = v.newMethod(NO_ORIGIN, flags, "getSignature", Type.getMethodDescriptor(JAVA_STRING_TYPE), null, null);
335                if (generateBody) {
336                    mv.visitCode();
337                    InstructionAdapter iv = new InstructionAdapter(mv);
338                    Method method = typeMapper.mapAsmMethod(descriptor.getOriginal());
339                    iv.aconst(method.getName() + method.getDescriptor());
340                    iv.areturn(JAVA_STRING_TYPE);
341                    FunctionCodegen.endVisit(iv, "function reference getSignature", element);
342                }
343            }
344        }
345    
346        public static void generateCallableReferenceDeclarationContainer(
347                @NotNull InstructionAdapter iv,
348                @NotNull CallableDescriptor descriptor,
349                @NotNull GenerationState state
350        ) {
351            DeclarationDescriptor container = descriptor.getContainingDeclaration();
352            if (container instanceof ClassDescriptor) {
353                // TODO: getDefaultType() here is wrong and won't work for arrays
354                StackValue value = generateClassLiteralReference(state.getTypeMapper(), ((ClassDescriptor) container).getDefaultType());
355                value.put(K_CLASS_TYPE, iv);
356            }
357            else if (container instanceof PackageFragmentDescriptor) {
358                iv.aconst(state.getTypeMapper().mapOwner(descriptor));
359                iv.aconst(state.getModuleName());
360                iv.invokestatic(REFLECTION, "getOrCreateKotlinPackage",
361                                Type.getMethodDescriptor(K_DECLARATION_CONTAINER_TYPE, getType(Class.class), getType(String.class)), false);
362            }
363            else {
364                iv.aconst(null);
365            }
366        }
367    
368        @NotNull
369        private Method generateConstructor() {
370            List<FieldInfo> args = calculateConstructorParameters(typeMapper, closure, asmType);
371    
372            Type[] argTypes = fieldListToTypeArray(args);
373    
374            Method constructor = new Method("<init>", Type.VOID_TYPE, argTypes);
375            MethodVisitor mv = v.newMethod(JvmDeclarationOriginKt.OtherOrigin(element, funDescriptor), visibilityFlag, "<init>", constructor.getDescriptor(), null,
376                                           ArrayUtil.EMPTY_STRING_ARRAY);
377            if (state.getClassBuilderMode() == ClassBuilderMode.FULL) {
378                mv.visitCode();
379                InstructionAdapter iv = new InstructionAdapter(mv);
380    
381                int k = 1;
382                for (FieldInfo fieldInfo : args) {
383                    k = genAssignInstanceFieldFromParam(fieldInfo, k, iv);
384                }
385    
386                iv.load(0, superClassAsmType);
387    
388                if (superClassAsmType.equals(LAMBDA) || superClassAsmType.equals(FUNCTION_REFERENCE)) {
389                    int arity = funDescriptor.getValueParameters().size();
390                    if (funDescriptor.getExtensionReceiverParameter() != null) arity++;
391                    if (funDescriptor.getDispatchReceiverParameter() != null) arity++;
392                    iv.iconst(arity);
393                    iv.invokespecial(superClassAsmType.getInternalName(), "<init>", "(I)V", false);
394                }
395                else {
396                    iv.invokespecial(superClassAsmType.getInternalName(), "<init>", "()V", false);
397                }
398    
399                iv.visitInsn(RETURN);
400    
401                FunctionCodegen.endVisit(iv, "constructor", element);
402            }
403            return constructor;
404        }
405    
406        @NotNull
407        public static List<FieldInfo> calculateConstructorParameters(
408                @NotNull KotlinTypeMapper typeMapper,
409                @NotNull CalculatedClosure closure,
410                @NotNull Type ownerType
411        ) {
412            BindingContext bindingContext = typeMapper.getBindingContext();
413            List<FieldInfo> args = Lists.newArrayList();
414            ClassDescriptor captureThis = closure.getCaptureThis();
415            if (captureThis != null) {
416                Type type = typeMapper.mapType(captureThis);
417                args.add(FieldInfo.createForHiddenField(ownerType, type, CAPTURED_THIS_FIELD));
418            }
419            KotlinType captureReceiverType = closure.getCaptureReceiverType();
420            if (captureReceiverType != null) {
421                args.add(FieldInfo.createForHiddenField(ownerType, typeMapper.mapType(captureReceiverType), CAPTURED_RECEIVER_FIELD));
422            }
423    
424            for (DeclarationDescriptor descriptor : closure.getCaptureVariables().keySet()) {
425                if (descriptor instanceof VariableDescriptor && !(descriptor instanceof PropertyDescriptor)) {
426                    Type sharedVarType = typeMapper.getSharedVarType(descriptor);
427    
428                    Type type = sharedVarType != null
429                                      ? sharedVarType
430                                      : typeMapper.mapType((VariableDescriptor) descriptor);
431                    args.add(FieldInfo.createForHiddenField(ownerType, type, "$" + descriptor.getName().asString()));
432                }
433                else if (ExpressionTypingUtils.isLocalFunction(descriptor)) {
434                    Type classType = asmTypeForAnonymousClass(bindingContext, (FunctionDescriptor) descriptor);
435                    args.add(FieldInfo.createForHiddenField(ownerType, classType, "$" + descriptor.getName().asString()));
436                }
437                else if (descriptor instanceof FunctionDescriptor) {
438                    assert captureReceiverType != null;
439                }
440            }
441            return args;
442        }
443    
444        private static Type[] fieldListToTypeArray(List<FieldInfo> args) {
445            Type[] argTypes = new Type[args.size()];
446            for (int i = 0; i != argTypes.length; ++i) {
447                argTypes[i] = args.get(i).getFieldType();
448            }
449            return argTypes;
450        }
451    
452        @NotNull
453        public static FunctionDescriptor getErasedInvokeFunction(@NotNull FunctionDescriptor function) {
454            ClassDescriptor functionClass = DescriptorUtilsKt.getBuiltIns(function).getFunction(
455                    function.getValueParameters().size() + (function.getExtensionReceiverParameter() != null ? 1 : 0)
456            );
457            MemberScope scope = functionClass.getDefaultType().getMemberScope();
458            return scope.getContributedFunctions(OperatorNameConventions.INVOKE, NoLookupLocation.FROM_BACKEND).iterator().next();
459        }
460    }