001 /* 002 * Copyright 2010-2015 JetBrains s.r.o. 003 * 004 * Licensed under the Apache License, Version 2.0 (the "License"); 005 * you may not use this file except in compliance with the License. 006 * You may obtain a copy of the License at 007 * 008 * http://www.apache.org/licenses/LICENSE-2.0 009 * 010 * Unless required by applicable law or agreed to in writing, software 011 * distributed under the License is distributed on an "AS IS" BASIS, 012 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 013 * See the License for the specific language governing permissions and 014 * limitations under the License. 015 */ 016 017 package org.jetbrains.kotlin.codegen; 018 019 import com.intellij.openapi.progress.ProcessCanceledException; 020 import com.intellij.psi.PsiElement; 021 import kotlin.Unit; 022 import kotlin.jvm.functions.Function0; 023 import kotlin.jvm.functions.Function1; 024 import org.jetbrains.annotations.NotNull; 025 import org.jetbrains.annotations.Nullable; 026 import org.jetbrains.kotlin.backend.common.CodegenUtil; 027 import org.jetbrains.kotlin.codegen.context.*; 028 import org.jetbrains.kotlin.codegen.inline.*; 029 import org.jetbrains.kotlin.codegen.state.GenerationState; 030 import org.jetbrains.kotlin.codegen.state.JetTypeMapper; 031 import org.jetbrains.kotlin.descriptors.*; 032 import org.jetbrains.kotlin.descriptors.annotations.Annotations; 033 import org.jetbrains.kotlin.descriptors.impl.SimpleFunctionDescriptorImpl; 034 import org.jetbrains.kotlin.fileClasses.FileClasses; 035 import org.jetbrains.kotlin.fileClasses.JvmFileClassesProvider; 036 import org.jetbrains.kotlin.load.java.JavaVisibilities; 037 import org.jetbrains.kotlin.load.java.JvmAbi; 038 import org.jetbrains.kotlin.name.Name; 039 import org.jetbrains.kotlin.name.SpecialNames; 040 import org.jetbrains.kotlin.psi.*; 041 import org.jetbrains.kotlin.resolve.*; 042 import org.jetbrains.kotlin.resolve.annotations.AnnotationUtilKt; 043 import org.jetbrains.kotlin.resolve.constants.ConstantValue; 044 import org.jetbrains.kotlin.resolve.constants.evaluate.ConstantExpressionEvaluator; 045 import org.jetbrains.kotlin.resolve.descriptorUtil.DescriptorUtilsKt; 046 import org.jetbrains.kotlin.resolve.jvm.AsmTypes; 047 import org.jetbrains.kotlin.resolve.jvm.diagnostics.JvmDeclarationOriginKt; 048 import org.jetbrains.kotlin.resolve.jvm.jvmSignature.JvmMethodSignature; 049 import org.jetbrains.kotlin.resolve.scopes.receivers.ReceiverValue; 050 import org.jetbrains.kotlin.resolve.scopes.receivers.TransientReceiver; 051 import org.jetbrains.kotlin.resolve.source.KotlinSourceElementKt; 052 import org.jetbrains.kotlin.storage.LockBasedStorageManager; 053 import org.jetbrains.kotlin.storage.NotNullLazyValue; 054 import org.jetbrains.kotlin.types.ErrorUtils; 055 import org.jetbrains.kotlin.types.KotlinType; 056 import org.jetbrains.org.objectweb.asm.Label; 057 import org.jetbrains.org.objectweb.asm.MethodVisitor; 058 import org.jetbrains.org.objectweb.asm.Type; 059 import org.jetbrains.org.objectweb.asm.commons.InstructionAdapter; 060 import org.jetbrains.org.objectweb.asm.commons.Method; 061 062 import java.util.*; 063 064 import static org.jetbrains.kotlin.codegen.AsmUtil.calculateInnerClassAccessFlags; 065 import static org.jetbrains.kotlin.codegen.AsmUtil.isPrimitive; 066 import static org.jetbrains.kotlin.descriptors.CallableMemberDescriptor.Kind.SYNTHESIZED; 067 import static org.jetbrains.kotlin.resolve.BindingContext.VARIABLE; 068 import static org.jetbrains.kotlin.resolve.DescriptorUtils.isCompanionObject; 069 import static org.jetbrains.kotlin.resolve.DescriptorUtils.isStaticDeclaration; 070 import static org.jetbrains.kotlin.resolve.jvm.AsmTypes.*; 071 import static org.jetbrains.kotlin.resolve.jvm.diagnostics.JvmDeclarationOrigin.NO_ORIGIN; 072 import static org.jetbrains.kotlin.resolve.jvm.diagnostics.JvmDeclarationOriginKt.Synthetic; 073 import static org.jetbrains.org.objectweb.asm.Opcodes.*; 074 075 public abstract class MemberCodegen<T extends KtElement/* TODO: & JetDeclarationContainer*/> { 076 protected final GenerationState state; 077 protected final T element; 078 protected final FieldOwnerContext context; 079 protected final ClassBuilder v; 080 protected final FunctionCodegen functionCodegen; 081 protected final PropertyCodegen propertyCodegen; 082 protected final JetTypeMapper typeMapper; 083 protected final BindingContext bindingContext; 084 protected final JvmFileClassesProvider fileClassesProvider; 085 private final MemberCodegen<?> parentCodegen; 086 private final ReifiedTypeParametersUsages reifiedTypeParametersUsages = new ReifiedTypeParametersUsages(); 087 protected final Collection<ClassDescriptor> innerClasses = new LinkedHashSet<ClassDescriptor>(); 088 089 protected ExpressionCodegen clInit; 090 private NameGenerator inlineNameGenerator; 091 092 private SourceMapper sourceMapper; 093 private final ConstantExpressionEvaluator constantExpressionEvaluator; 094 095 public MemberCodegen( 096 @NotNull GenerationState state, 097 @Nullable MemberCodegen<?> parentCodegen, 098 @NotNull FieldOwnerContext context, 099 T element, 100 @NotNull ClassBuilder builder 101 ) { 102 this.state = state; 103 this.typeMapper = state.getTypeMapper(); 104 this.bindingContext = state.getBindingContext(); 105 this.fileClassesProvider = state.getFileClassesProvider(); 106 this.element = element; 107 this.context = context; 108 this.v = builder; 109 this.functionCodegen = new FunctionCodegen(context, v, state, this); 110 this.propertyCodegen = new PropertyCodegen(context, v, functionCodegen, this); 111 this.parentCodegen = parentCodegen; 112 this.constantExpressionEvaluator = new ConstantExpressionEvaluator(state.getModule().getBuiltIns()); 113 } 114 115 protected MemberCodegen(@NotNull MemberCodegen<T> wrapped, T declaration, FieldOwnerContext codegenContext) { 116 this(wrapped.state, wrapped.getParentCodegen(), codegenContext, declaration, wrapped.v); 117 } 118 119 public void generate() { 120 generateDeclaration(); 121 122 generateBody(); 123 124 generateSyntheticParts(); 125 126 if (state.getClassBuilderMode() == ClassBuilderMode.FULL) { 127 generateKotlinAnnotation(); 128 } 129 130 done(); 131 } 132 133 protected abstract void generateDeclaration(); 134 135 protected abstract void generateBody(); 136 137 protected void generateSyntheticParts() { 138 } 139 140 protected abstract void generateKotlinAnnotation(); 141 142 @Nullable 143 protected ClassDescriptor classForInnerClassRecord() { 144 return null; 145 } 146 147 public static void markLineNumberForDescriptor(@Nullable ClassDescriptor declarationDescriptor, @NotNull InstructionAdapter v) { 148 if (declarationDescriptor == null) { 149 return; 150 } 151 152 PsiElement classElement = DescriptorToSourceUtils.getSourceFromDescriptor(declarationDescriptor); 153 if (classElement != null) { 154 markLineNumberForElement(classElement, v); 155 } 156 } 157 158 public static void markLineNumberForElement(@NotNull PsiElement element, @NotNull InstructionAdapter v) { 159 Integer lineNumber = CodegenUtil.getLineNumberForElement(element, false); 160 if (lineNumber != null) { 161 Label label = new Label(); 162 v.visitLabel(label); 163 v.visitLineNumber(lineNumber, label); 164 } 165 } 166 167 protected void done() { 168 if (clInit != null) { 169 clInit.v.visitInsn(RETURN); 170 FunctionCodegen.endVisit(clInit.v, "static initializer", element); 171 } 172 173 writeInnerClasses(); 174 175 if (sourceMapper != null) { 176 SourceMapper.Companion.flushToClassBuilder(sourceMapper, v); 177 } 178 179 v.done(); 180 } 181 182 public void genFunctionOrProperty(@NotNull KtDeclaration functionOrProperty) { 183 if (functionOrProperty instanceof KtNamedFunction) { 184 try { 185 functionCodegen.gen((KtNamedFunction) functionOrProperty); 186 } 187 catch (ProcessCanceledException e) { 188 throw e; 189 } 190 catch (CompilationException e) { 191 throw e; 192 } 193 catch (Exception e) { 194 throw new CompilationException("Failed to generate function " + functionOrProperty.getName(), e, functionOrProperty); 195 } 196 } 197 else if (functionOrProperty instanceof KtProperty) { 198 try { 199 propertyCodegen.gen((KtProperty) functionOrProperty); 200 } 201 catch (ProcessCanceledException e) { 202 throw e; 203 } 204 catch (CompilationException e) { 205 throw e; 206 } 207 catch (Exception e) { 208 throw new CompilationException("Failed to generate property " + functionOrProperty.getName(), e, functionOrProperty); 209 } 210 } 211 else { 212 throw new IllegalArgumentException("Unknown parameter: " + functionOrProperty); 213 } 214 } 215 216 public static void genClassOrObject( 217 @NotNull CodegenContext parentContext, 218 @NotNull KtClassOrObject aClass, 219 @NotNull GenerationState state, 220 @Nullable MemberCodegen<?> parentCodegen 221 ) { 222 ClassDescriptor descriptor = state.getBindingContext().get(BindingContext.CLASS, aClass); 223 224 if (descriptor == null || ErrorUtils.isError(descriptor)) { 225 badDescriptor(descriptor, state.getClassBuilderMode()); 226 return; 227 } 228 229 if (descriptor.getName().equals(SpecialNames.NO_NAME_PROVIDED)) { 230 badDescriptor(descriptor, state.getClassBuilderMode()); 231 } 232 233 Type classType = state.getTypeMapper().mapClass(descriptor); 234 ClassBuilder classBuilder = state.getFactory().newVisitor(JvmDeclarationOriginKt.OtherOrigin(aClass, descriptor), classType, aClass.getContainingFile()); 235 ClassContext classContext = parentContext.intoClass(descriptor, OwnerKind.IMPLEMENTATION, state); 236 new ImplementationBodyCodegen(aClass, classContext, classBuilder, state, parentCodegen, false).generate(); 237 } 238 239 private static void badDescriptor(ClassDescriptor descriptor, ClassBuilderMode mode) { 240 if (mode != ClassBuilderMode.LIGHT_CLASSES) { 241 throw new IllegalStateException("Generating bad descriptor in ClassBuilderMode = " + mode + ": " + descriptor); 242 } 243 } 244 245 public void genClassOrObject(KtClassOrObject aClass) { 246 genClassOrObject(context, aClass, state, this); 247 } 248 249 private void writeInnerClasses() { 250 // JVMS7 (4.7.6): a nested class or interface member will have InnerClasses information 251 // for each enclosing class and for each immediate member 252 ClassDescriptor classDescriptor = classForInnerClassRecord(); 253 if (classDescriptor != null) { 254 if (parentCodegen != null) { 255 parentCodegen.innerClasses.add(classDescriptor); 256 } 257 258 for (MemberCodegen<?> codegen = this; codegen != null; codegen = codegen.getParentCodegen()) { 259 ClassDescriptor outerClass = codegen.classForInnerClassRecord(); 260 if (outerClass != null) { 261 innerClasses.add(outerClass); 262 } 263 } 264 } 265 266 for (ClassDescriptor innerClass : innerClasses) { 267 writeInnerClass(innerClass); 268 } 269 } 270 271 private void writeInnerClass(@NotNull ClassDescriptor innerClass) { 272 DeclarationDescriptor containing = innerClass.getContainingDeclaration(); 273 String outerClassInternalName = null; 274 if (containing instanceof ClassDescriptor) { 275 outerClassInternalName = typeMapper.mapClass((ClassDescriptor) containing).getInternalName(); 276 } 277 String innerName = innerClass.getName().isSpecial() ? null : innerClass.getName().asString(); 278 String innerClassInternalName = typeMapper.mapClass(innerClass).getInternalName(); 279 v.visitInnerClass(innerClassInternalName, outerClassInternalName, innerName, calculateInnerClassAccessFlags(innerClass)); 280 } 281 282 protected void writeOuterClassAndEnclosingMethod() { 283 CodegenContext context = this.context.getParentContext(); 284 while (context instanceof MethodContext && ((MethodContext) context).isInliningLambda()) { 285 // If this is a lambda which will be inlined, skip its MethodContext and enclosing ClosureContext 286 //noinspection ConstantConditions 287 context = context.getParentContext().getParentContext(); 288 } 289 assert context != null : "Outermost context can't be null: " + this.context; 290 291 Type enclosingAsmType = computeOuterClass(context); 292 if (enclosingAsmType != null) { 293 Method method = computeEnclosingMethod(context); 294 295 v.visitOuterClass( 296 enclosingAsmType.getInternalName(), 297 method == null ? null : method.getName(), 298 method == null ? null : method.getDescriptor() 299 ); 300 } 301 } 302 303 @Nullable 304 private Type computeOuterClass(@NotNull CodegenContext<?> context) { 305 CodegenContext<? extends ClassOrPackageFragmentDescriptor> outermost = context.getClassOrPackageParentContext(); 306 if (outermost instanceof ClassContext) { 307 return typeMapper.mapType(((ClassContext) outermost).getContextDescriptor()); 308 } 309 else if (outermost instanceof DelegatingFacadeContext || outermost instanceof DelegatingToPartContext) { 310 Type implementationOwnerType = CodegenContextUtil.getImplementationOwnerClassType(outermost); 311 if (implementationOwnerType != null) { 312 return implementationOwnerType; 313 } 314 else { 315 return FileClasses.getFileClassType(fileClassesProvider, element.getContainingKtFile()); 316 } 317 } 318 319 return null; 320 } 321 322 @Nullable 323 private Method computeEnclosingMethod(@NotNull CodegenContext context) { 324 if (context instanceof MethodContext) { 325 Method method = typeMapper.mapSignature(((MethodContext) context).getFunctionDescriptor()).getAsmMethod(); 326 if (!method.getName().equals("<clinit>")) { 327 return method; 328 } 329 } 330 return null; 331 } 332 333 @NotNull 334 public NameGenerator getInlineNameGenerator() { 335 if (inlineNameGenerator == null) { 336 String prefix = InlineCodegenUtil.getInlineName(context, typeMapper, fileClassesProvider); 337 inlineNameGenerator = new NameGenerator(prefix); 338 } 339 return inlineNameGenerator; 340 } 341 342 @NotNull 343 protected ExpressionCodegen createOrGetClInitCodegen() { 344 DeclarationDescriptor descriptor = context.getContextDescriptor(); 345 if (clInit == null) { 346 MethodVisitor mv = v.newMethod(JvmDeclarationOriginKt.OtherOrigin(descriptor), ACC_STATIC, "<clinit>", "()V", null, null); 347 SimpleFunctionDescriptorImpl clInit = 348 SimpleFunctionDescriptorImpl.create(descriptor, Annotations.Companion.getEMPTY(), Name.special("<clinit>"), SYNTHESIZED, 349 KotlinSourceElementKt.toSourceElement(element)); 350 clInit.initialize(null, null, Collections.<TypeParameterDescriptor>emptyList(), 351 Collections.<ValueParameterDescriptor>emptyList(), 352 DescriptorUtilsKt.getModule(descriptor).getBuiltIns().getUnitType(), 353 null, Visibilities.PRIVATE); 354 355 this.clInit = new ExpressionCodegen(mv, new FrameMap(), Type.VOID_TYPE, context.intoFunction(clInit), state, this); 356 } 357 return clInit; 358 } 359 360 protected void generateInitializers(@NotNull Function0<ExpressionCodegen> createCodegen) { 361 NotNullLazyValue<ExpressionCodegen> codegen = LockBasedStorageManager.NO_LOCKS.createLazyValue(createCodegen); 362 for (KtDeclaration declaration : ((KtDeclarationContainer) element).getDeclarations()) { 363 if (declaration instanceof KtProperty) { 364 if (shouldInitializeProperty((KtProperty) declaration)) { 365 initializeProperty(codegen.invoke(), (KtProperty) declaration); 366 } 367 } 368 else if (declaration instanceof KtAnonymousInitializer) { 369 KtExpression body = ((KtAnonymousInitializer) declaration).getBody(); 370 if (body != null) { 371 codegen.invoke().gen(body, Type.VOID_TYPE); 372 } 373 } 374 } 375 } 376 377 private void initializeProperty(@NotNull ExpressionCodegen codegen, @NotNull KtProperty property) { 378 PropertyDescriptor propertyDescriptor = (PropertyDescriptor) bindingContext.get(VARIABLE, property); 379 assert propertyDescriptor != null; 380 381 KtExpression initializer = property.getDelegateExpressionOrInitializer(); 382 assert initializer != null : "shouldInitializeProperty must return false if initializer is null"; 383 384 StackValue.Property propValue = codegen.intermediateValueForProperty(propertyDescriptor, true, false, null, true, StackValue.LOCAL_0); 385 386 propValue.store(codegen.gen(initializer), codegen.v); 387 } 388 389 private boolean shouldInitializeProperty(@NotNull KtProperty property) { 390 if (!property.hasDelegateExpressionOrInitializer()) return false; 391 392 PropertyDescriptor propertyDescriptor = (PropertyDescriptor) bindingContext.get(VARIABLE, property); 393 assert propertyDescriptor != null; 394 395 if (propertyDescriptor.isConst()) { 396 //const initializer always inlined 397 return false; 398 } 399 400 KtExpression initializer = property.getInitializer(); 401 402 ConstantValue<?> initializerValue = computeInitializerValue(property, propertyDescriptor, initializer); 403 // we must write constant values for fields in light classes, 404 // because Java's completion for annotation arguments uses this information 405 if (initializerValue == null) return state.getClassBuilderMode() != ClassBuilderMode.LIGHT_CLASSES; 406 407 //TODO: OPTIMIZATION: don't initialize static final fields 408 KotlinType jetType = getPropertyOrDelegateType(property, propertyDescriptor); 409 Type type = typeMapper.mapType(jetType); 410 return !skipDefaultValue(propertyDescriptor, initializerValue.getValue(), type); 411 } 412 413 @Nullable 414 private ConstantValue<?> computeInitializerValue( 415 @NotNull KtProperty property, 416 @NotNull PropertyDescriptor propertyDescriptor, 417 @Nullable KtExpression initializer 418 ) { 419 if (property.isVar() && initializer != null) { 420 BindingTrace tempTrace = TemporaryBindingTrace.create(state.getBindingTrace(), "property initializer"); 421 return constantExpressionEvaluator.evaluateToConstantValue(initializer, tempTrace, propertyDescriptor.getType()); 422 } 423 return propertyDescriptor.getCompileTimeInitializer(); 424 } 425 426 @NotNull 427 private KotlinType getPropertyOrDelegateType(@NotNull KtProperty property, @NotNull PropertyDescriptor descriptor) { 428 KtExpression delegateExpression = property.getDelegateExpression(); 429 if (delegateExpression != null) { 430 KotlinType delegateType = bindingContext.getType(delegateExpression); 431 assert delegateType != null : "Type of delegate expression should be recorded"; 432 return delegateType; 433 } 434 return descriptor.getType(); 435 } 436 437 private static boolean skipDefaultValue(@NotNull PropertyDescriptor propertyDescriptor, Object value, @NotNull Type type) { 438 if (isPrimitive(type)) { 439 if (!propertyDescriptor.getType().isMarkedNullable() && value instanceof Number) { 440 if (type == Type.INT_TYPE && ((Number) value).intValue() == 0) { 441 return true; 442 } 443 if (type == Type.BYTE_TYPE && ((Number) value).byteValue() == 0) { 444 return true; 445 } 446 if (type == Type.LONG_TYPE && ((Number) value).longValue() == 0L) { 447 return true; 448 } 449 if (type == Type.SHORT_TYPE && ((Number) value).shortValue() == 0) { 450 return true; 451 } 452 if (type == Type.DOUBLE_TYPE && ((Number) value).doubleValue() == 0d) { 453 return true; 454 } 455 if (type == Type.FLOAT_TYPE && ((Number) value).floatValue() == 0f) { 456 return true; 457 } 458 } 459 if (type == Type.BOOLEAN_TYPE && value instanceof Boolean && !((Boolean) value)) { 460 return true; 461 } 462 if (type == Type.CHAR_TYPE && value instanceof Character && ((Character) value) == 0) { 463 return true; 464 } 465 } 466 else { 467 if (value == null) { 468 return true; 469 } 470 } 471 return false; 472 } 473 474 protected void generatePropertyMetadataArrayFieldIfNeeded(@NotNull Type thisAsmType) { 475 List<KtProperty> delegatedProperties = new ArrayList<KtProperty>(); 476 for (KtDeclaration declaration : ((KtDeclarationContainer) element).getDeclarations()) { 477 if (declaration instanceof KtProperty) { 478 KtProperty property = (KtProperty) declaration; 479 if (property.hasDelegate()) { 480 delegatedProperties.add(property); 481 } 482 } 483 } 484 if (delegatedProperties.isEmpty()) return; 485 486 v.newField(NO_ORIGIN, ACC_PRIVATE | ACC_STATIC | ACC_FINAL | ACC_SYNTHETIC, JvmAbi.DELEGATED_PROPERTIES_ARRAY_NAME, 487 "[" + K_PROPERTY_TYPE, null, null); 488 489 if (state.getClassBuilderMode() == ClassBuilderMode.LIGHT_CLASSES) return; 490 491 InstructionAdapter iv = createOrGetClInitCodegen().v; 492 iv.iconst(delegatedProperties.size()); 493 iv.newarray(K_PROPERTY_TYPE); 494 495 for (int i = 0, size = delegatedProperties.size(); i < size; i++) { 496 PropertyDescriptor property = 497 (PropertyDescriptor) BindingContextUtils.getNotNull(bindingContext, VARIABLE, delegatedProperties.get(i)); 498 499 iv.dup(); 500 iv.iconst(i); 501 502 StackValue value; 503 // TODO: remove this option and always generate PropertyReferenceNImpl creation 504 if ("true".equalsIgnoreCase(System.getProperty("kotlin.jvm.optimize.delegated.properties"))) { 505 int receiverCount = (property.getDispatchReceiverParameter() != null ? 1 : 0) + 506 (property.getExtensionReceiverParameter() != null ? 1 : 0); 507 Type implType = property.isVar() ? MUTABLE_PROPERTY_REFERENCE_IMPL[receiverCount] : PROPERTY_REFERENCE_IMPL[receiverCount]; 508 iv.anew(implType); 509 iv.dup(); 510 // TODO: generate the container once and save to a local field instead 511 ClosureCodegen.generateCallableReferenceDeclarationContainer(iv, property, state); 512 iv.aconst(property.getName().asString()); 513 iv.aconst(PropertyReferenceCodegen.getPropertyReferenceSignature(property, state)); 514 iv.invokespecial( 515 implType.getInternalName(), "<init>", 516 Type.getMethodDescriptor(Type.VOID_TYPE, K_DECLARATION_CONTAINER_TYPE, JAVA_STRING_TYPE, JAVA_STRING_TYPE), false 517 ); 518 value = StackValue.onStack(implType); 519 Method wrapper = PropertyReferenceCodegen.getWrapperMethodForPropertyReference(property, receiverCount); 520 iv.invokestatic(REFLECTION, wrapper.getName(), wrapper.getDescriptor(), false); 521 } 522 else { 523 ReceiverParameterDescriptor dispatchReceiver = property.getDispatchReceiverParameter(); 524 525 //noinspection ConstantConditions 526 value = createOrGetClInitCodegen().generatePropertyReference( 527 delegatedProperties.get(i).getDelegate(), property, property, 528 dispatchReceiver != null ? new TransientReceiver(dispatchReceiver.getType()) : ReceiverValue.NO_RECEIVER 529 ); 530 } 531 532 value.put(K_PROPERTY_TYPE, iv); 533 534 iv.astore(K_PROPERTY_TYPE); 535 } 536 537 iv.putstatic(thisAsmType.getInternalName(), JvmAbi.DELEGATED_PROPERTIES_ARRAY_NAME, "[" + K_PROPERTY_TYPE); 538 } 539 540 public String getClassName() { 541 return v.getThisName(); 542 } 543 544 @NotNull 545 public FieldOwnerContext<?> getContext() { 546 return context; 547 } 548 549 @NotNull 550 public ReifiedTypeParametersUsages getReifiedTypeParametersUsages() { 551 return reifiedTypeParametersUsages; 552 } 553 554 public MemberCodegen<?> getParentCodegen() { 555 return parentCodegen; 556 } 557 558 @Override 559 public String toString() { 560 return context.toString(); 561 } 562 563 @NotNull 564 public SourceMapper getOrCreateSourceMapper() { 565 if (sourceMapper == null) { 566 sourceMapper = new DefaultSourceMapper(SourceInfo.Companion.createInfo(element, getClassName()), null); 567 } 568 return sourceMapper; 569 } 570 571 protected void generateConstInstance( 572 @NotNull Type thisAsmType, 573 @NotNull Type fieldAsmType, 574 @NotNull Function1<InstructionAdapter, Unit> initialization 575 ) { 576 v.newField(JvmDeclarationOriginKt.OtherOrigin(element), ACC_STATIC | ACC_FINAL | ACC_PUBLIC, JvmAbi.INSTANCE_FIELD, fieldAsmType.getDescriptor(), 577 null, null); 578 579 if (state.getClassBuilderMode() == ClassBuilderMode.FULL) { 580 InstructionAdapter iv = createOrGetClInitCodegen().v; 581 iv.anew(thisAsmType); 582 iv.dup(); 583 iv.invokespecial(thisAsmType.getInternalName(), "<init>", "()V", false); 584 initialization.invoke(iv); 585 iv.putstatic(thisAsmType.getInternalName(), JvmAbi.INSTANCE_FIELD, fieldAsmType.getDescriptor()); 586 } 587 } 588 589 protected void generateSyntheticAccessors() { 590 for (AccessorForCallableDescriptor<?> accessor : ((CodegenContext<?>) context).getAccessors()) { 591 generateSyntheticAccessor(accessor); 592 } 593 } 594 595 private void generateSyntheticAccessor(@NotNull AccessorForCallableDescriptor<?> accessorForCallableDescriptor) { 596 if (accessorForCallableDescriptor instanceof FunctionDescriptor) { 597 final FunctionDescriptor accessor = (FunctionDescriptor) accessorForCallableDescriptor; 598 final FunctionDescriptor original = (FunctionDescriptor) accessorForCallableDescriptor.getCalleeDescriptor(); 599 functionCodegen.generateMethod( 600 Synthetic(null, original), accessor, 601 new FunctionGenerationStrategy.CodegenBased<FunctionDescriptor>(state, accessor) { 602 @Override 603 public void doGenerateBody(@NotNull ExpressionCodegen codegen, @NotNull JvmMethodSignature signature) { 604 markLineNumberForElement(element, codegen.v); 605 606 generateMethodCallTo(original, accessor, codegen.v).coerceTo(signature.getReturnType(), codegen.v); 607 608 codegen.v.areturn(signature.getReturnType()); 609 } 610 } 611 ); 612 } 613 else if (accessorForCallableDescriptor instanceof AccessorForPropertyDescriptor) { 614 final AccessorForPropertyDescriptor accessor = (AccessorForPropertyDescriptor) accessorForCallableDescriptor; 615 final PropertyDescriptor original = accessor.getCalleeDescriptor(); 616 617 class PropertyAccessorStrategy extends FunctionGenerationStrategy.CodegenBased<PropertyAccessorDescriptor> { 618 public PropertyAccessorStrategy(@NotNull PropertyAccessorDescriptor callableDescriptor) { 619 super(MemberCodegen.this.state, callableDescriptor); 620 } 621 622 @Override 623 public void doGenerateBody(@NotNull ExpressionCodegen codegen, @NotNull JvmMethodSignature signature) { 624 boolean syntheticBackingField = accessor instanceof AccessorForPropertyBackingFieldFromLocal; 625 boolean forceField = (AsmUtil.isPropertyWithBackingFieldInOuterClass(original) && 626 !isCompanionObject(accessor.getContainingDeclaration())) || 627 syntheticBackingField || 628 original.getVisibility() == JavaVisibilities.PROTECTED_STATIC_VISIBILITY; 629 StackValue property = codegen.intermediateValueForProperty( 630 original, forceField, syntheticBackingField, accessor.getSuperCallTarget(), true, StackValue.none() 631 ); 632 633 InstructionAdapter iv = codegen.v; 634 635 markLineNumberForElement(element, iv); 636 637 Type[] argTypes = signature.getAsmMethod().getArgumentTypes(); 638 for (int i = 0, reg = 0; i < argTypes.length; i++) { 639 Type argType = argTypes[i]; 640 iv.load(reg, argType); 641 //noinspection AssignmentToForLoopParameter 642 reg += argType.getSize(); 643 } 644 645 if (callableDescriptor instanceof PropertyGetterDescriptor) { 646 property.put(signature.getReturnType(), iv); 647 } 648 else { 649 property.store(StackValue.onStack(property.type), iv, true); 650 } 651 652 iv.areturn(signature.getReturnType()); 653 } 654 } 655 656 if (accessor.isWithSyntheticGetterAccessor()) { 657 PropertyGetterDescriptor getter = accessor.getGetter(); 658 assert getter != null; 659 functionCodegen.generateMethod(Synthetic(null, original.getGetter() != null ? original.getGetter() : original), 660 getter, new PropertyAccessorStrategy(getter)); 661 } 662 663 if (accessor.isVar() && accessor.isWithSyntheticSetterAccessor()) { 664 PropertySetterDescriptor setter = accessor.getSetter(); 665 assert setter != null; 666 667 functionCodegen.generateMethod(Synthetic(null, original.getSetter() != null ? original.getSetter() : original), 668 setter, new PropertyAccessorStrategy(setter)); 669 } 670 } 671 else { 672 throw new UnsupportedOperationException(); 673 } 674 } 675 676 private StackValue generateMethodCallTo( 677 @NotNull FunctionDescriptor functionDescriptor, 678 @Nullable FunctionDescriptor accessorDescriptor, 679 @NotNull InstructionAdapter iv 680 ) { 681 CallableMethod callableMethod = typeMapper.mapToCallableMethod( 682 functionDescriptor, 683 accessorDescriptor instanceof AccessorForCallableDescriptor && 684 ((AccessorForCallableDescriptor) accessorDescriptor).getSuperCallTarget() != null 685 ); 686 687 boolean hasDispatchReceiver = !isStaticDeclaration(functionDescriptor); 688 int reg = hasDispatchReceiver ? 1 : 0; 689 boolean accessorIsConstructor = accessorDescriptor instanceof AccessorForConstructorDescriptor; 690 if (!accessorIsConstructor && functionDescriptor instanceof ConstructorDescriptor) { 691 iv.anew(callableMethod.getOwner()); 692 iv.dup(); 693 reg = 0; 694 } 695 else if (accessorIsConstructor || (accessorDescriptor != null && JetTypeMapper.isAccessor(accessorDescriptor) && hasDispatchReceiver)) { 696 if (!AnnotationUtilKt.isPlatformStaticInObjectOrClass(functionDescriptor)) { 697 iv.load(0, OBJECT_TYPE); 698 } 699 } 700 701 for (Type argType : callableMethod.getParameterTypes()) { 702 if (AsmTypes.DEFAULT_CONSTRUCTOR_MARKER.equals(argType)) { 703 iv.aconst(null); 704 } 705 else { 706 iv.load(reg, argType); 707 reg += argType.getSize(); 708 } 709 } 710 711 callableMethod.genInvokeInstruction(iv); 712 713 return StackValue.onStack(callableMethod.getReturnType()); 714 } 715 }