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.annotations.Nullable;
021    import org.jetbrains.asm4.MethodVisitor;
022    import org.jetbrains.asm4.Type;
023    import org.jetbrains.asm4.commons.InstructionAdapter;
024    import org.jetbrains.jet.codegen.context.CodegenContext;
025    import org.jetbrains.jet.codegen.state.GenerationState;
026    import org.jetbrains.jet.lang.descriptors.FunctionDescriptor;
027    import org.jetbrains.jet.lang.descriptors.SimpleFunctionDescriptor;
028    import org.jetbrains.jet.lang.psi.JetFile;
029    import org.jetbrains.jet.lang.psi.JetPsiUtil;
030    import org.jetbrains.jet.lang.resolve.DescriptorUtils;
031    import org.jetbrains.jet.lang.resolve.java.JvmClassName;
032    import org.jetbrains.jet.lang.resolve.java.PackageClassUtils;
033    import org.jetbrains.jet.lang.resolve.java.descriptor.JavaClassDescriptor;
034    import org.jetbrains.jet.lang.resolve.java.sam.SingleAbstractMethodUtils;
035    import org.jetbrains.jet.lang.resolve.name.FqName;
036    import org.jetbrains.jet.lang.resolve.name.Name;
037    import org.jetbrains.jet.lang.types.JetType;
038    
039    import static org.jetbrains.asm4.Opcodes.*;
040    import static org.jetbrains.jet.codegen.AsmUtil.NO_FLAG_PACKAGE_PRIVATE;
041    import static org.jetbrains.jet.lang.resolve.java.AsmTypeConstants.OBJECT_TYPE;
042    
043    public class SamWrapperCodegen extends ParentCodegenAwareImpl {
044        private static final String FUNCTION_FIELD_NAME = "function";
045    
046        @NotNull private final JavaClassDescriptor samInterface;
047    
048        public SamWrapperCodegen(
049                @NotNull GenerationState state,
050                @NotNull JavaClassDescriptor samInterface,
051                @Nullable MemberCodegen parentCodegen
052        ) {
053            super(state, parentCodegen);
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            // e.g. ASM type for Function2
079            Type functionAsmType = state.getTypeMapper().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, interfaceFunction, 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 interfaceFunction,
122                JetType functionJetType
123        ) {
124    
125            // using static context to avoid creating ClassDescriptor and everything else
126            FunctionCodegen codegen = new FunctionCodegen(CodegenContext.STATIC, cv, state, getParentCodegen());
127    
128            FunctionDescriptor invokeFunction = functionJetType.getMemberScope()
129                    .getFunctions(Name.identifier("invoke")).iterator().next().getOriginal();
130            StackValue functionField = StackValue.field(functionType, ownerType, FUNCTION_FIELD_NAME, false);
131            codegen.genDelegate(interfaceFunction, invokeFunction, functionField);
132        }
133    
134        private String getWrapperName(@NotNull JetFile containingFile) {
135            FqName packageClassFqName = PackageClassUtils.getPackageClassFqName(JetPsiUtil.getFQName(containingFile));
136            String packageInternalName = JvmClassName.byFqNameWithoutInnerClasses(packageClassFqName).getInternalName();
137            return packageInternalName + "$sam$" + samInterface.getName().asString() + "$" +
138                   Integer.toHexString(CodegenUtil.getPathHashCode(containingFile.getVirtualFile()) * 31 + DescriptorUtils.getFqNameSafe(
139                           samInterface).hashCode());
140        }
141    }