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.intellij.util.ArrayUtil;
020    import kotlin.jvm.functions.Function0;
021    import org.jetbrains.annotations.NotNull;
022    import org.jetbrains.kotlin.codegen.context.CodegenContext;
023    import org.jetbrains.kotlin.codegen.context.MethodContext;
024    import org.jetbrains.kotlin.codegen.context.ScriptContext;
025    import org.jetbrains.kotlin.codegen.state.GenerationState;
026    import org.jetbrains.kotlin.descriptors.ClassDescriptor;
027    import org.jetbrains.kotlin.descriptors.PropertyDescriptor;
028    import org.jetbrains.kotlin.descriptors.ScriptDescriptor;
029    import org.jetbrains.kotlin.descriptors.ValueParameterDescriptor;
030    import org.jetbrains.kotlin.psi.*;
031    import org.jetbrains.kotlin.resolve.BindingContext;
032    import org.jetbrains.kotlin.resolve.jvm.diagnostics.JvmDeclarationOriginKt;
033    import org.jetbrains.kotlin.resolve.jvm.jvmSignature.JvmMethodSignature;
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 java.util.Collections;
039    import java.util.List;
040    
041    import static org.jetbrains.kotlin.codegen.binding.CodegenBinding.CLASS_FOR_SCRIPT;
042    import static org.jetbrains.kotlin.codegen.binding.CodegenBinding.asmTypeForScriptDescriptor;
043    import static org.jetbrains.kotlin.resolve.jvm.AsmTypes.OBJECT_TYPE;
044    import static org.jetbrains.kotlin.resolve.jvm.diagnostics.JvmDeclarationOrigin.NO_ORIGIN;
045    import static org.jetbrains.org.objectweb.asm.Opcodes.*;
046    
047    // SCRIPT: script code generator
048    public class ScriptCodegen extends MemberCodegen<KtScript> {
049    
050        public static ScriptCodegen createScriptCodegen(
051                @NotNull KtScript declaration,
052                @NotNull GenerationState state,
053                @NotNull CodegenContext parentContext
054        ) {
055            BindingContext bindingContext = state.getBindingContext();
056            ScriptDescriptor scriptDescriptor = bindingContext.get(BindingContext.SCRIPT, declaration);
057            assert scriptDescriptor != null;
058    
059            ClassDescriptor classDescriptorForScript = bindingContext.get(CLASS_FOR_SCRIPT, scriptDescriptor);
060            assert classDescriptorForScript != null;
061    
062            Type classType = asmTypeForScriptDescriptor(bindingContext, scriptDescriptor);
063    
064            ClassBuilder builder = state.getFactory().newVisitor(JvmDeclarationOriginKt.OtherOrigin(declaration, classDescriptorForScript),
065                                                                 classType, declaration.getContainingFile());
066            List<ScriptDescriptor> earlierScripts = state.getEarlierScriptsForReplInterpreter();
067            ScriptContext scriptContext = parentContext.intoScript(
068                    scriptDescriptor,
069                    earlierScripts == null ? Collections.<ScriptDescriptor>emptyList() : earlierScripts,
070                    classDescriptorForScript
071            );
072            return new ScriptCodegen(declaration, state, scriptContext, builder);
073        }
074    
075        private final KtScript scriptDeclaration;
076        private final ScriptContext context;
077        private final ScriptDescriptor scriptDescriptor;
078    
079        private ScriptCodegen(
080                @NotNull KtScript scriptDeclaration,
081                @NotNull GenerationState state,
082                @NotNull ScriptContext context,
083                @NotNull ClassBuilder builder
084        ) {
085            super(state, null, context, scriptDeclaration, builder);
086            this.scriptDeclaration = scriptDeclaration;
087            this.context = context;
088            this.scriptDescriptor = context.getScriptDescriptor();
089        }
090    
091        @Override
092        protected void generateDeclaration() {
093            Type classType = typeMapper.mapClass(context.getContextDescriptor());
094    
095            v.defineClass(scriptDeclaration,
096                          V1_6,
097                          ACC_PUBLIC,
098                          classType.getInternalName(),
099                          null,
100                          "java/lang/Object",
101                          ArrayUtil.EMPTY_STRING_ARRAY);
102        }
103    
104        @Override
105        protected void generateBody() {
106            genMembers();
107            genFieldsForParameters(scriptDescriptor, v);
108            genConstructor(scriptDescriptor, context.getContextDescriptor(), v,
109                           context.intoFunction(scriptDescriptor.getScriptCodeDescriptor()));
110        }
111    
112        @Override
113        protected void generateKotlinAnnotation() {
114            // TODO
115        }
116    
117        private void genConstructor(
118                @NotNull ScriptDescriptor scriptDescriptor,
119                @NotNull ClassDescriptor classDescriptorForScript,
120                @NotNull ClassBuilder classBuilder,
121                @NotNull MethodContext methodContext
122        ) {
123            //noinspection ConstantConditions
124            Type blockType = typeMapper.mapType(scriptDescriptor.getScriptCodeDescriptor().getReturnType());
125    
126            PropertyDescriptor scriptResultProperty = scriptDescriptor.getScriptResultProperty();
127            classBuilder.newField(JvmDeclarationOriginKt.OtherOrigin(scriptResultProperty),
128                                  ACC_PUBLIC | ACC_FINAL, scriptResultProperty.getName().asString(),
129                                  blockType.getDescriptor(), null, null);
130    
131            JvmMethodSignature jvmSignature = typeMapper.mapScriptSignature(scriptDescriptor, context.getEarlierScripts());
132    
133            MethodVisitor mv = classBuilder.newMethod(
134                    JvmDeclarationOriginKt.OtherOrigin(scriptDeclaration, scriptDescriptor.getClassDescriptor().getUnsubstitutedPrimaryConstructor()),
135                    ACC_PUBLIC, jvmSignature.getAsmMethod().getName(), jvmSignature.getAsmMethod().getDescriptor(),
136                    null, null);
137    
138            if (state.getClassBuilderMode() == ClassBuilderMode.FULL) {
139                mv.visitCode();
140    
141                InstructionAdapter iv = new InstructionAdapter(mv);
142    
143                Type classType = typeMapper.mapType(classDescriptorForScript);
144    
145                iv.load(0, classType);
146                iv.invokespecial("java/lang/Object", "<init>", "()V", false);
147    
148                iv.load(0, classType);
149    
150                FrameMap frameMap = new FrameMap();
151                frameMap.enterTemp(OBJECT_TYPE);
152    
153                for (ScriptDescriptor importedScript : context.getEarlierScripts()) {
154                    frameMap.enter(importedScript, OBJECT_TYPE);
155                }
156    
157                Type[] argTypes = jvmSignature.getAsmMethod().getArgumentTypes();
158                int add = 0;
159    
160                for (int i = 0; i < scriptDescriptor.getScriptCodeDescriptor().getValueParameters().size(); i++) {
161                    ValueParameterDescriptor parameter = scriptDescriptor.getScriptCodeDescriptor().getValueParameters().get(i);
162                    frameMap.enter(parameter, argTypes[i + add]);
163                }
164    
165                int offset = 1;
166    
167                for (ScriptDescriptor earlierScript : context.getEarlierScripts()) {
168                    Type earlierClassType = asmTypeForScriptDescriptor(bindingContext, earlierScript);
169                    iv.load(0, classType);
170                    iv.load(offset, earlierClassType);
171                    offset += earlierClassType.getSize();
172                    iv.putfield(classType.getInternalName(), context.getScriptFieldName(earlierScript), earlierClassType.getDescriptor());
173                }
174    
175                for (ValueParameterDescriptor parameter : scriptDescriptor.getScriptCodeDescriptor().getValueParameters()) {
176                    Type parameterType = typeMapper.mapType(parameter.getType());
177                    iv.load(0, classType);
178                    iv.load(offset, parameterType);
179                    offset += parameterType.getSize();
180                    iv.putfield(classType.getInternalName(), parameter.getName().getIdentifier(), parameterType.getDescriptor());
181                }
182    
183                final ExpressionCodegen codegen = new ExpressionCodegen(mv, frameMap, Type.VOID_TYPE, methodContext, state, this);
184    
185                generateInitializers(new Function0<ExpressionCodegen>() {
186                    @Override
187                    public ExpressionCodegen invoke() {
188                        return codegen;
189                    }
190                });
191    
192                StackValue stackValue = codegen.gen(scriptDeclaration.getBlockExpression());
193                if (stackValue.type != Type.VOID_TYPE) {
194                    StackValue.Field resultValue = StackValue
195                            .field(blockType, classType, ScriptDescriptor.LAST_EXPRESSION_VALUE_FIELD_NAME, false, StackValue.LOCAL_0);
196                    resultValue.store(stackValue, iv);
197                }
198                else {
199                    stackValue.put(blockType, iv);
200                }
201    
202                iv.areturn(Type.VOID_TYPE);
203            }
204    
205            mv.visitMaxs(-1, -1);
206            mv.visitEnd();
207        }
208    
209        private void genFieldsForParameters(@NotNull ScriptDescriptor script, @NotNull ClassBuilder classBuilder) {
210            for (ScriptDescriptor earlierScript : context.getEarlierScripts()) {
211                Type earlierClassName = asmTypeForScriptDescriptor(bindingContext, earlierScript);
212                int access = ACC_PRIVATE | ACC_FINAL;
213                classBuilder.newField(NO_ORIGIN, access, context.getScriptFieldName(earlierScript), earlierClassName.getDescriptor(), null, null);
214            }
215    
216            for (ValueParameterDescriptor parameter : script.getScriptCodeDescriptor().getValueParameters()) {
217                Type parameterType = typeMapper.mapType(parameter);
218                int access = ACC_PUBLIC | ACC_FINAL;
219                classBuilder.newField(JvmDeclarationOriginKt.OtherOrigin(parameter), access, parameter.getName().getIdentifier(), parameterType.getDescriptor(), null, null);
220            }
221        }
222    
223        private void genMembers() {
224            for (KtDeclaration declaration : scriptDeclaration.getDeclarations()) {
225                if (declaration instanceof KtProperty || declaration instanceof KtNamedFunction) {
226                    genFunctionOrProperty(declaration);
227                }
228                else if (declaration instanceof KtClassOrObject) {
229                    genClassOrObject((KtClassOrObject) declaration);
230                }
231            }
232        }
233    }