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.util.Pair;
020    import com.intellij.psi.PsiElement;
021    import org.jetbrains.annotations.NotNull;
022    import org.jetbrains.annotations.Nullable;
023    import org.jetbrains.kotlin.codegen.annotation.AnnotatedSimple;
024    import org.jetbrains.kotlin.codegen.annotation.AnnotatedWithFakeAnnotations;
025    import org.jetbrains.kotlin.codegen.context.*;
026    import org.jetbrains.kotlin.codegen.state.GenerationState;
027    import org.jetbrains.kotlin.codegen.state.JetTypeMapper;
028    import org.jetbrains.kotlin.descriptors.*;
029    import org.jetbrains.kotlin.descriptors.annotations.Annotated;
030    import org.jetbrains.kotlin.descriptors.annotations.AnnotationSplitter;
031    import org.jetbrains.kotlin.descriptors.annotations.AnnotationUseSiteTarget;
032    import org.jetbrains.kotlin.descriptors.annotations.Annotations;
033    import org.jetbrains.kotlin.load.java.JvmAbi;
034    import org.jetbrains.kotlin.psi.*;
035    import org.jetbrains.kotlin.psi.psiUtil.PsiUtilsKt;
036    import org.jetbrains.kotlin.resolve.BindingContext;
037    import org.jetbrains.kotlin.resolve.DescriptorFactory;
038    import org.jetbrains.kotlin.resolve.DescriptorToSourceUtils;
039    import org.jetbrains.kotlin.resolve.annotations.AnnotationUtilKt;
040    import org.jetbrains.kotlin.resolve.calls.model.ResolvedCall;
041    import org.jetbrains.kotlin.resolve.constants.ConstantValue;
042    import org.jetbrains.kotlin.resolve.jvm.diagnostics.JvmDeclarationOriginKt;
043    import org.jetbrains.kotlin.resolve.jvm.jvmSignature.JvmMethodSignature;
044    import org.jetbrains.kotlin.serialization.deserialization.descriptors.DeserializedPropertyDescriptor;
045    import org.jetbrains.kotlin.storage.LockBasedStorageManager;
046    import org.jetbrains.kotlin.types.ErrorUtils;
047    import org.jetbrains.kotlin.types.KotlinType;
048    import org.jetbrains.org.objectweb.asm.FieldVisitor;
049    import org.jetbrains.org.objectweb.asm.MethodVisitor;
050    import org.jetbrains.org.objectweb.asm.Opcodes;
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.List;
056    
057    import static org.jetbrains.kotlin.codegen.AsmUtil.*;
058    import static org.jetbrains.kotlin.codegen.JvmCodegenUtil.isJvmInterface;
059    import static org.jetbrains.kotlin.codegen.serialization.JvmSerializationBindings.*;
060    import static org.jetbrains.kotlin.resolve.DescriptorUtils.*;
061    import static org.jetbrains.kotlin.resolve.jvm.AsmTypes.PROPERTY_METADATA_TYPE;
062    import static org.jetbrains.kotlin.resolve.jvm.annotations.AnnotationUtilKt.hasJvmFieldAnnotation;
063    import static org.jetbrains.org.objectweb.asm.Opcodes.*;
064    
065    public class PropertyCodegen {
066        private final GenerationState state;
067        private final ClassBuilder v;
068        private final FunctionCodegen functionCodegen;
069        private final JetTypeMapper typeMapper;
070        private final BindingContext bindingContext;
071        private final FieldOwnerContext context;
072        private final MemberCodegen<?> memberCodegen;
073        private final OwnerKind kind;
074    
075        public PropertyCodegen(
076                @NotNull FieldOwnerContext context,
077                @NotNull ClassBuilder v,
078                @NotNull FunctionCodegen functionCodegen,
079                @NotNull MemberCodegen<?> memberCodegen
080        ) {
081            this.state = functionCodegen.state;
082            this.v = v;
083            this.functionCodegen = functionCodegen;
084            this.typeMapper = state.getTypeMapper();
085            this.bindingContext = state.getBindingContext();
086            this.context = context;
087            this.memberCodegen = memberCodegen;
088            this.kind = context.getContextKind();
089        }
090    
091        public void gen(@NotNull KtProperty property) {
092            VariableDescriptor variableDescriptor = bindingContext.get(BindingContext.VARIABLE, property);
093            assert variableDescriptor instanceof PropertyDescriptor : "Property " + property.getText() + " should have a property descriptor: " + variableDescriptor;
094    
095            PropertyDescriptor propertyDescriptor = (PropertyDescriptor) variableDescriptor;
096            gen(property, propertyDescriptor, property.getGetter(), property.getSetter());
097        }
098    
099        public void generateInPackageFacade(@NotNull DeserializedPropertyDescriptor deserializedProperty) {
100            assert context instanceof DelegatingFacadeContext : "should be called only for generating facade: " + context;
101            gen(null, deserializedProperty, null, null);
102        }
103    
104        private void gen(
105                @Nullable KtProperty declaration,
106                @NotNull PropertyDescriptor descriptor,
107                @Nullable KtPropertyAccessor getter,
108                @Nullable KtPropertyAccessor setter
109        ) {
110            assert kind == OwnerKind.PACKAGE || kind == OwnerKind.IMPLEMENTATION || kind == OwnerKind.DEFAULT_IMPLS
111                    : "Generating property with a wrong kind (" + kind + "): " + descriptor;
112    
113            String implClassName = CodegenContextUtil.getImplementationClassShortName(context);
114            if (implClassName != null) {
115                v.getSerializationBindings().put(IMPL_CLASS_NAME_FOR_CALLABLE, descriptor, implClassName);
116            }
117    
118            if (CodegenContextUtil.isImplClassOwner(context)) {
119                assert declaration != null : "Declaration is null for different context: " + context;
120    
121                boolean hasBackingField = hasBackingField(declaration, descriptor);
122    
123                AnnotationSplitter annotationSplitter = AnnotationSplitter.create(LockBasedStorageManager.NO_LOCKS,
124                        descriptor.getAnnotations(), AnnotationSplitter.getTargetSet(false, descriptor.isVar(), hasBackingField));
125    
126                Annotations fieldAnnotations = annotationSplitter.getAnnotationsForTarget(AnnotationUseSiteTarget.FIELD);
127                Annotations propertyAnnotations = annotationSplitter.getAnnotationsForTarget(AnnotationUseSiteTarget.PROPERTY);
128    
129                generateBackingField(declaration, descriptor, fieldAnnotations);
130                generateSyntheticMethodIfNeeded(descriptor, propertyAnnotations);
131            }
132    
133            if (isAccessorNeeded(declaration, descriptor, getter)) {
134                generateGetter(declaration, descriptor, getter);
135            }
136            if (isAccessorNeeded(declaration, descriptor, setter)) {
137                generateSetter(declaration, descriptor, setter);
138            }
139    
140            context.recordSyntheticAccessorIfNeeded(descriptor, bindingContext);
141        }
142    
143        /**
144         * Determines if it's necessary to generate an accessor to the property, i.e. if this property can be referenced via getter/setter
145         * for any reason
146         *
147         * @see JvmCodegenUtil#couldUseDirectAccessToProperty
148         */
149        private boolean isAccessorNeeded(
150                @Nullable KtProperty declaration,
151                @NotNull PropertyDescriptor descriptor,
152                @Nullable KtPropertyAccessor accessor
153        ) {
154            if (hasJvmFieldAnnotation(descriptor)) return false;
155    
156            boolean isDefaultAccessor = accessor == null || !accessor.hasBody();
157    
158            // Don't generate accessors for interface properties with default accessors in DefaultImpls
159            if (kind == OwnerKind.DEFAULT_IMPLS && isDefaultAccessor) return false;
160    
161            if (declaration == null) return true;
162    
163            // Delegated or extension properties can only be referenced via accessors
164            if (declaration.hasDelegate() || declaration.getReceiverTypeReference() != null) return true;
165    
166            // Companion object properties always should have accessors, because their backing fields are moved/copied to the outer class
167            if (isCompanionObject(descriptor.getContainingDeclaration())) return true;
168    
169            // Private class properties have accessors only in cases when those accessors are non-trivial
170            if (Visibilities.isPrivate(descriptor.getVisibility())) {
171                return !isDefaultAccessor;
172            }
173    
174            return true;
175        }
176    
177        public void generatePrimaryConstructorProperty(KtParameter p, PropertyDescriptor descriptor) {
178            AnnotationSplitter annotationSplitter = AnnotationSplitter.create(LockBasedStorageManager.NO_LOCKS,
179                    descriptor.getAnnotations(), AnnotationSplitter.getTargetSet(true, descriptor.isVar(), hasBackingField(p, descriptor)));
180    
181            Annotations fieldAnnotations = annotationSplitter.getAnnotationsForTarget(AnnotationUseSiteTarget.FIELD);
182            Annotations propertyAnnotations = annotationSplitter.getAnnotationsForTarget(AnnotationUseSiteTarget.PROPERTY);
183    
184            generateBackingField(p, descriptor, fieldAnnotations);
185            generateSyntheticMethodIfNeeded(descriptor, propertyAnnotations);
186    
187            if (!Visibilities.isPrivate(descriptor.getVisibility())) {
188                generateGetter(p, descriptor, null);
189                if (descriptor.isVar()) {
190                    generateSetter(p, descriptor, null);
191                }
192            }
193        }
194    
195        public void generateConstructorPropertyAsMethodForAnnotationClass(KtParameter p, PropertyDescriptor descriptor) {
196            JvmMethodSignature signature = typeMapper.mapAnnotationParameterSignature(descriptor);
197            String name = p.getName();
198            if (name == null) return;
199            MethodVisitor mv = v.newMethod(
200                    JvmDeclarationOriginKt.OtherOrigin(p, descriptor), ACC_PUBLIC | ACC_ABSTRACT, name,
201                    signature.getAsmMethod().getDescriptor(),
202                    signature.getGenericsSignature(),
203                    null
204            );
205    
206            if (state.getClassBuilderMode() == ClassBuilderMode.FULL) {
207                KtExpression defaultValue = p.getDefaultValue();
208                if (defaultValue != null) {
209                    ConstantValue<?> constant = ExpressionCodegen.getCompileTimeConstant(defaultValue, bindingContext);
210                    assert constant != null : "Default value for annotation parameter should be compile time value: " + defaultValue.getText();
211                    AnnotationCodegen annotationCodegen = AnnotationCodegen.forAnnotationDefaultValue(mv, typeMapper);
212                    annotationCodegen.generateAnnotationDefaultValue(constant, descriptor.getType());
213                }
214            }
215    
216            mv.visitEnd();
217        }
218    
219        private boolean hasBackingField(@NotNull KtNamedDeclaration p, @NotNull PropertyDescriptor descriptor) {
220            return !isJvmInterface(descriptor.getContainingDeclaration()) &&
221                   kind != OwnerKind.DEFAULT_IMPLS &&
222                   !Boolean.FALSE.equals(bindingContext.get(BindingContext.BACKING_FIELD_REQUIRED, descriptor));
223        }
224    
225        private boolean generateBackingField(
226                @NotNull KtNamedDeclaration p,
227                @NotNull PropertyDescriptor descriptor,
228                @NotNull Annotations annotations
229        ) {
230            if (isJvmInterface(descriptor.getContainingDeclaration()) || kind == OwnerKind.DEFAULT_IMPLS) {
231                return false;
232            }
233    
234            if (p instanceof KtProperty && ((KtProperty) p).hasDelegate()) {
235                generatePropertyDelegateAccess((KtProperty) p, descriptor, annotations);
236            }
237            else if (Boolean.TRUE.equals(bindingContext.get(BindingContext.BACKING_FIELD_REQUIRED, descriptor))) {
238                generateBackingFieldAccess(p, descriptor, annotations);
239            }
240            else {
241                return false;
242            }
243            return true;
244        }
245    
246        // Annotations on properties are stored in bytecode on an empty synthetic method. This way they're still
247        // accessible via reflection, and 'deprecated' and 'private' flags prevent this method from being called accidentally
248        private void generateSyntheticMethodIfNeeded(@NotNull PropertyDescriptor descriptor, Annotations annotations) {
249            if (annotations.getAllAnnotations().isEmpty()) return;
250    
251            ReceiverParameterDescriptor receiver = descriptor.getExtensionReceiverParameter();
252            String name = JvmAbi.getSyntheticMethodNameForAnnotatedProperty(descriptor.getName());
253            String desc = receiver == null ? "()V" : "(" + typeMapper.mapType(receiver.getType()) + ")V";
254    
255            if (!isInterface(context.getContextDescriptor()) || kind == OwnerKind.DEFAULT_IMPLS) {
256                int flags = ACC_DEPRECATED | ACC_FINAL | ACC_PRIVATE | ACC_STATIC | ACC_SYNTHETIC;
257                MethodVisitor mv = v.newMethod(JvmDeclarationOriginKt.OtherOrigin(descriptor), flags, name, desc, null, null);
258                AnnotationCodegen.forMethod(mv, typeMapper)
259                        .genAnnotations(new AnnotatedSimple(annotations), Type.VOID_TYPE, AnnotationUseSiteTarget.PROPERTY);
260                mv.visitCode();
261                mv.visitInsn(Opcodes.RETURN);
262                mv.visitEnd();
263            }
264            else {
265                Type tImplType = typeMapper.mapDefaultImpls((ClassDescriptor) context.getContextDescriptor());
266                v.getSerializationBindings().put(IMPL_CLASS_NAME_FOR_CALLABLE, descriptor, shortNameByAsmType(tImplType));
267            }
268    
269            if (kind != OwnerKind.DEFAULT_IMPLS) {
270                v.getSerializationBindings().put(SYNTHETIC_METHOD_FOR_PROPERTY, descriptor, new Method(name, desc));
271            }
272        }
273    
274        private void generateBackingField(
275                KtNamedDeclaration element,
276                PropertyDescriptor propertyDescriptor,
277                boolean isDelegate,
278                KotlinType jetType,
279                Object defaultValue,
280                Annotations annotations
281        ) {
282            int modifiers = getDeprecatedAccessFlag(propertyDescriptor);
283    
284            for (AnnotationCodegen.JvmFlagAnnotation flagAnnotation : AnnotationCodegen.FIELD_FLAGS) {
285                if (flagAnnotation.hasAnnotation(propertyDescriptor.getOriginal())) {
286                    modifiers |= flagAnnotation.getJvmFlag();
287                }
288            }
289    
290            if (kind == OwnerKind.PACKAGE) {
291                modifiers |= ACC_STATIC;
292            }
293    
294            if (!propertyDescriptor.isLateInit() && (!propertyDescriptor.isVar() || isDelegate)) {
295                modifiers |= ACC_FINAL;
296            }
297    
298            if (AnnotationUtilKt.hasJvmSyntheticAnnotation(propertyDescriptor)) {
299                modifiers |= ACC_SYNTHETIC;
300            }
301    
302            Type type = typeMapper.mapType(jetType);
303    
304            ClassBuilder builder = v;
305    
306            boolean hasJvmFieldAnnotation = hasJvmFieldAnnotation(propertyDescriptor);
307    
308            FieldOwnerContext backingFieldContext = context;
309            boolean takeVisibilityFromDescriptor = propertyDescriptor.isLateInit() || propertyDescriptor.isConst();
310            if (AsmUtil.isInstancePropertyWithStaticBackingField(propertyDescriptor) ) {
311                modifiers |= ACC_STATIC;
312    
313                if (takeVisibilityFromDescriptor) {
314                    modifiers |= getVisibilityAccessFlag(propertyDescriptor);
315                }
316                else if (hasJvmFieldAnnotation && !isDelegate) {
317                    modifiers |= getDefaultVisibilityFlag(propertyDescriptor.getVisibility());
318                }
319                else {
320                    modifiers |= getVisibilityForSpecialPropertyBackingField(propertyDescriptor, isDelegate);
321                }
322    
323                if (AsmUtil.isPropertyWithBackingFieldInOuterClass(propertyDescriptor)) {
324                    ImplementationBodyCodegen codegen = (ImplementationBodyCodegen) memberCodegen.getParentCodegen();
325                    builder = codegen.v;
326                    backingFieldContext = codegen.context;
327                    v.getSerializationBindings().put(STATIC_FIELD_IN_OUTER_CLASS, propertyDescriptor);
328                }
329    
330                if (isObject(propertyDescriptor.getContainingDeclaration()) &&
331                    !hasJvmFieldAnnotation &&
332                    !propertyDescriptor.isConst() &&
333                    (modifiers & ACC_PRIVATE) == 0) {
334                    modifiers |= ACC_DEPRECATED;
335                }
336            }
337            else if (takeVisibilityFromDescriptor) {
338                modifiers |= getVisibilityAccessFlag(propertyDescriptor);
339            }
340            else if (!isDelegate && hasJvmFieldAnnotation) {
341                modifiers |= getDefaultVisibilityFlag(propertyDescriptor.getVisibility());
342            }
343            else {
344                modifiers |= ACC_PRIVATE;
345            }
346    
347            if (AsmUtil.isPropertyWithBackingFieldCopyInOuterClass(propertyDescriptor)) {
348                ImplementationBodyCodegen parentBodyCodegen = (ImplementationBodyCodegen) memberCodegen.getParentCodegen();
349                parentBodyCodegen.addCompanionObjectPropertyToCopy(propertyDescriptor, defaultValue);
350            }
351    
352            String name = backingFieldContext.getFieldName(propertyDescriptor, isDelegate);
353    
354            v.getSerializationBindings().put(FIELD_FOR_PROPERTY, propertyDescriptor, Pair.create(type, name));
355    
356            FieldVisitor fv = builder.newField(JvmDeclarationOriginKt.OtherOrigin(element, propertyDescriptor), modifiers, name, type.getDescriptor(),
357                                               typeMapper.mapFieldSignature(jetType), defaultValue);
358    
359            Annotated fieldAnnotated = new AnnotatedWithFakeAnnotations(propertyDescriptor, annotations);
360            AnnotationCodegen.forField(fv, typeMapper).genAnnotations(fieldAnnotated, type, AnnotationUseSiteTarget.FIELD);
361        }
362    
363        private void generatePropertyDelegateAccess(KtProperty p, PropertyDescriptor propertyDescriptor, Annotations annotations) {
364            KtExpression delegateExpression = p.getDelegateExpression();
365            KotlinType delegateType = delegateExpression != null ? bindingContext.getType(p.getDelegateExpression()) : null;
366            if (delegateType == null) {
367                // If delegate expression is unresolved reference
368                delegateType = ErrorUtils.createErrorType("Delegate type");
369            }
370    
371            generateBackingField(p, propertyDescriptor, true, delegateType, null, annotations);
372        }
373    
374        private void generateBackingFieldAccess(KtNamedDeclaration p, PropertyDescriptor propertyDescriptor, Annotations annotations) {
375            Object value = null;
376    
377            if (shouldWriteFieldInitializer(propertyDescriptor)) {
378                ConstantValue<?> initializer = propertyDescriptor.getCompileTimeInitializer();
379                if (initializer != null) {
380                    value = initializer.getValue();
381                }
382            }
383    
384            generateBackingField(p, propertyDescriptor, false, propertyDescriptor.getType(), value, annotations);
385        }
386    
387        private boolean shouldWriteFieldInitializer(@NotNull PropertyDescriptor descriptor) {
388            //final field of primitive or String type
389            if (!descriptor.isVar()) {
390                Type type = typeMapper.mapType(descriptor);
391                return AsmUtil.isPrimitive(type) || "java.lang.String".equals(type.getClassName());
392            }
393            return false;
394        }
395    
396        private void generateGetter(@Nullable KtNamedDeclaration p, @NotNull PropertyDescriptor descriptor, @Nullable KtPropertyAccessor getter) {
397            generateAccessor(p, getter, descriptor.getGetter() != null
398                                        ? descriptor.getGetter()
399                                        : DescriptorFactory.createDefaultGetter(descriptor, Annotations.Companion.getEMPTY()));
400        }
401    
402        private void generateSetter(@Nullable KtNamedDeclaration p, @NotNull PropertyDescriptor descriptor, @Nullable KtPropertyAccessor setter) {
403            if (!descriptor.isVar()) return;
404    
405            generateAccessor(p, setter, descriptor.getSetter() != null
406                                        ? descriptor.getSetter()
407                                        : DescriptorFactory.createDefaultSetter(descriptor, Annotations.Companion.getEMPTY()));
408        }
409    
410        private void generateAccessor(
411                @Nullable KtNamedDeclaration p,
412                @Nullable KtPropertyAccessor accessor,
413                @NotNull PropertyAccessorDescriptor accessorDescriptor
414        ) {
415            if (context instanceof MultifileClassFacadeContext && Visibilities.isPrivate(accessorDescriptor.getVisibility())) {
416                return;
417            }
418    
419            FunctionGenerationStrategy strategy;
420            if (accessor == null || !accessor.hasBody()) {
421                if (p instanceof KtProperty && ((KtProperty) p).hasDelegate()) {
422                    strategy = new DelegatedPropertyAccessorStrategy(state, accessorDescriptor, indexOfDelegatedProperty((KtProperty) p));
423                }
424                else {
425                    strategy = new DefaultPropertyAccessorStrategy(state, accessorDescriptor);
426                }
427            }
428            else {
429                strategy = new FunctionGenerationStrategy.FunctionDefault(state, accessorDescriptor, accessor);
430            }
431    
432            functionCodegen.generateMethod(JvmDeclarationOriginKt.OtherOrigin(accessor != null ? accessor : p, accessorDescriptor), accessorDescriptor, strategy);
433        }
434    
435        public static int indexOfDelegatedProperty(@NotNull KtProperty property) {
436            PsiElement parent = property.getParent();
437            KtDeclarationContainer container;
438            if (parent instanceof KtClassBody) {
439                container = ((KtClassOrObject) parent.getParent());
440            }
441            else if (parent instanceof KtFile) {
442                container = (KtFile) parent;
443            }
444            else {
445                throw new UnsupportedOperationException("Unknown delegated property container: " + parent);
446            }
447    
448            int index = 0;
449            for (KtDeclaration declaration : container.getDeclarations()) {
450                if (declaration instanceof KtProperty && ((KtProperty) declaration).hasDelegate()) {
451                    if (declaration == property) {
452                        return index;
453                    }
454                    index++;
455                }
456            }
457    
458            throw new IllegalStateException("Delegated property not found in its parent: " + PsiUtilsKt.getElementTextWithContext(property));
459        }
460    
461    
462        private static class DefaultPropertyAccessorStrategy extends FunctionGenerationStrategy.CodegenBased<PropertyAccessorDescriptor> {
463            public DefaultPropertyAccessorStrategy(@NotNull GenerationState state, @NotNull PropertyAccessorDescriptor descriptor) {
464                super(state, descriptor);
465            }
466    
467            @Override
468            public void doGenerateBody(@NotNull ExpressionCodegen codegen, @NotNull JvmMethodSignature signature) {
469                InstructionAdapter v = codegen.v;
470                PropertyDescriptor propertyDescriptor = callableDescriptor.getCorrespondingProperty();
471                StackValue property = codegen.intermediateValueForProperty(propertyDescriptor, true, null, StackValue.LOCAL_0);
472    
473                PsiElement jetProperty = DescriptorToSourceUtils.descriptorToDeclaration(propertyDescriptor);
474                if (jetProperty instanceof KtProperty || jetProperty instanceof KtParameter) {
475                    codegen.markLineNumber((KtElement) jetProperty, false);
476                }
477    
478                if (callableDescriptor instanceof PropertyGetterDescriptor) {
479                    Type type = signature.getReturnType();
480                    property.put(type, v);
481                    v.areturn(type);
482                }
483                else if (callableDescriptor instanceof PropertySetterDescriptor) {
484                    List<ValueParameterDescriptor> valueParameters = callableDescriptor.getValueParameters();
485                    assert valueParameters.size() == 1 : "Property setter should have only one value parameter but has " + callableDescriptor;
486                    int parameterIndex = codegen.lookupLocalIndex(valueParameters.get(0));
487                    assert parameterIndex >= 0 : "Local index for setter parameter should be positive or zero: " + callableDescriptor;
488                    Type type = codegen.typeMapper.mapType(propertyDescriptor);
489                    property.store(StackValue.local(parameterIndex, type), codegen.v);
490                    v.visitInsn(RETURN);
491                }
492                else {
493                    throw new IllegalStateException("Unknown property accessor: " + callableDescriptor);
494                }
495            }
496        }
497    
498        public static StackValue invokeDelegatedPropertyConventionMethod(
499                @NotNull PropertyDescriptor propertyDescriptor,
500                @NotNull ExpressionCodegen codegen,
501                @NotNull JetTypeMapper typeMapper,
502                @NotNull ResolvedCall<FunctionDescriptor> resolvedCall,
503                final int indexInPropertyMetadataArray,
504                int propertyMetadataArgumentIndex
505        ) {
506            CodegenContext<? extends ClassOrPackageFragmentDescriptor> ownerContext = codegen.getContext().getClassOrPackageParentContext();
507            final Type owner;
508            if (ownerContext instanceof ClassContext) {
509                owner = typeMapper.mapClass(((ClassContext) ownerContext).getContextDescriptor());
510            }
511            else if (ownerContext instanceof PackageContext) {
512                owner = ((PackageContext) ownerContext).getPackagePartType();
513            }
514            else if (ownerContext instanceof MultifileClassContextBase) {
515                owner = ((MultifileClassContextBase) ownerContext).getFilePartType();
516            }
517            else {
518                throw new UnsupportedOperationException("Unknown context: " + ownerContext);
519            }
520    
521            codegen.tempVariables.put(
522                    resolvedCall.getCall().getValueArguments().get(propertyMetadataArgumentIndex).asElement(),
523                    new StackValue(PROPERTY_METADATA_TYPE) {
524                        @Override
525                        public void putSelector(@NotNull Type type, @NotNull InstructionAdapter v) {
526                            Field array = StackValue
527                                    .field(Type.getType("[" + PROPERTY_METADATA_TYPE), owner, JvmAbi.DELEGATED_PROPERTIES_ARRAY_NAME, true,
528                                           StackValue.none());
529                            StackValue.arrayElement(PROPERTY_METADATA_TYPE, array, StackValue.constant(indexInPropertyMetadataArray, Type.INT_TYPE)).put(type, v);
530                        }
531                    }
532            );
533    
534            StackValue delegatedProperty = codegen.intermediateValueForProperty(propertyDescriptor, true, null, StackValue.LOCAL_0);
535            return codegen.invokeFunction(resolvedCall, delegatedProperty);
536        }
537    
538        private static class DelegatedPropertyAccessorStrategy extends FunctionGenerationStrategy.CodegenBased<PropertyAccessorDescriptor> {
539            private final int index;
540    
541            public DelegatedPropertyAccessorStrategy(@NotNull GenerationState state, @NotNull PropertyAccessorDescriptor descriptor, int index) {
542                super(state, descriptor);
543                this.index = index;
544            }
545    
546            @Override
547            public void doGenerateBody(@NotNull ExpressionCodegen codegen, @NotNull JvmMethodSignature signature) {
548                InstructionAdapter v = codegen.v;
549    
550                BindingContext bindingContext = state.getBindingContext();
551                ResolvedCall<FunctionDescriptor> resolvedCall =
552                        bindingContext.get(BindingContext.DELEGATED_PROPERTY_RESOLVED_CALL, callableDescriptor);
553                assert resolvedCall != null : "Resolve call should be recorded for delegate call " + signature.toString();
554    
555                StackValue lastValue = invokeDelegatedPropertyConventionMethod(callableDescriptor.getCorrespondingProperty(),
556                                                                               codegen, state.getTypeMapper(), resolvedCall, index, 1);
557                Type asmType = signature.getReturnType();
558                lastValue.put(asmType, v);
559                v.areturn(asmType);
560            }
561        }
562    
563        public void genDelegate(@NotNull PropertyDescriptor delegate, @NotNull PropertyDescriptor delegateTo, @NotNull StackValue field) {
564            ClassDescriptor toClass = (ClassDescriptor) delegateTo.getContainingDeclaration();
565    
566            PropertyGetterDescriptor getter = delegate.getGetter();
567            if (getter != null) {
568                //noinspection ConstantConditions
569                functionCodegen.genDelegate(getter, delegateTo.getGetter().getOriginal(), toClass, field);
570            }
571    
572            PropertySetterDescriptor setter = delegate.getSetter();
573            if (setter != null) {
574                //noinspection ConstantConditions
575                functionCodegen.genDelegate(setter, delegateTo.getSetter().getOriginal(), toClass, field);
576            }
577        }
578    }