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.boxType;
054    import static org.jetbrains.jet.codegen.AsmUtil.isPrimitive;
055    import static org.jetbrains.jet.lang.descriptors.CallableMemberDescriptor.Kind.SYNTHESIZED;
056    import static org.jetbrains.jet.lang.descriptors.SourceElement.NO_SOURCE;
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.jet.lang.resolve.java.diagnostics.DiagnosticsPackage.OtherOrigin;
060    import static org.jetbrains.jet.lang.resolve.java.diagnostics.DiagnosticsPackage.TraitImpl;
061    import static org.jetbrains.jet.lang.resolve.java.diagnostics.JvmDeclarationOrigin.NO_ORIGIN;
062    import static org.jetbrains.org.objectweb.asm.Opcodes.*;
063    
064    public abstract class MemberCodegen<T extends JetElement/* TODO: & JetDeclarationContainer*/> extends ParentCodegenAware {
065        protected final T element;
066        protected final FieldOwnerContext context;
067        protected final ClassBuilder v;
068        protected final FunctionCodegen functionCodegen;
069        protected final PropertyCodegen propertyCodegen;
070    
071        protected ExpressionCodegen clInit;
072        private NameGenerator inlineNameGenerator;
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            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            propValue.store(type, codegen.v);
252    
253            ResolvedCall<FunctionDescriptor> pdResolvedCall =
254                    bindingContext.get(BindingContext.DELEGATED_PROPERTY_PD_RESOLVED_CALL, propertyDescriptor);
255            if (pdResolvedCall != null) {
256                int index = PropertyCodegen.indexOfDelegatedProperty(property);
257                StackValue lastValue = PropertyCodegen.invokeDelegatedPropertyConventionMethod(propertyDescriptor, codegen,
258                                                                                               state.getTypeMapper(), pdResolvedCall, index, 0);
259                lastValue.put(Type.VOID_TYPE, codegen.v);
260            }
261        }
262    
263        private boolean shouldInitializeProperty(@NotNull JetProperty property) {
264            if (!property.hasDelegateExpressionOrInitializer()) return false;
265    
266            PropertyDescriptor propertyDescriptor = (PropertyDescriptor) bindingContext.get(VARIABLE, property);
267            assert propertyDescriptor != null;
268    
269            CompileTimeConstant<?> compileTimeValue = propertyDescriptor.getCompileTimeInitializer();
270            // we must write constant values for fields in light classes,
271            // because Java's completion for annotation arguments uses this information
272            if (compileTimeValue == null) return state.getClassBuilderMode() != ClassBuilderMode.LIGHT_CLASSES;
273    
274            //TODO: OPTIMIZATION: don't initialize static final fields
275    
276            Object value = compileTimeValue.getValue();
277            JetType jetType = getPropertyOrDelegateType(property, propertyDescriptor);
278            Type type = typeMapper.mapType(jetType);
279            return !skipDefaultValue(propertyDescriptor, value, type);
280        }
281    
282        @NotNull
283        private JetType getPropertyOrDelegateType(@NotNull JetProperty property, @NotNull PropertyDescriptor descriptor) {
284            JetExpression delegateExpression = property.getDelegateExpression();
285            if (delegateExpression != null) {
286                JetType delegateType = bindingContext.get(BindingContext.EXPRESSION_TYPE, delegateExpression);
287                assert delegateType != null : "Type of delegate expression should be recorded";
288                return delegateType;
289            }
290            return descriptor.getType();
291        }
292    
293        private static boolean skipDefaultValue(@NotNull PropertyDescriptor propertyDescriptor, Object value, @NotNull Type type) {
294            if (isPrimitive(type)) {
295                if (!propertyDescriptor.getType().isNullable() && value instanceof Number) {
296                    if (type == Type.INT_TYPE && ((Number) value).intValue() == 0) {
297                        return true;
298                    }
299                    if (type == Type.BYTE_TYPE && ((Number) value).byteValue() == 0) {
300                        return true;
301                    }
302                    if (type == Type.LONG_TYPE && ((Number) value).longValue() == 0L) {
303                        return true;
304                    }
305                    if (type == Type.SHORT_TYPE && ((Number) value).shortValue() == 0) {
306                        return true;
307                    }
308                    if (type == Type.DOUBLE_TYPE && ((Number) value).doubleValue() == 0d) {
309                        return true;
310                    }
311                    if (type == Type.FLOAT_TYPE && ((Number) value).floatValue() == 0f) {
312                        return true;
313                    }
314                }
315                if (type == Type.BOOLEAN_TYPE && value instanceof Boolean && !((Boolean) value)) {
316                    return true;
317                }
318                if (type == Type.CHAR_TYPE && value instanceof Character && ((Character) value) == 0) {
319                    return true;
320                }
321            }
322            else {
323                if (value == null) {
324                    return true;
325                }
326            }
327            return false;
328        }
329    
330        public static void generateReflectionObjectField(
331                @NotNull GenerationState state,
332                @NotNull Type thisAsmType,
333                @NotNull ClassBuilder classBuilder,
334                @NotNull Method factory,
335                @NotNull String fieldName,
336                @NotNull InstructionAdapter v
337        ) {
338            String type = factory.getReturnType().getDescriptor();
339            // TODO: generic signature
340            classBuilder.newField(NO_ORIGIN, ACC_PUBLIC | ACC_STATIC | ACC_FINAL | ACC_SYNTHETIC, fieldName, type, null, null);
341    
342            if (state.getClassBuilderMode() == ClassBuilderMode.LIGHT_CLASSES) return;
343    
344            v.aconst(thisAsmType);
345            v.invokestatic(REFLECTION_INTERNAL_PACKAGE, factory.getName(), factory.getDescriptor(), false);
346            v.putstatic(thisAsmType.getInternalName(), fieldName, type);
347        }
348    
349        protected void generatePropertyMetadataArrayFieldIfNeeded(@NotNull Type thisAsmType) {
350            List<JetProperty> delegatedProperties = new ArrayList<JetProperty>();
351            for (JetDeclaration declaration : ((JetDeclarationContainer) element).getDeclarations()) {
352                if (declaration instanceof JetProperty) {
353                    JetProperty property = (JetProperty) declaration;
354                    if (property.hasDelegate()) {
355                        delegatedProperties.add(property);
356                    }
357                }
358            }
359            if (delegatedProperties.isEmpty()) return;
360    
361            v.newField(NO_ORIGIN, ACC_PRIVATE | ACC_STATIC | ACC_FINAL | ACC_SYNTHETIC, JvmAbi.PROPERTY_METADATA_ARRAY_NAME,
362                       "[" + PROPERTY_METADATA_TYPE, null, null);
363    
364            if (state.getClassBuilderMode() == ClassBuilderMode.LIGHT_CLASSES) return;
365    
366            InstructionAdapter iv = createOrGetClInitCodegen().v;
367            iv.iconst(delegatedProperties.size());
368            iv.newarray(PROPERTY_METADATA_TYPE);
369    
370            for (int i = 0, size = delegatedProperties.size(); i < size; i++) {
371                VariableDescriptor property = BindingContextUtils.getNotNull(bindingContext, VARIABLE, delegatedProperties.get(i));
372    
373                iv.dup();
374                iv.iconst(i);
375                iv.anew(PROPERTY_METADATA_IMPL_TYPE);
376                iv.dup();
377                iv.visitLdcInsn(property.getName().asString());
378                iv.invokespecial(PROPERTY_METADATA_IMPL_TYPE.getInternalName(), "<init>", "(Ljava/lang/String;)V", false);
379                iv.astore(PROPERTY_METADATA_IMPL_TYPE);
380            }
381    
382            iv.putstatic(thisAsmType.getInternalName(), JvmAbi.PROPERTY_METADATA_ARRAY_NAME, "[" + PROPERTY_METADATA_TYPE);
383        }
384    
385        public String getClassName() {
386            return v.getThisName();
387        }
388    
389        @NotNull
390        public FieldOwnerContext<?> getContext() {
391            return context;
392        }
393    }