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 org.jetbrains.annotations.NotNull;
020    import org.jetbrains.jet.codegen.context.CodegenContext;
021    import org.jetbrains.jet.codegen.state.GenerationState;
022    import org.jetbrains.jet.codegen.state.JetTypeMapper;
023    import org.jetbrains.jet.lang.descriptors.FunctionDescriptor;
024    import org.jetbrains.jet.lang.descriptors.SimpleFunctionDescriptor;
025    import org.jetbrains.jet.lang.psi.JetFile;
026    import org.jetbrains.jet.lang.resolve.DescriptorUtils;
027    import org.jetbrains.jet.lang.resolve.java.JvmClassName;
028    import org.jetbrains.jet.lang.resolve.java.PackageClassUtils;
029    import org.jetbrains.jet.lang.resolve.java.descriptor.JavaClassDescriptor;
030    import org.jetbrains.jet.lang.resolve.java.sam.SingleAbstractMethodUtils;
031    import org.jetbrains.jet.lang.resolve.name.FqName;
032    import org.jetbrains.jet.lang.resolve.name.Name;
033    import org.jetbrains.jet.lang.types.JetType;
034    import org.jetbrains.org.objectweb.asm.MethodVisitor;
035    import org.jetbrains.org.objectweb.asm.Type;
036    import org.jetbrains.org.objectweb.asm.commons.InstructionAdapter;
037    
038    import static org.jetbrains.jet.codegen.AsmUtil.NO_FLAG_PACKAGE_PRIVATE;
039    import static org.jetbrains.jet.codegen.AsmUtil.writeKotlinSyntheticClassAnnotation;
040    import static org.jetbrains.jet.lang.resolve.java.AsmTypeConstants.OBJECT_TYPE;
041    import static org.jetbrains.jet.lang.resolve.java.JvmAnnotationNames.KotlinSyntheticClass;
042    import static org.jetbrains.org.objectweb.asm.Opcodes.*;
043    
044    public class SamWrapperCodegen {
045        private static final String FUNCTION_FIELD_NAME = "function";
046    
047        private final GenerationState state;
048        private final JetTypeMapper typeMapper;
049        private final JavaClassDescriptor samInterface;
050    
051        public SamWrapperCodegen(@NotNull GenerationState state, @NotNull JavaClassDescriptor samInterface) {
052            this.state = state;
053            this.typeMapper = state.getTypeMapper();
054            this.samInterface = samInterface;
055        }
056    
057        public Type genWrapper(@NotNull JetFile file) {
058            // Name for generated class, in form of whatever$1
059            Type asmType = Type.getObjectType(getWrapperName(file));
060    
061            // e.g. (T, T) -> Int
062            JetType functionType = samInterface.getFunctionTypeForSamInterface();
063            assert functionType != null : samInterface.toString();
064            // e.g. compare(T, T)
065            SimpleFunctionDescriptor interfaceFunction = SingleAbstractMethodUtils.getAbstractMethodOfSamInterface(samInterface);
066    
067            ClassBuilder cv = state.getFactory().newVisitor(asmType, file);
068            cv.defineClass(file,
069                           V1_6,
070                           ACC_FINAL,
071                           asmType.getInternalName(),
072                           null,
073                           OBJECT_TYPE.getInternalName(),
074                           new String[]{ typeMapper.mapType(samInterface).getInternalName() }
075            );
076            cv.visitSource(file.getName(), null);
077    
078            writeKotlinSyntheticClassAnnotation(cv, KotlinSyntheticClass.Kind.SAM_WRAPPER);
079    
080            // e.g. ASM type for Function2
081            Type functionAsmType = typeMapper.mapType(functionType);
082    
083            cv.newField(null,
084                        ACC_SYNTHETIC | ACC_PRIVATE | ACC_FINAL,
085                        FUNCTION_FIELD_NAME,
086                        functionAsmType.getDescriptor(),
087                        null,
088                        null);
089    
090            generateConstructor(asmType, functionAsmType, cv);
091            generateMethod(asmType, functionAsmType, cv, interfaceFunction, functionType);
092    
093            cv.done();
094    
095            return asmType;
096        }
097    
098        private void generateConstructor(Type ownerType, Type functionType, ClassBuilder cv) {
099            MethodVisitor mv = cv.newMethod(null, NO_FLAG_PACKAGE_PRIVATE, "<init>", Type.getMethodDescriptor(Type.VOID_TYPE, functionType), null, null);
100    
101            if (state.getClassBuilderMode() == ClassBuilderMode.FULL) {
102                mv.visitCode();
103                InstructionAdapter iv = new InstructionAdapter(mv);
104    
105                // super constructor
106                iv.load(0, OBJECT_TYPE);
107                iv.invokespecial(OBJECT_TYPE.getInternalName(), "<init>", "()V");
108    
109                // save parameter to field
110                iv.load(0, OBJECT_TYPE);
111                iv.load(1, functionType);
112                iv.putfield(ownerType.getInternalName(), FUNCTION_FIELD_NAME, functionType.getDescriptor());
113    
114                iv.visitInsn(RETURN);
115                FunctionCodegen.endVisit(iv, "constructor of SAM wrapper", null);
116            }
117        }
118    
119        private void generateMethod(
120                Type ownerType,
121                Type functionType,
122                ClassBuilder cv,
123                SimpleFunctionDescriptor interfaceFunction,
124                JetType functionJetType
125        ) {
126            // using static context to avoid creating ClassDescriptor and everything else
127            FunctionCodegen codegen = new FunctionCodegen(CodegenContext.STATIC, cv, state, null);
128    
129            FunctionDescriptor invokeFunction = functionJetType.getMemberScope()
130                    .getFunctions(Name.identifier("invoke")).iterator().next().getOriginal();
131            StackValue functionField = StackValue.field(functionType, ownerType, FUNCTION_FIELD_NAME, false);
132            codegen.genDelegate(interfaceFunction, invokeFunction, functionField);
133        }
134    
135        private String getWrapperName(@NotNull JetFile containingFile) {
136            FqName packageClassFqName = PackageClassUtils.getPackageClassFqName(containingFile.getPackageFqName());
137            String packageInternalName = JvmClassName.byFqNameWithoutInnerClasses(packageClassFqName).getInternalName();
138            return packageInternalName + "$sam$" + samInterface.getName().asString() + "$" +
139                   Integer.toHexString(JvmCodegenUtil.getPathHashCode(containingFile.getVirtualFile()) * 31 + DescriptorUtils.getFqNameSafe(
140                           samInterface).hashCode());
141        }
142    }