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