001    /*
002     * Copyright 2010-2015 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.kotlin.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.kotlin.codegen.context.*;
024    import org.jetbrains.kotlin.codegen.inline.InlineCodegenUtil;
025    import org.jetbrains.kotlin.codegen.inline.NameGenerator;
026    import org.jetbrains.kotlin.codegen.inline.ReifiedTypeParametersUsages;
027    import org.jetbrains.kotlin.codegen.state.GenerationState;
028    import org.jetbrains.kotlin.codegen.state.JetTypeMapper;
029    import org.jetbrains.kotlin.descriptors.*;
030    import org.jetbrains.kotlin.descriptors.annotations.Annotations;
031    import org.jetbrains.kotlin.descriptors.impl.SimpleFunctionDescriptorImpl;
032    import org.jetbrains.kotlin.load.java.JvmAbi;
033    import org.jetbrains.kotlin.load.kotlin.PackagePartClassUtils;
034    import org.jetbrains.kotlin.name.Name;
035    import org.jetbrains.kotlin.name.SpecialNames;
036    import org.jetbrains.kotlin.psi.*;
037    import org.jetbrains.kotlin.resolve.BindingContext;
038    import org.jetbrains.kotlin.resolve.BindingContextUtils;
039    import org.jetbrains.kotlin.resolve.BindingTrace;
040    import org.jetbrains.kotlin.resolve.TemporaryBindingTrace;
041    import org.jetbrains.kotlin.resolve.calls.model.ResolvedCall;
042    import org.jetbrains.kotlin.resolve.constants.CompileTimeConstant;
043    import org.jetbrains.kotlin.resolve.constants.IntegerValueTypeConstant;
044    import org.jetbrains.kotlin.resolve.constants.evaluate.ConstantExpressionEvaluator;
045    import org.jetbrains.kotlin.resolve.descriptorUtil.DescriptorUtilPackage;
046    import org.jetbrains.kotlin.storage.LockBasedStorageManager;
047    import org.jetbrains.kotlin.storage.NotNullLazyValue;
048    import org.jetbrains.kotlin.types.ErrorUtils;
049    import org.jetbrains.kotlin.types.JetType;
050    import org.jetbrains.org.objectweb.asm.MethodVisitor;
051    import org.jetbrains.org.objectweb.asm.Type;
052    import org.jetbrains.org.objectweb.asm.commons.InstructionAdapter;
053    import org.jetbrains.org.objectweb.asm.commons.Method;
054    
055    import java.util.*;
056    
057    import static org.jetbrains.kotlin.codegen.AsmUtil.calculateInnerClassAccessFlags;
058    import static org.jetbrains.kotlin.codegen.AsmUtil.isPrimitive;
059    import static org.jetbrains.kotlin.descriptors.CallableMemberDescriptor.Kind.SYNTHESIZED;
060    import static org.jetbrains.kotlin.descriptors.SourceElement.NO_SOURCE;
061    import static org.jetbrains.kotlin.resolve.BindingContext.VARIABLE;
062    import static org.jetbrains.kotlin.resolve.jvm.AsmTypes.*;
063    import static org.jetbrains.kotlin.resolve.jvm.diagnostics.DiagnosticsPackage.OtherOrigin;
064    import static org.jetbrains.kotlin.resolve.jvm.diagnostics.DiagnosticsPackage.TraitImpl;
065    import static org.jetbrains.kotlin.resolve.jvm.diagnostics.JvmDeclarationOrigin.NO_ORIGIN;
066    import static org.jetbrains.org.objectweb.asm.Opcodes.*;
067    
068    public abstract class MemberCodegen<T extends JetElement/* TODO: & JetDeclarationContainer*/> {
069        protected final GenerationState state;
070        protected final T element;
071        protected final FieldOwnerContext context;
072        protected final ClassBuilder v;
073        protected final FunctionCodegen functionCodegen;
074        protected final PropertyCodegen propertyCodegen;
075        protected final JetTypeMapper typeMapper;
076        protected final BindingContext bindingContext;
077        private final MemberCodegen<?> parentCodegen;
078        private final ReifiedTypeParametersUsages reifiedTypeParametersUsages = new ReifiedTypeParametersUsages();
079        protected final Collection<ClassDescriptor> innerClasses = new LinkedHashSet<ClassDescriptor>();
080    
081        protected ExpressionCodegen clInit;
082        private NameGenerator inlineNameGenerator;
083    
084        public MemberCodegen(
085                @NotNull GenerationState state,
086                @Nullable MemberCodegen<?> parentCodegen,
087                @NotNull FieldOwnerContext context,
088                T element,
089                @NotNull ClassBuilder builder
090        ) {
091            this.state = state;
092            this.typeMapper = state.getTypeMapper();
093            this.bindingContext = state.getBindingContext();
094            this.element = element;
095            this.context = context;
096            this.v = builder;
097            this.functionCodegen = new FunctionCodegen(context, v, state, this);
098            this.propertyCodegen = new PropertyCodegen(context, v, functionCodegen, this);
099            this.parentCodegen = parentCodegen;
100        }
101    
102        protected MemberCodegen(@NotNull MemberCodegen<T> wrapped) {
103            this(wrapped.state, wrapped.getParentCodegen(), wrapped.getContext(), wrapped.element, wrapped.v);
104        }
105    
106        public void generate() {
107            generateDeclaration();
108    
109            generateBody();
110    
111            generateSyntheticParts();
112    
113            generateKotlinAnnotation();
114    
115            done();
116        }
117    
118        protected abstract void generateDeclaration();
119    
120        protected abstract void generateBody();
121    
122        protected void generateSyntheticParts() {
123        }
124    
125        protected abstract void generateKotlinAnnotation();
126    
127        @Nullable
128        protected ClassDescriptor classForInnerClassRecord() {
129            return null;
130        }
131    
132        protected void done() {
133            if (clInit != null) {
134                clInit.v.visitInsn(RETURN);
135                FunctionCodegen.endVisit(clInit.v, "static initializer", element);
136            }
137    
138            writeInnerClasses();
139    
140            v.done();
141        }
142    
143        public void genFunctionOrProperty(@NotNull JetDeclaration functionOrProperty) {
144            if (functionOrProperty instanceof JetNamedFunction) {
145                try {
146                    functionCodegen.gen((JetNamedFunction) functionOrProperty);
147                }
148                catch (ProcessCanceledException e) {
149                    throw e;
150                }
151                catch (CompilationException e) {
152                    throw e;
153                }
154                catch (Exception e) {
155                    throw new CompilationException("Failed to generate function " + functionOrProperty.getName(), e, functionOrProperty);
156                }
157            }
158            else if (functionOrProperty instanceof JetProperty) {
159                try {
160                    propertyCodegen.gen((JetProperty) functionOrProperty);
161                }
162                catch (ProcessCanceledException e) {
163                    throw e;
164                }
165                catch (CompilationException e) {
166                    throw e;
167                }
168                catch (Exception e) {
169                    throw new CompilationException("Failed to generate property " + functionOrProperty.getName(), e, functionOrProperty);
170                }
171            }
172            else {
173                throw new IllegalArgumentException("Unknown parameter: " + functionOrProperty);
174            }
175        }
176    
177        public static void genClassOrObject(
178                @NotNull CodegenContext parentContext,
179                @NotNull JetClassOrObject aClass,
180                @NotNull GenerationState state,
181                @Nullable MemberCodegen<?> parentCodegen
182        ) {
183            ClassDescriptor descriptor = state.getBindingContext().get(BindingContext.CLASS, aClass);
184    
185            if (descriptor == null || ErrorUtils.isError(descriptor)) {
186                badDescriptor(descriptor, state.getClassBuilderMode());
187                return;
188            }
189    
190            if (descriptor.getName().equals(SpecialNames.NO_NAME_PROVIDED)) {
191                badDescriptor(descriptor, state.getClassBuilderMode());
192            }
193    
194            Type classType = state.getTypeMapper().mapClass(descriptor);
195            ClassBuilder classBuilder = state.getFactory().newVisitor(OtherOrigin(aClass, descriptor), classType, aClass.getContainingFile());
196            ClassContext classContext = parentContext.intoClass(descriptor, OwnerKind.IMPLEMENTATION, state);
197            new ImplementationBodyCodegen(aClass, classContext, classBuilder, state, parentCodegen).generate();
198    
199            if (aClass instanceof JetClass && ((JetClass) aClass).isTrait()) {
200                Type traitImplType = state.getTypeMapper().mapTraitImpl(descriptor);
201                ClassBuilder traitImplBuilder = state.getFactory().newVisitor(TraitImpl(aClass, descriptor), traitImplType, aClass.getContainingFile());
202                ClassContext traitImplContext = parentContext.intoClass(descriptor, OwnerKind.TRAIT_IMPL, state);
203                new TraitImplBodyCodegen(aClass, traitImplContext, traitImplBuilder, state, parentCodegen).generate();
204            }
205        }
206    
207        private static void badDescriptor(ClassDescriptor descriptor, ClassBuilderMode mode) {
208            if (mode != ClassBuilderMode.LIGHT_CLASSES) {
209                throw new IllegalStateException("Generating bad descriptor in ClassBuilderMode = " + mode + ": " + descriptor);
210            }
211        }
212    
213        public void genClassOrObject(JetClassOrObject aClass) {
214            genClassOrObject(context, aClass, state, this);
215        }
216    
217        private void writeInnerClasses() {
218            // JVMS7 (4.7.6): a nested class or interface member will have InnerClasses information
219            // for each enclosing class and for each immediate member
220            ClassDescriptor classDescriptor = classForInnerClassRecord();
221            if (classDescriptor != null) {
222                if (parentCodegen != null) {
223                    parentCodegen.innerClasses.add(classDescriptor);
224                }
225    
226                for (MemberCodegen<?> codegen = this; codegen != null; codegen = codegen.getParentCodegen()) {
227                    ClassDescriptor outerClass = codegen.classForInnerClassRecord();
228                    if (outerClass != null) {
229                        innerClasses.add(outerClass);
230                    }
231                }
232            }
233    
234            for (ClassDescriptor innerClass : innerClasses) {
235                writeInnerClass(innerClass);
236            }
237        }
238    
239        private void writeInnerClass(@NotNull ClassDescriptor innerClass) {
240            DeclarationDescriptor containing = innerClass.getContainingDeclaration();
241            String outerClassInternalName =
242                    containing instanceof ClassDescriptor ? typeMapper.mapClass((ClassDescriptor) containing).getInternalName() : null;
243    
244            String innerName = innerClass.getName().isSpecial() ? null : innerClass.getName().asString();
245    
246            String innerClassInternalName = typeMapper.mapClass(innerClass).getInternalName();
247            v.visitInnerClass(innerClassInternalName, outerClassInternalName, innerName, calculateInnerClassAccessFlags(innerClass));
248        }
249    
250        protected void writeOuterClassAndEnclosingMethod() {
251            CodegenContext context = this.context.getParentContext();
252            while (context instanceof MethodContext && ((MethodContext) context).isInliningLambda()) {
253                // If this is a lambda which will be inlined, skip its MethodContext and enclosing ClosureContext
254                //noinspection ConstantConditions
255                context = context.getParentContext().getParentContext();
256            }
257            assert context != null : "Outermost context can't be null: " + this.context;
258    
259            Type enclosingAsmType = computeOuterClass(context);
260            if (enclosingAsmType != null) {
261                Method method = computeEnclosingMethod(context);
262    
263                v.visitOuterClass(
264                        enclosingAsmType.getInternalName(),
265                        method == null ? null : method.getName(),
266                        method == null ? null : method.getDescriptor()
267                );
268            }
269        }
270    
271        @Nullable
272        private Type computeOuterClass(@NotNull CodegenContext<?> context) {
273            CodegenContext<? extends ClassOrPackageFragmentDescriptor> outermost = context.getClassOrPackageParentContext();
274            if (outermost instanceof ClassContext) {
275                return typeMapper.mapType(((ClassContext) outermost).getContextDescriptor());
276            }
277            else if (outermost instanceof PackageContext && !(outermost instanceof PackageFacadeContext)) {
278                return PackagePartClassUtils.getPackagePartType(element.getContainingJetFile());
279            }
280            return null;
281        }
282    
283        @Nullable
284        private Method computeEnclosingMethod(@NotNull CodegenContext context) {
285            if (context instanceof MethodContext) {
286                Method method = typeMapper.mapSignature(((MethodContext) context).getFunctionDescriptor()).getAsmMethod();
287                if (!method.getName().equals("<clinit>")) {
288                    return method;
289                }
290            }
291            return null;
292        }
293    
294        @NotNull
295        public NameGenerator getInlineNameGenerator() {
296            if (inlineNameGenerator == null) {
297                String prefix = InlineCodegenUtil.getInlineName(context, typeMapper);
298                inlineNameGenerator = new NameGenerator(prefix);
299            }
300            return inlineNameGenerator;
301        }
302    
303        @NotNull
304        protected ExpressionCodegen createOrGetClInitCodegen() {
305            DeclarationDescriptor descriptor = context.getContextDescriptor();
306            if (clInit == null) {
307                MethodVisitor mv = v.newMethod(OtherOrigin(descriptor), ACC_STATIC, "<clinit>", "()V", null, null);
308                SimpleFunctionDescriptorImpl clInit =
309                        SimpleFunctionDescriptorImpl.create(descriptor, Annotations.EMPTY, Name.special("<clinit>"), SYNTHESIZED, NO_SOURCE);
310                clInit.initialize(null, null, Collections.<TypeParameterDescriptor>emptyList(),
311                                  Collections.<ValueParameterDescriptor>emptyList(),
312                                  DescriptorUtilPackage.getModule(descriptor).getBuiltIns().getUnitType(),
313                                  null, Visibilities.PRIVATE);
314    
315                this.clInit = new ExpressionCodegen(mv, new FrameMap(), Type.VOID_TYPE, context.intoFunction(clInit), state, this);
316            }
317            return clInit;
318        }
319    
320        protected void generateInitializers(@NotNull Function0<ExpressionCodegen> createCodegen) {
321            NotNullLazyValue<ExpressionCodegen> codegen = LockBasedStorageManager.NO_LOCKS.createLazyValue(createCodegen);
322            for (JetDeclaration declaration : ((JetDeclarationContainer) element).getDeclarations()) {
323                if (declaration instanceof JetProperty) {
324                    if (shouldInitializeProperty((JetProperty) declaration)) {
325                        initializeProperty(codegen.invoke(), (JetProperty) declaration);
326                    }
327                }
328                else if (declaration instanceof JetClassInitializer) {
329                    codegen.invoke().gen(((JetClassInitializer) declaration).getBody(), Type.VOID_TYPE);
330                }
331            }
332        }
333    
334        private void initializeProperty(@NotNull ExpressionCodegen codegen, @NotNull JetProperty property) {
335            PropertyDescriptor propertyDescriptor = (PropertyDescriptor) bindingContext.get(VARIABLE, property);
336            assert propertyDescriptor != null;
337    
338            JetExpression initializer = property.getDelegateExpressionOrInitializer();
339            assert initializer != null : "shouldInitializeProperty must return false if initializer is null";
340    
341            StackValue.Property propValue = codegen.intermediateValueForProperty(propertyDescriptor, true, null, MethodKind.INITIALIZER,
342                                                                                 StackValue.LOCAL_0);
343    
344            propValue.store(codegen.gen(initializer), codegen.v);
345    
346            ResolvedCall<FunctionDescriptor> pdResolvedCall =
347                    bindingContext.get(BindingContext.DELEGATED_PROPERTY_PD_RESOLVED_CALL, propertyDescriptor);
348            if (pdResolvedCall != null) {
349                int index = PropertyCodegen.indexOfDelegatedProperty(property);
350                StackValue lastValue = PropertyCodegen.invokeDelegatedPropertyConventionMethod(
351                        propertyDescriptor, codegen, typeMapper, pdResolvedCall, index, 0
352                );
353                lastValue.put(Type.VOID_TYPE, codegen.v);
354            }
355        }
356    
357        private boolean shouldInitializeProperty(@NotNull JetProperty property) {
358            if (!property.hasDelegateExpressionOrInitializer()) return false;
359    
360            PropertyDescriptor propertyDescriptor = (PropertyDescriptor) bindingContext.get(VARIABLE, property);
361            assert propertyDescriptor != null;
362    
363            JetExpression initializer = property.getInitializer();
364    
365            CompileTimeConstant<?> initializerValue;
366            if (property.isVar() && initializer != null) {
367                BindingTrace tempTrace = TemporaryBindingTrace.create(state.getBindingTrace(), "property initializer");
368                initializerValue = ConstantExpressionEvaluator.evaluate(initializer, tempTrace, propertyDescriptor.getType());
369            }
370            else {
371                initializerValue = propertyDescriptor.getCompileTimeInitializer();
372            }
373            // we must write constant values for fields in light classes,
374            // because Java's completion for annotation arguments uses this information
375            if (initializerValue == null) return state.getClassBuilderMode() != ClassBuilderMode.LIGHT_CLASSES;
376    
377            //TODO: OPTIMIZATION: don't initialize static final fields
378    
379            Object value = initializerValue instanceof IntegerValueTypeConstant
380                ? ((IntegerValueTypeConstant) initializerValue).getValue(propertyDescriptor.getType())
381                : initializerValue.getValue();
382            JetType jetType = getPropertyOrDelegateType(property, propertyDescriptor);
383            Type type = typeMapper.mapType(jetType);
384            return !skipDefaultValue(propertyDescriptor, value, type);
385        }
386    
387        @NotNull
388        private JetType getPropertyOrDelegateType(@NotNull JetProperty property, @NotNull PropertyDescriptor descriptor) {
389            JetExpression delegateExpression = property.getDelegateExpression();
390            if (delegateExpression != null) {
391                JetType delegateType = bindingContext.get(BindingContext.EXPRESSION_TYPE, delegateExpression);
392                assert delegateType != null : "Type of delegate expression should be recorded";
393                return delegateType;
394            }
395            return descriptor.getType();
396        }
397    
398        private static boolean skipDefaultValue(@NotNull PropertyDescriptor propertyDescriptor, Object value, @NotNull Type type) {
399            if (isPrimitive(type)) {
400                if (!propertyDescriptor.getType().isMarkedNullable() && value instanceof Number) {
401                    if (type == Type.INT_TYPE && ((Number) value).intValue() == 0) {
402                        return true;
403                    }
404                    if (type == Type.BYTE_TYPE && ((Number) value).byteValue() == 0) {
405                        return true;
406                    }
407                    if (type == Type.LONG_TYPE && ((Number) value).longValue() == 0L) {
408                        return true;
409                    }
410                    if (type == Type.SHORT_TYPE && ((Number) value).shortValue() == 0) {
411                        return true;
412                    }
413                    if (type == Type.DOUBLE_TYPE && ((Number) value).doubleValue() == 0d) {
414                        return true;
415                    }
416                    if (type == Type.FLOAT_TYPE && ((Number) value).floatValue() == 0f) {
417                        return true;
418                    }
419                }
420                if (type == Type.BOOLEAN_TYPE && value instanceof Boolean && !((Boolean) value)) {
421                    return true;
422                }
423                if (type == Type.CHAR_TYPE && value instanceof Character && ((Character) value) == 0) {
424                    return true;
425                }
426            }
427            else {
428                if (value == null) {
429                    return true;
430                }
431            }
432            return false;
433        }
434    
435        public static void generateReflectionObjectField(
436                @NotNull GenerationState state,
437                @NotNull Type thisAsmType,
438                @NotNull ClassBuilder classBuilder,
439                @NotNull Method factory,
440                @NotNull String fieldName,
441                @NotNull InstructionAdapter v
442        ) {
443            String type = factory.getReturnType().getDescriptor();
444            // TODO: generic signature
445            classBuilder.newField(NO_ORIGIN, ACC_PUBLIC | ACC_STATIC | ACC_FINAL | ACC_SYNTHETIC, fieldName, type, null, null);
446    
447            if (state.getClassBuilderMode() == ClassBuilderMode.LIGHT_CLASSES) return;
448    
449            v.aconst(thisAsmType);
450            v.invokestatic(REFLECTION, factory.getName(), factory.getDescriptor(), false);
451            v.putstatic(thisAsmType.getInternalName(), fieldName, type);
452        }
453    
454        protected void generatePropertyMetadataArrayFieldIfNeeded(@NotNull Type thisAsmType) {
455            List<JetProperty> delegatedProperties = new ArrayList<JetProperty>();
456            for (JetDeclaration declaration : ((JetDeclarationContainer) element).getDeclarations()) {
457                if (declaration instanceof JetProperty) {
458                    JetProperty property = (JetProperty) declaration;
459                    if (property.hasDelegate()) {
460                        delegatedProperties.add(property);
461                    }
462                }
463            }
464            if (delegatedProperties.isEmpty()) return;
465    
466            v.newField(NO_ORIGIN, ACC_PRIVATE | ACC_STATIC | ACC_FINAL | ACC_SYNTHETIC, JvmAbi.PROPERTY_METADATA_ARRAY_NAME,
467                       "[" + PROPERTY_METADATA_TYPE, null, null);
468    
469            if (state.getClassBuilderMode() == ClassBuilderMode.LIGHT_CLASSES) return;
470    
471            InstructionAdapter iv = createOrGetClInitCodegen().v;
472            iv.iconst(delegatedProperties.size());
473            iv.newarray(PROPERTY_METADATA_TYPE);
474    
475            for (int i = 0, size = delegatedProperties.size(); i < size; i++) {
476                VariableDescriptor property = BindingContextUtils.getNotNull(bindingContext, VARIABLE, delegatedProperties.get(i));
477    
478                iv.dup();
479                iv.iconst(i);
480                iv.anew(PROPERTY_METADATA_IMPL_TYPE);
481                iv.dup();
482                iv.visitLdcInsn(property.getName().asString());
483                iv.invokespecial(PROPERTY_METADATA_IMPL_TYPE.getInternalName(), "<init>", "(Ljava/lang/String;)V", false);
484                iv.astore(PROPERTY_METADATA_IMPL_TYPE);
485            }
486    
487            iv.putstatic(thisAsmType.getInternalName(), JvmAbi.PROPERTY_METADATA_ARRAY_NAME, "[" + PROPERTY_METADATA_TYPE);
488        }
489    
490        public String getClassName() {
491            return v.getThisName();
492        }
493    
494        @NotNull
495        public FieldOwnerContext<?> getContext() {
496            return context;
497        }
498    
499        @NotNull
500        public ReifiedTypeParametersUsages getReifiedTypeParametersUsages() {
501            return reifiedTypeParametersUsages;
502        }
503    
504        public MemberCodegen<?> getParentCodegen() {
505            return parentCodegen;
506        }
507    
508        @Override
509        public String toString() {
510            return context.toString();
511        }
512    }