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