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 org.jetbrains.annotations.NotNull;
020    import org.jetbrains.kotlin.codegen.state.GenerationState;
021    import org.jetbrains.kotlin.codegen.state.KotlinTypeMapper;
022    import org.jetbrains.kotlin.descriptors.*;
023    import org.jetbrains.kotlin.descriptors.impl.ClassDescriptorImpl;
024    import org.jetbrains.kotlin.descriptors.impl.SimpleFunctionDescriptorImpl;
025    import org.jetbrains.kotlin.fileClasses.JvmFileClassUtil;
026    import org.jetbrains.kotlin.incremental.components.NoLookupLocation;
027    import org.jetbrains.kotlin.load.java.descriptors.JavaClassDescriptor;
028    import org.jetbrains.kotlin.load.kotlin.PackagePartClassUtils;
029    import org.jetbrains.kotlin.name.FqName;
030    import org.jetbrains.kotlin.name.Name;
031    import org.jetbrains.kotlin.psi.KtFile;
032    import org.jetbrains.kotlin.resolve.DescriptorUtils;
033    import org.jetbrains.kotlin.resolve.descriptorUtil.DescriptorUtilsKt;
034    import org.jetbrains.kotlin.resolve.jvm.diagnostics.JvmDeclarationOriginKt;
035    import org.jetbrains.kotlin.types.KotlinType;
036    import org.jetbrains.kotlin.util.OperatorNameConventions;
037    import org.jetbrains.org.objectweb.asm.MethodVisitor;
038    import org.jetbrains.org.objectweb.asm.Type;
039    import org.jetbrains.org.objectweb.asm.commons.InstructionAdapter;
040    
041    import java.util.Collections;
042    
043    import static org.jetbrains.kotlin.codegen.AsmUtil.NO_FLAG_PACKAGE_PRIVATE;
044    import static org.jetbrains.kotlin.codegen.AsmUtil.asmTypeByFqNameWithoutInnerClasses;
045    import static org.jetbrains.kotlin.resolve.jvm.AsmTypes.OBJECT_TYPE;
046    import static org.jetbrains.org.objectweb.asm.Opcodes.*;
047    
048    public class SamWrapperCodegen {
049        private static final String FUNCTION_FIELD_NAME = "function";
050    
051        private final GenerationState state;
052        private final boolean isInsideInline;
053        private final KotlinTypeMapper typeMapper;
054        private final SamType samType;
055        private final MemberCodegen<?> parentCodegen;
056        private final int visibility;
057    
058        public SamWrapperCodegen(
059                @NotNull GenerationState state,
060                @NotNull SamType samType,
061                @NotNull MemberCodegen<?> parentCodegen,
062                boolean isInsideInline
063        ) {
064            this.state = state;
065            this.isInsideInline = isInsideInline;
066            this.typeMapper = state.getTypeMapper();
067            this.samType = samType;
068            this.parentCodegen = parentCodegen;
069            visibility = isInsideInline ? ACC_PUBLIC : NO_FLAG_PACKAGE_PRIVATE;
070        }
071    
072        @NotNull
073        public Type genWrapper(@NotNull KtFile file) {
074            // Name for generated class, in form of whatever$1
075            FqName fqName = getWrapperName(file);
076            Type asmType = asmTypeByFqNameWithoutInnerClasses(fqName);
077    
078            // e.g. (T, T) -> Int
079            KotlinType functionType = samType.getKotlinFunctionType();
080    
081            ClassDescriptor classDescriptor = new ClassDescriptorImpl(
082                    samType.getJavaClassDescriptor().getContainingDeclaration(),
083                    fqName.shortName(),
084                    Modality.FINAL,
085                    ClassKind.CLASS,
086                    Collections.singleton(samType.getType()),
087                    SourceElement.NO_SOURCE,
088                    /* isExternal = */ false
089            );
090            // e.g. compare(T, T)
091            SimpleFunctionDescriptor erasedInterfaceFunction = samType.getAbstractMethod().getOriginal().copy(
092                    classDescriptor,
093                    Modality.FINAL,
094                    Visibilities.PUBLIC,
095                    CallableMemberDescriptor.Kind.SYNTHESIZED,
096                    /*copyOverrides=*/ false
097            );
098    
099            ClassBuilder cv = state.getFactory().newVisitor(JvmDeclarationOriginKt.OtherOrigin(erasedInterfaceFunction), asmType, file);
100            cv.defineClass(file,
101                           state.getClassFileVersion(),
102                           ACC_FINAL | ACC_SUPER | visibility,
103                           asmType.getInternalName(),
104                           null,
105                           OBJECT_TYPE.getInternalName(),
106                           new String[]{ typeMapper.mapType(samType.getType()).getInternalName() }
107            );
108            cv.visitSource(file.getName(), null);
109    
110            WriteAnnotationUtilKt.writeSyntheticClassMetadata(cv, state);
111    
112            // e.g. ASM type for Function2
113            Type functionAsmType = typeMapper.mapType(functionType);
114    
115            cv.newField(JvmDeclarationOriginKt.OtherOrigin(erasedInterfaceFunction),
116                        ACC_SYNTHETIC | ACC_PRIVATE | ACC_FINAL,
117                        FUNCTION_FIELD_NAME,
118                        functionAsmType.getDescriptor(),
119                        null,
120                        null);
121    
122            generateConstructor(asmType, functionAsmType, cv);
123            generateMethod(asmType, functionAsmType, cv, erasedInterfaceFunction, functionType);
124    
125            cv.done();
126    
127            return asmType;
128        }
129    
130        private void generateConstructor(Type ownerType, Type functionType, ClassBuilder cv) {
131            MethodVisitor mv = cv.newMethod(JvmDeclarationOriginKt.OtherOrigin(samType.getJavaClassDescriptor()),
132                                            visibility, "<init>", Type.getMethodDescriptor(Type.VOID_TYPE, functionType), null, null);
133    
134            if (state.getClassBuilderMode().generateBodies) {
135                mv.visitCode();
136                InstructionAdapter iv = new InstructionAdapter(mv);
137    
138                // super constructor
139                iv.load(0, OBJECT_TYPE);
140                iv.invokespecial(OBJECT_TYPE.getInternalName(), "<init>", "()V", false);
141    
142                // save parameter to field
143                iv.load(0, OBJECT_TYPE);
144                iv.load(1, functionType);
145                iv.putfield(ownerType.getInternalName(), FUNCTION_FIELD_NAME, functionType.getDescriptor());
146    
147                iv.visitInsn(RETURN);
148                FunctionCodegen.endVisit(iv, "constructor of SAM wrapper");
149            }
150        }
151    
152        private void generateMethod(
153                Type ownerType,
154                Type functionType,
155                ClassBuilder cv,
156                SimpleFunctionDescriptor erasedInterfaceFunction,
157                KotlinType functionJetType
158        ) {
159            // using root context to avoid creating ClassDescriptor and everything else
160            FunctionCodegen codegen = new FunctionCodegen(state.getRootContext().intoClass(
161                    (ClassDescriptor) erasedInterfaceFunction.getContainingDeclaration(), OwnerKind.IMPLEMENTATION, state), cv, state, parentCodegen);
162    
163            FunctionDescriptor invokeFunction =
164                    functionJetType.getMemberScope().getContributedFunctions(OperatorNameConventions.INVOKE, NoLookupLocation.FROM_BACKEND).iterator().next().getOriginal();
165            StackValue functionField = StackValue.field(functionType, ownerType, FUNCTION_FIELD_NAME, false, StackValue.none());
166            codegen.genSamDelegate(erasedInterfaceFunction, invokeFunction, functionField);
167    
168            // generate sam bridges
169            // TODO: erasedInterfaceFunction is actually not an interface function, but function in generated class
170            SimpleFunctionDescriptor originalInterfaceErased = samType.getAbstractMethod().getOriginal();
171            SimpleFunctionDescriptorImpl descriptorForBridges = SimpleFunctionDescriptorImpl
172                    .create(erasedInterfaceFunction.getContainingDeclaration(), erasedInterfaceFunction.getAnnotations(), originalInterfaceErased.getName(),
173                            CallableMemberDescriptor.Kind.DECLARATION, erasedInterfaceFunction.getSource());
174    
175            descriptorForBridges
176                    .initialize(null, originalInterfaceErased.getDispatchReceiverParameter(), originalInterfaceErased.getTypeParameters(),
177                                originalInterfaceErased.getValueParameters(), originalInterfaceErased.getReturnType(),
178                                Modality.OPEN, originalInterfaceErased.getVisibility());
179    
180            DescriptorUtilsKt.setSingleOverridden(descriptorForBridges, originalInterfaceErased);
181            codegen.generateBridges(descriptorForBridges);
182        }
183    
184        @NotNull
185        private FqName getWrapperName(@NotNull KtFile containingFile) {
186            FqName fileClassFqName = JvmFileClassUtil.getFileClassInfoNoResolve(containingFile).getFileClassFqName();
187            JavaClassDescriptor descriptor = samType.getJavaClassDescriptor();
188            int hash = PackagePartClassUtils.getPathHashCode(containingFile.getVirtualFile()) * 31 +
189                    DescriptorUtils.getFqNameSafe(descriptor).hashCode();
190            String shortName = String.format(
191                    "%s$sam$%s%s$%08x",
192                    fileClassFqName.shortName().asString(),
193                    descriptor.getName().asString(),
194                    (isInsideInline ? "$i" : ""),
195                    hash
196            );
197            return fileClassFqName.parent().child(Name.identifier(shortName));
198        }
199    }