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