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 ParentCodegenAware {
059        protected final T element;
060        protected final FieldOwnerContext context;
061        protected final ClassBuilder v;
062        protected final FunctionCodegen functionCodegen;
063        protected final PropertyCodegen propertyCodegen;
064    
065        protected ExpressionCodegen clInit;
066        private NameGenerator inlineNameGenerator;
067    
068        public MemberCodegen(
069                @NotNull GenerationState state,
070                @Nullable MemberCodegen<?> parentCodegen,
071                @NotNull FieldOwnerContext context,
072                T element,
073                @NotNull ClassBuilder builder
074        ) {
075            super(state, parentCodegen);
076            this.element = element;
077            this.context = context;
078            this.v = builder;
079            this.functionCodegen = new FunctionCodegen(context, v, state, this);
080            this.propertyCodegen = new PropertyCodegen(context, v, functionCodegen, this);
081        }
082    
083        public void generate() {
084            generateDeclaration();
085    
086            generateBody();
087    
088            generateSyntheticParts();
089    
090            generateKotlinAnnotation();
091    
092            done();
093        }
094    
095        protected abstract void generateDeclaration();
096    
097        protected abstract void generateBody();
098    
099        protected void generateSyntheticParts() {
100        }
101    
102        protected abstract void generateKotlinAnnotation();
103    
104        private void done() {
105            if (clInit != null) {
106                clInit.v.visitInsn(RETURN);
107                FunctionCodegen.endVisit(clInit.v, "static initializer", element);
108            }
109    
110            v.done();
111        }
112    
113        public void genFunctionOrProperty(@NotNull JetDeclaration functionOrProperty) {
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                    propertyCodegen.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            Type classType = state.getTypeMapper().mapClass(descriptor);
165            ClassBuilder classBuilder = state.getFactory().newVisitor(classType, aClass.getContainingFile());
166            ClassContext classContext = parentContext.intoClass(descriptor, OwnerKind.IMPLEMENTATION, state);
167            new ImplementationBodyCodegen(aClass, classContext, classBuilder, state, parentCodegen).generate();
168    
169            if (aClass instanceof JetClass && ((JetClass) aClass).isTrait()) {
170                Type traitImplType = state.getTypeMapper().mapTraitImpl(descriptor);
171                ClassBuilder traitImplBuilder = state.getFactory().newVisitor(traitImplType, aClass.getContainingFile());
172                ClassContext traitImplContext = parentContext.intoClass(descriptor, OwnerKind.TRAIT_IMPL, state);
173                new TraitImplBodyCodegen(aClass, traitImplContext, traitImplBuilder, state, parentCodegen).generate();
174            }
175        }
176    
177        private static void badDescriptor(ClassDescriptor descriptor, ClassBuilderMode mode) {
178            if (mode != ClassBuilderMode.LIGHT_CLASSES) {
179                throw new IllegalStateException("Generating bad descriptor in ClassBuilderMode = " + mode + ": " + descriptor);
180            }
181        }
182    
183        public void genClassOrObject(JetClassOrObject aClass) {
184            genClassOrObject(context, aClass, state, this);
185        }
186    
187        @NotNull
188        public NameGenerator getInlineNameGenerator() {
189            if (inlineNameGenerator == null) {
190                String prefix = InlineCodegenUtil.getInlineName(context, typeMapper);
191                inlineNameGenerator = new NameGenerator(prefix);
192            }
193            return inlineNameGenerator;
194        }
195    
196        @NotNull
197        protected ExpressionCodegen createOrGetClInitCodegen() {
198            DeclarationDescriptor descriptor = context.getContextDescriptor();
199            assert state.getClassBuilderMode() == ClassBuilderMode.FULL
200                    : "<clinit> should not be generated for light classes. Descriptor: " + descriptor;
201            if (clInit == null) {
202                MethodVisitor mv = v.newMethod(null, ACC_STATIC, "<clinit>", "()V", null, null);
203                mv.visitCode();
204                SimpleFunctionDescriptorImpl clInit =
205                        SimpleFunctionDescriptorImpl.create(descriptor, Annotations.EMPTY, Name.special("<clinit>"), SYNTHESIZED);
206                clInit.initialize(null, null, Collections.<TypeParameterDescriptor>emptyList(),
207                                  Collections.<ValueParameterDescriptor>emptyList(), null, null, Visibilities.PRIVATE);
208    
209                this.clInit = new ExpressionCodegen(mv, new FrameMap(), Type.VOID_TYPE, context.intoFunction(clInit), state, this);
210            }
211            return clInit;
212        }
213    
214        protected void generateInitializers(@NotNull Function0<ExpressionCodegen> createCodegen) {
215            NotNullLazyValue<ExpressionCodegen> codegen = LockBasedStorageManager.NO_LOCKS.createLazyValue(createCodegen);
216            for (JetDeclaration declaration : ((JetDeclarationContainer) element).getDeclarations()) {
217                if (declaration instanceof JetProperty) {
218                    if (shouldInitializeProperty((JetProperty) declaration)) {
219                        initializeProperty(codegen.invoke(), (JetProperty) declaration);
220                    }
221                }
222                else if (declaration instanceof JetClassInitializer) {
223                    codegen.invoke().gen(((JetClassInitializer) declaration).getBody(), Type.VOID_TYPE);
224                }
225            }
226        }
227    
228        private void initializeProperty(@NotNull ExpressionCodegen codegen, @NotNull JetProperty property) {
229            PropertyDescriptor propertyDescriptor = (PropertyDescriptor) bindingContext.get(VARIABLE, property);
230            assert propertyDescriptor != null;
231    
232            JetExpression initializer = property.getDelegateExpressionOrInitializer();
233            assert initializer != null : "shouldInitializeProperty must return false if initializer is null";
234    
235            JetType jetType = getPropertyOrDelegateType(property, propertyDescriptor);
236    
237            StackValue.Property propValue = codegen.intermediateValueForProperty(propertyDescriptor, true, null, MethodKind.INITIALIZER);
238    
239            if (!propValue.isStatic) {
240                codegen.v.load(0, OBJECT_TYPE);
241            }
242    
243            Type type = codegen.expressionType(initializer);
244            if (jetType.isNullable()) {
245                type = boxType(type);
246            }
247            codegen.gen(initializer, type);
248    
249            propValue.store(type, codegen.v);
250        }
251    
252        private boolean shouldInitializeProperty(@NotNull JetProperty property) {
253            if (!property.hasDelegateExpressionOrInitializer()) return false;
254    
255            PropertyDescriptor propertyDescriptor = (PropertyDescriptor) bindingContext.get(VARIABLE, property);
256            assert propertyDescriptor != null;
257    
258            CompileTimeConstant<?> compileTimeValue = propertyDescriptor.getCompileTimeInitializer();
259            if (compileTimeValue == null) return true;
260    
261            //TODO: OPTIMIZATION: don't initialize static final fields
262    
263            Object value = compileTimeValue.getValue();
264            JetType jetType = getPropertyOrDelegateType(property, propertyDescriptor);
265            Type type = typeMapper.mapType(jetType);
266            return !skipDefaultValue(propertyDescriptor, value, type);
267        }
268    
269        @NotNull
270        private JetType getPropertyOrDelegateType(@NotNull JetProperty property, @NotNull PropertyDescriptor descriptor) {
271            JetExpression delegateExpression = property.getDelegateExpression();
272            if (delegateExpression != null) {
273                JetType delegateType = bindingContext.get(BindingContext.EXPRESSION_TYPE, delegateExpression);
274                assert delegateType != null : "Type of delegate expression should be recorded";
275                return delegateType;
276            }
277            return descriptor.getType();
278        }
279    
280        private static boolean skipDefaultValue(@NotNull PropertyDescriptor propertyDescriptor, Object value, @NotNull Type type) {
281            if (isPrimitive(type)) {
282                if (!propertyDescriptor.getType().isNullable() && value instanceof Number) {
283                    if (type == Type.INT_TYPE && ((Number) value).intValue() == 0) {
284                        return true;
285                    }
286                    if (type == Type.BYTE_TYPE && ((Number) value).byteValue() == 0) {
287                        return true;
288                    }
289                    if (type == Type.LONG_TYPE && ((Number) value).longValue() == 0L) {
290                        return true;
291                    }
292                    if (type == Type.SHORT_TYPE && ((Number) value).shortValue() == 0) {
293                        return true;
294                    }
295                    if (type == Type.DOUBLE_TYPE && ((Number) value).doubleValue() == 0d) {
296                        return true;
297                    }
298                    if (type == Type.FLOAT_TYPE && ((Number) value).floatValue() == 0f) {
299                        return true;
300                    }
301                }
302                if (type == Type.BOOLEAN_TYPE && value instanceof Boolean && !((Boolean) value)) {
303                    return true;
304                }
305                if (type == Type.CHAR_TYPE && value instanceof Character && ((Character) value) == 0) {
306                    return true;
307                }
308            }
309            else {
310                if (value == null) {
311                    return true;
312                }
313            }
314            return false;
315        }
316    
317        protected void generatePropertyMetadataArrayFieldIfNeeded(@NotNull Type thisAsmType) {
318            List<JetProperty> delegatedProperties = new ArrayList<JetProperty>();
319            for (JetDeclaration declaration : ((JetDeclarationContainer) element).getDeclarations()) {
320                if (declaration instanceof JetProperty) {
321                    JetProperty property = (JetProperty) declaration;
322                    if (property.hasDelegate()) {
323                        delegatedProperties.add(property);
324                    }
325                }
326            }
327            if (delegatedProperties.isEmpty()) return;
328    
329            v.newField(null, ACC_PRIVATE | ACC_STATIC | ACC_FINAL | ACC_SYNTHETIC, JvmAbi.PROPERTY_METADATA_ARRAY_NAME,
330                       "[" + PROPERTY_METADATA_TYPE, null, null);
331    
332            InstructionAdapter iv = createOrGetClInitCodegen().v;
333            iv.iconst(delegatedProperties.size());
334            iv.newarray(PROPERTY_METADATA_TYPE);
335    
336            for (int i = 0, size = delegatedProperties.size(); i < size; i++) {
337                VariableDescriptor property = BindingContextUtils.getNotNull(bindingContext, VARIABLE, delegatedProperties.get(i));
338    
339                iv.dup();
340                iv.iconst(i);
341                iv.anew(PROPERTY_METADATA_IMPL_TYPE);
342                iv.dup();
343                iv.visitLdcInsn(property.getName().asString());
344                iv.invokespecial(PROPERTY_METADATA_IMPL_TYPE.getInternalName(), "<init>", "(Ljava/lang/String;)V");
345                iv.astore(PROPERTY_METADATA_IMPL_TYPE);
346            }
347    
348            iv.putstatic(thisAsmType.getInternalName(), JvmAbi.PROPERTY_METADATA_ARRAY_NAME, "[" + PROPERTY_METADATA_TYPE);
349        }
350    
351        public String getClassName() {
352            return v.getThisName();
353        }
354    }