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