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