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