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