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