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