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.JvmAbi; 037 import org.jetbrains.kotlin.name.Name; 038 import org.jetbrains.kotlin.name.SpecialNames; 039 import org.jetbrains.kotlin.psi.*; 040 import org.jetbrains.kotlin.resolve.*; 041 import org.jetbrains.kotlin.resolve.annotations.AnnotationUtilKt; 042 import org.jetbrains.kotlin.resolve.constants.ConstantValue; 043 import org.jetbrains.kotlin.resolve.constants.evaluate.ConstantExpressionEvaluator; 044 import org.jetbrains.kotlin.resolve.descriptorUtil.DescriptorUtilsKt; 045 import org.jetbrains.kotlin.resolve.jvm.AsmTypes; 046 import org.jetbrains.kotlin.resolve.jvm.diagnostics.JvmDeclarationOriginKt; 047 import org.jetbrains.kotlin.resolve.jvm.jvmSignature.JvmMethodSignature; 048 import org.jetbrains.kotlin.resolve.scopes.receivers.ReceiverValue; 049 import org.jetbrains.kotlin.resolve.scopes.receivers.TransientReceiver; 050 import org.jetbrains.kotlin.resolve.source.KotlinSourceElementKt; 051 import org.jetbrains.kotlin.storage.LockBasedStorageManager; 052 import org.jetbrains.kotlin.storage.NotNullLazyValue; 053 import org.jetbrains.kotlin.types.ErrorUtils; 054 import org.jetbrains.kotlin.types.KotlinType; 055 import org.jetbrains.org.objectweb.asm.Label; 056 import org.jetbrains.org.objectweb.asm.MethodVisitor; 057 import org.jetbrains.org.objectweb.asm.Type; 058 import org.jetbrains.org.objectweb.asm.commons.InstructionAdapter; 059 import org.jetbrains.org.objectweb.asm.commons.Method; 060 061 import java.util.*; 062 063 import static org.jetbrains.kotlin.codegen.AsmUtil.calculateInnerClassAccessFlags; 064 import static org.jetbrains.kotlin.codegen.AsmUtil.isPrimitive; 065 import static org.jetbrains.kotlin.descriptors.CallableMemberDescriptor.Kind.SYNTHESIZED; 066 import static org.jetbrains.kotlin.resolve.BindingContext.VARIABLE; 067 import static org.jetbrains.kotlin.resolve.DescriptorUtils.isCompanionObject; 068 import static org.jetbrains.kotlin.resolve.DescriptorUtils.isTopLevelDeclaration; 069 import static org.jetbrains.kotlin.resolve.jvm.AsmTypes.OBJECT_TYPE; 070 import static org.jetbrains.kotlin.resolve.jvm.AsmTypes.PROPERTY_METADATA_TYPE; 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 markLineNumberForSyntheticFunction(@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 markLineNumberForSyntheticFunction(classElement, v); 155 } 156 } 157 158 public static void markLineNumberForSyntheticFunction(@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 } /* disabled cause of KT-7775 277 else if (containing instanceof ScriptDescriptor) { 278 outerClassInternalName = asmTypeForScriptDescriptor(bindingContext, (ScriptDescriptor) containing).getInternalName(); 279 }*/ 280 281 String innerName = innerClass.getName().isSpecial() ? null : innerClass.getName().asString(); 282 283 String innerClassInternalName = typeMapper.mapClass(innerClass).getInternalName(); 284 v.visitInnerClass(innerClassInternalName, outerClassInternalName, innerName, calculateInnerClassAccessFlags(innerClass)); 285 } 286 287 protected void writeOuterClassAndEnclosingMethod() { 288 CodegenContext context = this.context.getParentContext(); 289 while (context instanceof MethodContext && ((MethodContext) context).isInliningLambda()) { 290 // If this is a lambda which will be inlined, skip its MethodContext and enclosing ClosureContext 291 //noinspection ConstantConditions 292 context = context.getParentContext().getParentContext(); 293 } 294 assert context != null : "Outermost context can't be null: " + this.context; 295 296 Type enclosingAsmType = computeOuterClass(context); 297 if (enclosingAsmType != null) { 298 Method method = computeEnclosingMethod(context); 299 300 v.visitOuterClass( 301 enclosingAsmType.getInternalName(), 302 method == null ? null : method.getName(), 303 method == null ? null : method.getDescriptor() 304 ); 305 } 306 } 307 308 @Nullable 309 private Type computeOuterClass(@NotNull CodegenContext<?> context) { 310 CodegenContext<? extends ClassOrPackageFragmentDescriptor> outermost = context.getClassOrPackageParentContext(); 311 if (outermost instanceof ClassContext) { 312 return typeMapper.mapType(((ClassContext) outermost).getContextDescriptor()); 313 } 314 else if (outermost instanceof DelegatingFacadeContext || outermost instanceof DelegatingToPartContext) { 315 Type implementationOwnerType = CodegenContextUtil.getImplementationOwnerClassType(outermost); 316 if (implementationOwnerType != null) { 317 return implementationOwnerType; 318 } 319 else { 320 return FileClasses.getFileClassType(fileClassesProvider, element.getContainingJetFile()); 321 } 322 } 323 /*disabled cause of KT-7775 324 else if (outermost instanceof ScriptContext) { 325 return asmTypeForScriptDescriptor(bindingContext, ((ScriptContext) outermost).getScriptDescriptor()); 326 }*/ 327 return null; 328 } 329 330 @Nullable 331 private Method computeEnclosingMethod(@NotNull CodegenContext context) { 332 if (context instanceof MethodContext) { 333 Method method = typeMapper.mapSignature(((MethodContext) context).getFunctionDescriptor()).getAsmMethod(); 334 if (!method.getName().equals("<clinit>")) { 335 return method; 336 } 337 } 338 return null; 339 } 340 341 @NotNull 342 public NameGenerator getInlineNameGenerator() { 343 if (inlineNameGenerator == null) { 344 String prefix = InlineCodegenUtil.getInlineName(context, typeMapper, fileClassesProvider); 345 inlineNameGenerator = new NameGenerator(prefix); 346 } 347 return inlineNameGenerator; 348 } 349 350 @NotNull 351 protected ExpressionCodegen createOrGetClInitCodegen() { 352 DeclarationDescriptor descriptor = context.getContextDescriptor(); 353 if (clInit == null) { 354 MethodVisitor mv = v.newMethod(JvmDeclarationOriginKt.OtherOrigin(descriptor), ACC_STATIC, "<clinit>", "()V", null, null); 355 SimpleFunctionDescriptorImpl clInit = 356 SimpleFunctionDescriptorImpl.create(descriptor, Annotations.Companion.getEMPTY(), Name.special("<clinit>"), SYNTHESIZED, 357 KotlinSourceElementKt.toSourceElement(element)); 358 clInit.initialize(null, null, Collections.<TypeParameterDescriptor>emptyList(), 359 Collections.<ValueParameterDescriptor>emptyList(), 360 DescriptorUtilsKt.getModule(descriptor).getBuiltIns().getUnitType(), 361 null, Visibilities.PRIVATE); 362 363 this.clInit = new ExpressionCodegen(mv, new FrameMap(), Type.VOID_TYPE, context.intoFunction(clInit), state, this); 364 } 365 return clInit; 366 } 367 368 protected void generateInitializers(@NotNull Function0<ExpressionCodegen> createCodegen) { 369 NotNullLazyValue<ExpressionCodegen> codegen = LockBasedStorageManager.NO_LOCKS.createLazyValue(createCodegen); 370 for (KtDeclaration declaration : ((KtDeclarationContainer) element).getDeclarations()) { 371 if (declaration instanceof KtProperty) { 372 if (shouldInitializeProperty((KtProperty) declaration)) { 373 initializeProperty(codegen.invoke(), (KtProperty) declaration); 374 } 375 } 376 else if (declaration instanceof KtClassInitializer) { 377 KtExpression body = ((KtClassInitializer) declaration).getBody(); 378 if (body != null) { 379 codegen.invoke().gen(body, Type.VOID_TYPE); 380 } 381 } 382 } 383 } 384 385 private void initializeProperty(@NotNull ExpressionCodegen codegen, @NotNull KtProperty property) { 386 PropertyDescriptor propertyDescriptor = (PropertyDescriptor) bindingContext.get(VARIABLE, property); 387 assert propertyDescriptor != null; 388 389 KtExpression initializer = property.getDelegateExpressionOrInitializer(); 390 assert initializer != null : "shouldInitializeProperty must return false if initializer is null"; 391 392 StackValue.Property propValue = codegen.intermediateValueForProperty(propertyDescriptor, true, null, true, StackValue.LOCAL_0); 393 394 propValue.store(codegen.gen(initializer), codegen.v); 395 } 396 397 private boolean shouldInitializeProperty(@NotNull KtProperty property) { 398 if (!property.hasDelegateExpressionOrInitializer()) return false; 399 400 PropertyDescriptor propertyDescriptor = (PropertyDescriptor) bindingContext.get(VARIABLE, property); 401 assert propertyDescriptor != null; 402 403 if (propertyDescriptor.isConst()) { 404 //const initializer always inlined 405 return false; 406 } 407 408 KtExpression initializer = property.getInitializer(); 409 410 ConstantValue<?> initializerValue = computeInitializerValue(property, propertyDescriptor, initializer); 411 // we must write constant values for fields in light classes, 412 // because Java's completion for annotation arguments uses this information 413 if (initializerValue == null) return state.getClassBuilderMode() != ClassBuilderMode.LIGHT_CLASSES; 414 415 //TODO: OPTIMIZATION: don't initialize static final fields 416 KotlinType jetType = getPropertyOrDelegateType(property, propertyDescriptor); 417 Type type = typeMapper.mapType(jetType); 418 return !skipDefaultValue(propertyDescriptor, initializerValue.getValue(), type); 419 } 420 421 @Nullable 422 private ConstantValue<?> computeInitializerValue( 423 @NotNull KtProperty property, 424 @NotNull PropertyDescriptor propertyDescriptor, 425 @Nullable KtExpression initializer 426 ) { 427 if (property.isVar() && initializer != null) { 428 BindingTrace tempTrace = TemporaryBindingTrace.create(state.getBindingTrace(), "property initializer"); 429 return constantExpressionEvaluator.evaluateToConstantValue(initializer, tempTrace, propertyDescriptor.getType()); 430 } 431 return propertyDescriptor.getCompileTimeInitializer(); 432 } 433 434 @NotNull 435 private KotlinType getPropertyOrDelegateType(@NotNull KtProperty property, @NotNull PropertyDescriptor descriptor) { 436 KtExpression delegateExpression = property.getDelegateExpression(); 437 if (delegateExpression != null) { 438 KotlinType delegateType = bindingContext.getType(delegateExpression); 439 assert delegateType != null : "Type of delegate expression should be recorded"; 440 return delegateType; 441 } 442 return descriptor.getType(); 443 } 444 445 private static boolean skipDefaultValue(@NotNull PropertyDescriptor propertyDescriptor, Object value, @NotNull Type type) { 446 if (isPrimitive(type)) { 447 if (!propertyDescriptor.getType().isMarkedNullable() && value instanceof Number) { 448 if (type == Type.INT_TYPE && ((Number) value).intValue() == 0) { 449 return true; 450 } 451 if (type == Type.BYTE_TYPE && ((Number) value).byteValue() == 0) { 452 return true; 453 } 454 if (type == Type.LONG_TYPE && ((Number) value).longValue() == 0L) { 455 return true; 456 } 457 if (type == Type.SHORT_TYPE && ((Number) value).shortValue() == 0) { 458 return true; 459 } 460 if (type == Type.DOUBLE_TYPE && ((Number) value).doubleValue() == 0d) { 461 return true; 462 } 463 if (type == Type.FLOAT_TYPE && ((Number) value).floatValue() == 0f) { 464 return true; 465 } 466 } 467 if (type == Type.BOOLEAN_TYPE && value instanceof Boolean && !((Boolean) value)) { 468 return true; 469 } 470 if (type == Type.CHAR_TYPE && value instanceof Character && ((Character) value) == 0) { 471 return true; 472 } 473 } 474 else { 475 if (value == null) { 476 return true; 477 } 478 } 479 return false; 480 } 481 482 public static void generateModuleNameField( 483 @NotNull GenerationState state, 484 @NotNull ClassBuilder classBuilder 485 ) { 486 classBuilder.newField(NO_ORIGIN, ACC_PUBLIC | ACC_STATIC | ACC_FINAL | ACC_SYNTHETIC, JvmAbi.MODULE_NAME_FIELD, 487 AsmTypes.JAVA_STRING_TYPE.getDescriptor(), null, state.getModuleName()); 488 } 489 490 protected void generatePropertyMetadataArrayFieldIfNeeded(@NotNull Type thisAsmType) { 491 List<KtProperty> delegatedProperties = new ArrayList<KtProperty>(); 492 for (KtDeclaration declaration : ((KtDeclarationContainer) element).getDeclarations()) { 493 if (declaration instanceof KtProperty) { 494 KtProperty property = (KtProperty) declaration; 495 if (property.hasDelegate()) { 496 delegatedProperties.add(property); 497 } 498 } 499 } 500 if (delegatedProperties.isEmpty()) return; 501 502 v.newField(NO_ORIGIN, ACC_PRIVATE | ACC_STATIC | ACC_FINAL | ACC_SYNTHETIC, JvmAbi.DELEGATED_PROPERTIES_ARRAY_NAME, 503 "[" + PROPERTY_METADATA_TYPE, null, null); 504 505 if (state.getClassBuilderMode() == ClassBuilderMode.LIGHT_CLASSES) return; 506 507 InstructionAdapter iv = createOrGetClInitCodegen().v; 508 iv.iconst(delegatedProperties.size()); 509 iv.newarray(PROPERTY_METADATA_TYPE); 510 511 for (int i = 0, size = delegatedProperties.size(); i < size; i++) { 512 VariableDescriptor property = BindingContextUtils.getNotNull(bindingContext, VARIABLE, delegatedProperties.get(i)); 513 514 iv.dup(); 515 iv.iconst(i); 516 517 ReceiverParameterDescriptor dispatchReceiver = property.getDispatchReceiverParameter(); 518 519 //noinspection ConstantConditions 520 StackValue value = createOrGetClInitCodegen().generatePropertyReference( 521 delegatedProperties.get(i).getDelegate(), property, property, 522 dispatchReceiver != null ? new TransientReceiver(dispatchReceiver.getType()) : ReceiverValue.NO_RECEIVER 523 ); 524 525 value.put(PROPERTY_METADATA_TYPE, iv); 526 527 iv.astore(PROPERTY_METADATA_TYPE); 528 } 529 530 iv.putstatic(thisAsmType.getInternalName(), JvmAbi.DELEGATED_PROPERTIES_ARRAY_NAME, "[" + PROPERTY_METADATA_TYPE); 531 } 532 533 public String getClassName() { 534 return v.getThisName(); 535 } 536 537 @NotNull 538 public FieldOwnerContext<?> getContext() { 539 return context; 540 } 541 542 @NotNull 543 public ReifiedTypeParametersUsages getReifiedTypeParametersUsages() { 544 return reifiedTypeParametersUsages; 545 } 546 547 public MemberCodegen<?> getParentCodegen() { 548 return parentCodegen; 549 } 550 551 @Override 552 public String toString() { 553 return context.toString(); 554 } 555 556 @NotNull 557 public SourceMapper getOrCreateSourceMapper() { 558 if (sourceMapper == null) { 559 sourceMapper = new DefaultSourceMapper(SourceInfo.Companion.createInfo(element, getClassName()), null); 560 } 561 return sourceMapper; 562 } 563 564 protected void generateConstInstance( 565 @NotNull Type thisAsmType, 566 @NotNull Type fieldAsmType, 567 @NotNull Function1<InstructionAdapter, Unit> initialization 568 ) { 569 v.newField(JvmDeclarationOriginKt.OtherOrigin(element), ACC_STATIC | ACC_FINAL | ACC_PUBLIC, JvmAbi.INSTANCE_FIELD, fieldAsmType.getDescriptor(), 570 null, null); 571 572 if (state.getClassBuilderMode() == ClassBuilderMode.FULL) { 573 InstructionAdapter iv = createOrGetClInitCodegen().v; 574 iv.anew(thisAsmType); 575 iv.dup(); 576 iv.invokespecial(thisAsmType.getInternalName(), "<init>", "()V", false); 577 initialization.invoke(iv); 578 iv.putstatic(thisAsmType.getInternalName(), JvmAbi.INSTANCE_FIELD, fieldAsmType.getDescriptor()); 579 } 580 } 581 582 protected void generateSyntheticAccessors() { 583 for (AccessorForCallableDescriptor<?> accessor : ((CodegenContext<?>) context).getAccessors()) { 584 generateSyntheticAccessor(accessor); 585 } 586 } 587 588 private void generateSyntheticAccessor(@NotNull AccessorForCallableDescriptor<?> accessorForCallableDescriptor) { 589 if (accessorForCallableDescriptor instanceof FunctionDescriptor) { 590 final FunctionDescriptor accessor = (FunctionDescriptor) accessorForCallableDescriptor; 591 final FunctionDescriptor original = (FunctionDescriptor) accessorForCallableDescriptor.getCalleeDescriptor(); 592 functionCodegen.generateMethod( 593 Synthetic(null, original), accessor, 594 new FunctionGenerationStrategy.CodegenBased<FunctionDescriptor>(state, accessor) { 595 @Override 596 public void doGenerateBody(@NotNull ExpressionCodegen codegen, @NotNull JvmMethodSignature signature) { 597 markLineNumberForSyntheticFunction(element, codegen.v); 598 599 generateMethodCallTo(original, accessor, codegen.v); 600 codegen.v.areturn(signature.getReturnType()); 601 } 602 } 603 ); 604 } 605 else if (accessorForCallableDescriptor instanceof AccessorForPropertyDescriptor) { 606 final AccessorForPropertyDescriptor accessor = (AccessorForPropertyDescriptor) accessorForCallableDescriptor; 607 final PropertyDescriptor original = accessor.getCalleeDescriptor(); 608 609 class PropertyAccessorStrategy extends FunctionGenerationStrategy.CodegenBased<PropertyAccessorDescriptor> { 610 public PropertyAccessorStrategy(@NotNull PropertyAccessorDescriptor callableDescriptor) { 611 super(MemberCodegen.this.state, callableDescriptor); 612 } 613 614 @Override 615 public void doGenerateBody(@NotNull ExpressionCodegen codegen, @NotNull JvmMethodSignature signature) { 616 boolean forceField = AsmUtil.isPropertyWithBackingFieldInOuterClass(original) && 617 !isCompanionObject(accessor.getContainingDeclaration()); 618 StackValue property = codegen.intermediateValueForProperty( 619 original, forceField, accessor.getSuperCallExpression(), true, StackValue.none() 620 ); 621 622 InstructionAdapter iv = codegen.v; 623 624 markLineNumberForSyntheticFunction(element, iv); 625 626 Type[] argTypes = signature.getAsmMethod().getArgumentTypes(); 627 for (int i = 0, reg = 0; i < argTypes.length; i++) { 628 Type argType = argTypes[i]; 629 iv.load(reg, argType); 630 //noinspection AssignmentToForLoopParameter 631 reg += argType.getSize(); 632 } 633 634 if (callableDescriptor instanceof PropertyGetterDescriptor) { 635 property.put(property.type, iv); 636 } 637 else { 638 property.store(StackValue.onStack(property.type), iv, true); 639 } 640 641 iv.areturn(signature.getReturnType()); 642 } 643 } 644 645 PropertyGetterDescriptor getter = accessor.getGetter(); 646 assert getter != null; 647 functionCodegen.generateMethod(Synthetic(null, original.getGetter() != null ? original.getGetter() : original), 648 getter, new PropertyAccessorStrategy(getter)); 649 650 651 if (accessor.isVar()) { 652 PropertySetterDescriptor setter = accessor.getSetter(); 653 assert setter != null; 654 655 functionCodegen.generateMethod(Synthetic(null, original.getSetter() != null ? original.getSetter() : original), 656 setter, new PropertyAccessorStrategy(setter)); 657 } 658 } 659 else { 660 throw new UnsupportedOperationException(); 661 } 662 } 663 664 private void generateMethodCallTo( 665 @NotNull FunctionDescriptor functionDescriptor, 666 @Nullable FunctionDescriptor accessorDescriptor, 667 @NotNull InstructionAdapter iv 668 ) { 669 CallableMethod callableMethod = typeMapper.mapToCallableMethod( 670 functionDescriptor, 671 accessorDescriptor instanceof AccessorForCallableDescriptor && 672 ((AccessorForCallableDescriptor) accessorDescriptor).getSuperCallExpression() != null 673 ); 674 675 boolean isTopLevelDeclaration = isTopLevelDeclaration(functionDescriptor); 676 int reg = isTopLevelDeclaration ? 0 : 1; 677 boolean accessorIsConstructor = accessorDescriptor instanceof AccessorForConstructorDescriptor; 678 if (!accessorIsConstructor && functionDescriptor instanceof ConstructorDescriptor) { 679 iv.anew(callableMethod.getOwner()); 680 iv.dup(); 681 reg = 0; 682 } 683 else if (accessorIsConstructor || (accessorDescriptor != null && JetTypeMapper.isAccessor(accessorDescriptor) && !isTopLevelDeclaration)) { 684 if (!AnnotationUtilKt.isPlatformStaticInObjectOrClass(functionDescriptor)) { 685 iv.load(0, OBJECT_TYPE); 686 } 687 } 688 689 for (Type argType : callableMethod.getParameterTypes()) { 690 if (AsmTypes.DEFAULT_CONSTRUCTOR_MARKER.equals(argType)) { 691 iv.aconst(null); 692 } 693 else { 694 iv.load(reg, argType); 695 reg += argType.getSize(); 696 } 697 } 698 699 callableMethod.genInvokeInstruction(iv); 700 } 701 }