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.openapi.progress.ProcessCanceledException;
020    import kotlin.Function0;
021    import org.jetbrains.annotations.NotNull;
022    import org.jetbrains.annotations.Nullable;
023    import org.jetbrains.jet.codegen.context.ClassContext;
024    import org.jetbrains.jet.codegen.context.CodegenContext;
025    import org.jetbrains.jet.codegen.context.FieldOwnerContext;
026    import org.jetbrains.jet.codegen.inline.InlineCodegenUtil;
027    import org.jetbrains.jet.codegen.inline.NameGenerator;
028    import org.jetbrains.jet.codegen.state.GenerationState;
029    import org.jetbrains.jet.lang.descriptors.*;
030    import org.jetbrains.jet.lang.descriptors.annotations.Annotations;
031    import org.jetbrains.jet.lang.descriptors.impl.SimpleFunctionDescriptorImpl;
032    import org.jetbrains.jet.lang.psi.*;
033    import org.jetbrains.jet.lang.resolve.BindingContext;
034    import org.jetbrains.jet.lang.resolve.BindingContextUtils;
035    import org.jetbrains.jet.lang.resolve.constants.CompileTimeConstant;
036    import org.jetbrains.jet.lang.resolve.java.JvmAbi;
037    import org.jetbrains.jet.lang.resolve.name.Name;
038    import org.jetbrains.jet.lang.resolve.name.SpecialNames;
039    import org.jetbrains.jet.lang.types.ErrorUtils;
040    import org.jetbrains.jet.lang.types.JetType;
041    import org.jetbrains.jet.storage.LockBasedStorageManager;
042    import org.jetbrains.jet.storage.NotNullLazyValue;
043    import org.jetbrains.org.objectweb.asm.MethodVisitor;
044    import org.jetbrains.org.objectweb.asm.Type;
045    import org.jetbrains.org.objectweb.asm.commons.InstructionAdapter;
046    
047    import java.util.ArrayList;
048    import java.util.Collections;
049    import java.util.List;
050    
051    import static org.jetbrains.jet.codegen.AsmUtil.boxType;
052    import static org.jetbrains.jet.codegen.AsmUtil.isPrimitive;
053    import static org.jetbrains.jet.lang.descriptors.CallableMemberDescriptor.Kind.SYNTHESIZED;
054    import static org.jetbrains.jet.lang.resolve.BindingContext.VARIABLE;
055    import static org.jetbrains.jet.lang.resolve.java.AsmTypeConstants.*;
056    import static org.jetbrains.org.objectweb.asm.Opcodes.*;
057    
058    public abstract class MemberCodegen<T extends JetElement/* TODO: & JetDeclarationContainer*/> extends ParentCodegenAwareImpl {
059        protected final T element;
060        protected final FieldOwnerContext context;
061        protected final ClassBuilder v;
062        protected ExpressionCodegen clInit;
063    
064        private NameGenerator inlineNameGenerator;
065    
066        public MemberCodegen(
067                @NotNull GenerationState state,
068                @Nullable MemberCodegen<?> parentCodegen,
069                @NotNull FieldOwnerContext context,
070                T element,
071                ClassBuilder builder
072        ) {
073            super(state, parentCodegen);
074            this.element = element;
075            this.context = context;
076            this.v = builder;
077        }
078    
079        public void generate() {
080            generateDeclaration();
081    
082            generateBody();
083    
084            generateSyntheticParts();
085    
086            generateKotlinAnnotation();
087    
088            done();
089        }
090    
091        protected abstract void generateDeclaration();
092    
093        protected abstract void generateBody();
094    
095        protected void generateSyntheticParts() {
096        }
097    
098        protected abstract void generateKotlinAnnotation();
099    
100        private void done() {
101            if (clInit != null) {
102                clInit.v.visitInsn(RETURN);
103                FunctionCodegen.endVisit(clInit.v, "static initializer", element);
104            }
105    
106            v.done();
107        }
108    
109        public void genFunctionOrProperty(
110                @NotNull JetTypeParameterListOwner functionOrProperty,
111                @NotNull ClassBuilder classBuilder
112        ) {
113            FunctionCodegen functionCodegen = new FunctionCodegen(context, classBuilder, state, this);
114            if (functionOrProperty instanceof JetNamedFunction) {
115                try {
116                    functionCodegen.gen((JetNamedFunction) functionOrProperty);
117                }
118                catch (ProcessCanceledException e) {
119                    throw e;
120                }
121                catch (CompilationException e) {
122                    throw e;
123                }
124                catch (Exception e) {
125                    throw new CompilationException("Failed to generate function " + functionOrProperty.getName(), e, functionOrProperty);
126                }
127            }
128            else if (functionOrProperty instanceof JetProperty) {
129                try {
130                    new PropertyCodegen(context, classBuilder, functionCodegen, this).gen((JetProperty) functionOrProperty);
131                }
132                catch (ProcessCanceledException e) {
133                    throw e;
134                }
135                catch (CompilationException e) {
136                    throw e;
137                }
138                catch (Exception e) {
139                    throw new CompilationException("Failed to generate property " + functionOrProperty.getName(), e, functionOrProperty);
140                }
141            }
142            else {
143                throw new IllegalArgumentException("Unknown parameter: " + functionOrProperty);
144            }
145        }
146    
147        public static void genClassOrObject(
148                @NotNull CodegenContext parentContext,
149                @NotNull JetClassOrObject aClass,
150                @NotNull GenerationState state,
151                @Nullable MemberCodegen<?> parentCodegen
152        ) {
153            ClassDescriptor descriptor = state.getBindingContext().get(BindingContext.CLASS, aClass);
154    
155            if (descriptor == null || ErrorUtils.isError(descriptor)) {
156                badDescriptor(descriptor, state.getClassBuilderMode());
157                return;
158            }
159    
160            if (descriptor.getName().equals(SpecialNames.NO_NAME_PROVIDED)) {
161                badDescriptor(descriptor, state.getClassBuilderMode());
162            }
163    
164            ClassBuilder classBuilder = state.getFactory().forClassImplementation(descriptor, aClass.getContainingFile());
165            ClassContext classContext = parentContext.intoClass(descriptor, OwnerKind.IMPLEMENTATION, state);
166            new ImplementationBodyCodegen(aClass, classContext, classBuilder, state, parentCodegen).generate();
167    
168            if (aClass instanceof JetClass && ((JetClass) aClass).isTrait()) {
169                ClassBuilder traitImplBuilder = state.getFactory().forTraitImplementation(descriptor, state, aClass.getContainingFile());
170                ClassContext traitImplContext = parentContext.intoClass(descriptor, OwnerKind.TRAIT_IMPL, state);
171                new TraitImplBodyCodegen(aClass, traitImplContext, traitImplBuilder, state, parentCodegen).generate();
172            }
173        }
174    
175        private static void badDescriptor(ClassDescriptor descriptor, ClassBuilderMode mode) {
176            if (mode != ClassBuilderMode.LIGHT_CLASSES) {
177                throw new IllegalStateException("Generating bad descriptor in ClassBuilderMode = " + mode + ": " + descriptor);
178            }
179        }
180    
181        public void genClassOrObject(JetClassOrObject aClass) {
182            genClassOrObject(context, aClass, state, this);
183        }
184    
185        @NotNull
186        public NameGenerator getInlineNameGenerator() {
187            if (inlineNameGenerator == null) {
188                String prefix = InlineCodegenUtil.getInlineName(context, typeMapper);
189                inlineNameGenerator = new NameGenerator(prefix);
190            }
191            return inlineNameGenerator;
192        }
193    
194        @NotNull
195        protected ExpressionCodegen createOrGetClInitCodegen() {
196            DeclarationDescriptor descriptor = context.getContextDescriptor();
197            assert state.getClassBuilderMode() == ClassBuilderMode.FULL
198                    : "<clinit> should not be generated for light classes. Descriptor: " + descriptor;
199            if (clInit == null) {
200                MethodVisitor mv = v.newMethod(null, ACC_STATIC, "<clinit>", "()V", null, null);
201                mv.visitCode();
202                SimpleFunctionDescriptorImpl clInit =
203                        SimpleFunctionDescriptorImpl.create(descriptor, Annotations.EMPTY, Name.special("<clinit>"), SYNTHESIZED);
204                clInit.initialize(null, null, Collections.<TypeParameterDescriptor>emptyList(),
205                                  Collections.<ValueParameterDescriptor>emptyList(), null, null, Visibilities.PRIVATE);
206    
207                this.clInit = new ExpressionCodegen(mv, new FrameMap(), Type.VOID_TYPE, context.intoFunction(clInit), state, this);
208            }
209            return clInit;
210        }
211    
212        protected void generateInitializers(@NotNull Function0<ExpressionCodegen> createCodegen) {
213            NotNullLazyValue<ExpressionCodegen> codegen = LockBasedStorageManager.NO_LOCKS.createLazyValue(createCodegen);
214            for (JetDeclaration declaration : ((JetDeclarationContainer) element).getDeclarations()) {
215                if (declaration instanceof JetProperty) {
216                    if (shouldInitializeProperty((JetProperty) declaration)) {
217                        initializeProperty(codegen.invoke(), (JetProperty) declaration);
218                    }
219                }
220                else if (declaration instanceof JetClassInitializer) {
221                    codegen.invoke().gen(((JetClassInitializer) declaration).getBody(), Type.VOID_TYPE);
222                }
223            }
224        }
225    
226        private void initializeProperty(@NotNull ExpressionCodegen codegen, @NotNull JetProperty property) {
227            PropertyDescriptor propertyDescriptor = (PropertyDescriptor) bindingContext.get(VARIABLE, property);
228            assert propertyDescriptor != null;
229    
230            JetExpression initializer = property.getDelegateExpressionOrInitializer();
231            assert initializer != null : "shouldInitializeProperty must return false if initializer is null";
232    
233            JetType jetType = getPropertyOrDelegateType(property, propertyDescriptor);
234    
235            StackValue.Property propValue = codegen.intermediateValueForProperty(propertyDescriptor, true, null, MethodKind.INITIALIZER);
236    
237            if (!propValue.isStatic) {
238                codegen.v.load(0, OBJECT_TYPE);
239            }
240    
241            Type type = codegen.expressionType(initializer);
242            if (jetType.isNullable()) {
243                type = boxType(type);
244            }
245            codegen.gen(initializer, type);
246    
247            propValue.store(type, codegen.v);
248        }
249    
250        private boolean shouldInitializeProperty(@NotNull JetProperty property) {
251            JetExpression initializer = property.getDelegateExpressionOrInitializer();
252            if (initializer == null) return false;
253    
254            PropertyDescriptor propertyDescriptor = (PropertyDescriptor) bindingContext.get(VARIABLE, property);
255            assert propertyDescriptor != null;
256    
257            CompileTimeConstant<?> compileTimeValue = propertyDescriptor.getCompileTimeInitializer();
258            if (compileTimeValue == null) return true;
259    
260            //TODO: OPTIMIZATION: don't initialize static final fields
261    
262            Object value = compileTimeValue.getValue();
263            JetType jetType = getPropertyOrDelegateType(property, propertyDescriptor);
264            Type type = typeMapper.mapType(jetType);
265            return !skipDefaultValue(propertyDescriptor, value, type);
266        }
267    
268        @NotNull
269        private JetType getPropertyOrDelegateType(@NotNull JetProperty property, @NotNull PropertyDescriptor descriptor) {
270            JetExpression delegateExpression = property.getDelegateExpression();
271            if (delegateExpression != null) {
272                JetType delegateType = bindingContext.get(BindingContext.EXPRESSION_TYPE, delegateExpression);
273                assert delegateType != null : "Type of delegate expression should be recorded";
274                return delegateType;
275            }
276            return descriptor.getType();
277        }
278    
279        private static boolean skipDefaultValue(@NotNull PropertyDescriptor propertyDescriptor, Object value, @NotNull Type type) {
280            if (isPrimitive(type)) {
281                if (!propertyDescriptor.getType().isNullable() && value instanceof Number) {
282                    if (type == Type.INT_TYPE && ((Number) value).intValue() == 0) {
283                        return true;
284                    }
285                    if (type == Type.BYTE_TYPE && ((Number) value).byteValue() == 0) {
286                        return true;
287                    }
288                    if (type == Type.LONG_TYPE && ((Number) value).longValue() == 0L) {
289                        return true;
290                    }
291                    if (type == Type.SHORT_TYPE && ((Number) value).shortValue() == 0) {
292                        return true;
293                    }
294                    if (type == Type.DOUBLE_TYPE && ((Number) value).doubleValue() == 0d) {
295                        return true;
296                    }
297                    if (type == Type.FLOAT_TYPE && ((Number) value).floatValue() == 0f) {
298                        return true;
299                    }
300                }
301                if (type == Type.BOOLEAN_TYPE && value instanceof Boolean && !((Boolean) value)) {
302                    return true;
303                }
304                if (type == Type.CHAR_TYPE && value instanceof Character && ((Character) value) == 0) {
305                    return true;
306                }
307            }
308            else {
309                if (value == null) {
310                    return true;
311                }
312            }
313            return false;
314        }
315    
316        protected void generatePropertyMetadataArrayFieldIfNeeded(@NotNull Type thisAsmType) {
317            List<JetProperty> delegatedProperties = new ArrayList<JetProperty>();
318            for (JetDeclaration declaration : ((JetDeclarationContainer) element).getDeclarations()) {
319                if (declaration instanceof JetProperty) {
320                    JetProperty property = (JetProperty) declaration;
321                    if (property.getDelegate() != null) {
322                        delegatedProperties.add(property);
323                    }
324                }
325            }
326            if (delegatedProperties.isEmpty()) return;
327    
328            v.newField(null, ACC_PRIVATE | ACC_STATIC | ACC_FINAL | ACC_SYNTHETIC, JvmAbi.PROPERTY_METADATA_ARRAY_NAME,
329                       "[" + PROPERTY_METADATA_TYPE, null, null);
330    
331            InstructionAdapter iv = createOrGetClInitCodegen().v;
332            iv.iconst(delegatedProperties.size());
333            iv.newarray(PROPERTY_METADATA_TYPE);
334    
335            for (int i = 0, size = delegatedProperties.size(); i < size; i++) {
336                VariableDescriptor property = BindingContextUtils.getNotNull(bindingContext, VARIABLE, delegatedProperties.get(i));
337    
338                iv.dup();
339                iv.iconst(i);
340                iv.anew(PROPERTY_METADATA_IMPL_TYPE);
341                iv.dup();
342                iv.visitLdcInsn(property.getName().asString());
343                iv.invokespecial(PROPERTY_METADATA_IMPL_TYPE.getInternalName(), "<init>", "(Ljava/lang/String;)V");
344                iv.astore(PROPERTY_METADATA_IMPL_TYPE);
345            }
346    
347            iv.putstatic(thisAsmType.getInternalName(), JvmAbi.PROPERTY_METADATA_ARRAY_NAME, "[" + PROPERTY_METADATA_TYPE);
348        }
349    
350        public String getClassName() {
351            return v.getThisName();
352        }
353    }