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 kotlin.jvm.functions.Function0; 021 import org.jetbrains.annotations.NotNull; 022 import org.jetbrains.annotations.Nullable; 023 import org.jetbrains.kotlin.codegen.context.*; 024 import org.jetbrains.kotlin.codegen.inline.*; 025 import org.jetbrains.kotlin.codegen.state.GenerationState; 026 import org.jetbrains.kotlin.codegen.state.JetTypeMapper; 027 import org.jetbrains.kotlin.descriptors.*; 028 import org.jetbrains.kotlin.descriptors.annotations.Annotations; 029 import org.jetbrains.kotlin.descriptors.impl.SimpleFunctionDescriptorImpl; 030 import org.jetbrains.kotlin.load.java.JvmAbi; 031 import org.jetbrains.kotlin.load.kotlin.PackagePartClassUtils; 032 import org.jetbrains.kotlin.name.Name; 033 import org.jetbrains.kotlin.name.SpecialNames; 034 import org.jetbrains.kotlin.psi.*; 035 import org.jetbrains.kotlin.resolve.BindingContext; 036 import org.jetbrains.kotlin.resolve.BindingContextUtils; 037 import org.jetbrains.kotlin.resolve.BindingTrace; 038 import org.jetbrains.kotlin.resolve.TemporaryBindingTrace; 039 import org.jetbrains.kotlin.resolve.calls.model.ResolvedCall; 040 import org.jetbrains.kotlin.resolve.constants.CompileTimeConstant; 041 import org.jetbrains.kotlin.resolve.constants.IntegerValueTypeConstant; 042 import org.jetbrains.kotlin.resolve.constants.evaluate.ConstantExpressionEvaluator; 043 import org.jetbrains.kotlin.resolve.descriptorUtil.DescriptorUtilPackage; 044 import org.jetbrains.kotlin.storage.LockBasedStorageManager; 045 import org.jetbrains.kotlin.storage.NotNullLazyValue; 046 import org.jetbrains.kotlin.types.ErrorUtils; 047 import org.jetbrains.kotlin.types.JetType; 048 import org.jetbrains.org.objectweb.asm.MethodVisitor; 049 import org.jetbrains.org.objectweb.asm.Type; 050 import org.jetbrains.org.objectweb.asm.commons.InstructionAdapter; 051 import org.jetbrains.org.objectweb.asm.commons.Method; 052 053 import java.util.*; 054 055 import static org.jetbrains.kotlin.codegen.AsmUtil.calculateInnerClassAccessFlags; 056 import static org.jetbrains.kotlin.codegen.AsmUtil.isPrimitive; 057 import static org.jetbrains.kotlin.descriptors.CallableMemberDescriptor.Kind.SYNTHESIZED; 058 import static org.jetbrains.kotlin.descriptors.SourceElement.NO_SOURCE; 059 import static org.jetbrains.kotlin.resolve.BindingContext.VARIABLE; 060 import static org.jetbrains.kotlin.resolve.jvm.AsmTypes.*; 061 import static org.jetbrains.kotlin.resolve.jvm.diagnostics.DiagnosticsPackage.OtherOrigin; 062 import static org.jetbrains.kotlin.resolve.jvm.diagnostics.DiagnosticsPackage.TraitImpl; 063 import static org.jetbrains.kotlin.resolve.jvm.diagnostics.JvmDeclarationOrigin.NO_ORIGIN; 064 import static org.jetbrains.org.objectweb.asm.Opcodes.*; 065 066 public abstract class MemberCodegen<T extends JetElement/* TODO: & JetDeclarationContainer*/> { 067 protected final GenerationState state; 068 protected final T element; 069 protected final FieldOwnerContext context; 070 protected final ClassBuilder v; 071 protected final FunctionCodegen functionCodegen; 072 protected final PropertyCodegen propertyCodegen; 073 protected final JetTypeMapper typeMapper; 074 protected final BindingContext bindingContext; 075 private final MemberCodegen<?> parentCodegen; 076 private final ReifiedTypeParametersUsages reifiedTypeParametersUsages = new ReifiedTypeParametersUsages(); 077 protected final Collection<ClassDescriptor> innerClasses = new LinkedHashSet<ClassDescriptor>(); 078 079 protected ExpressionCodegen clInit; 080 private NameGenerator inlineNameGenerator; 081 082 private SourceMapper sourceMapper; 083 084 public MemberCodegen( 085 @NotNull GenerationState state, 086 @Nullable MemberCodegen<?> parentCodegen, 087 @NotNull FieldOwnerContext context, 088 T element, 089 @NotNull ClassBuilder builder 090 ) { 091 this.state = state; 092 this.typeMapper = state.getTypeMapper(); 093 this.bindingContext = state.getBindingContext(); 094 this.element = element; 095 this.context = context; 096 this.v = builder; 097 this.functionCodegen = new FunctionCodegen(context, v, state, this); 098 this.propertyCodegen = new PropertyCodegen(context, v, functionCodegen, this); 099 this.parentCodegen = parentCodegen; 100 } 101 102 protected MemberCodegen(@NotNull MemberCodegen<T> wrapped, T declaration, FieldOwnerContext codegenContext) { 103 this(wrapped.state, wrapped.getParentCodegen(), codegenContext, declaration, wrapped.v); 104 } 105 106 public void generate() { 107 generateDeclaration(); 108 109 generateBody(); 110 111 generateSyntheticParts(); 112 113 generateKotlinAnnotation(); 114 115 done(); 116 } 117 118 protected abstract void generateDeclaration(); 119 120 protected abstract void generateBody(); 121 122 protected void generateSyntheticParts() { 123 } 124 125 protected abstract void generateKotlinAnnotation(); 126 127 @Nullable 128 protected ClassDescriptor classForInnerClassRecord() { 129 return null; 130 } 131 132 protected void done() { 133 if (clInit != null) { 134 clInit.v.visitInsn(RETURN); 135 FunctionCodegen.endVisit(clInit.v, "static initializer", element); 136 } 137 138 writeInnerClasses(); 139 140 if (sourceMapper != null) { 141 SourceMapper.Companion.flushToClassBuilder(sourceMapper, v); 142 } 143 144 v.done(); 145 } 146 147 public void genFunctionOrProperty(@NotNull JetDeclaration functionOrProperty) { 148 if (functionOrProperty instanceof JetNamedFunction) { 149 try { 150 functionCodegen.gen((JetNamedFunction) functionOrProperty); 151 } 152 catch (ProcessCanceledException e) { 153 throw e; 154 } 155 catch (CompilationException e) { 156 throw e; 157 } 158 catch (Exception e) { 159 throw new CompilationException("Failed to generate function " + functionOrProperty.getName(), e, functionOrProperty); 160 } 161 } 162 else if (functionOrProperty instanceof JetProperty) { 163 try { 164 propertyCodegen.gen((JetProperty) functionOrProperty); 165 } 166 catch (ProcessCanceledException e) { 167 throw e; 168 } 169 catch (CompilationException e) { 170 throw e; 171 } 172 catch (Exception e) { 173 throw new CompilationException("Failed to generate property " + functionOrProperty.getName(), e, functionOrProperty); 174 } 175 } 176 else { 177 throw new IllegalArgumentException("Unknown parameter: " + functionOrProperty); 178 } 179 } 180 181 public static void genClassOrObject( 182 @NotNull CodegenContext parentContext, 183 @NotNull JetClassOrObject aClass, 184 @NotNull GenerationState state, 185 @Nullable MemberCodegen<?> parentCodegen 186 ) { 187 ClassDescriptor descriptor = state.getBindingContext().get(BindingContext.CLASS, aClass); 188 189 if (descriptor == null || ErrorUtils.isError(descriptor)) { 190 badDescriptor(descriptor, state.getClassBuilderMode()); 191 return; 192 } 193 194 if (descriptor.getName().equals(SpecialNames.NO_NAME_PROVIDED)) { 195 badDescriptor(descriptor, state.getClassBuilderMode()); 196 } 197 198 Type classType = state.getTypeMapper().mapClass(descriptor); 199 ClassBuilder classBuilder = state.getFactory().newVisitor(OtherOrigin(aClass, descriptor), classType, aClass.getContainingFile()); 200 ClassContext classContext = parentContext.intoClass(descriptor, OwnerKind.IMPLEMENTATION, state); 201 new ImplementationBodyCodegen(aClass, classContext, classBuilder, state, parentCodegen).generate(); 202 203 if (aClass instanceof JetClass && ((JetClass) aClass).isInterface()) { 204 Type traitImplType = state.getTypeMapper().mapTraitImpl(descriptor); 205 ClassBuilder traitImplBuilder = state.getFactory().newVisitor(TraitImpl(aClass, descriptor), traitImplType, aClass.getContainingFile()); 206 ClassContext traitImplContext = parentContext.intoClass(descriptor, OwnerKind.TRAIT_IMPL, state); 207 new TraitImplBodyCodegen(aClass, traitImplContext, traitImplBuilder, state, parentCodegen).generate(); 208 } 209 } 210 211 private static void badDescriptor(ClassDescriptor descriptor, ClassBuilderMode mode) { 212 if (mode != ClassBuilderMode.LIGHT_CLASSES) { 213 throw new IllegalStateException("Generating bad descriptor in ClassBuilderMode = " + mode + ": " + descriptor); 214 } 215 } 216 217 public void genClassOrObject(JetClassOrObject aClass) { 218 genClassOrObject(context, aClass, state, this); 219 } 220 221 private void writeInnerClasses() { 222 // JVMS7 (4.7.6): a nested class or interface member will have InnerClasses information 223 // for each enclosing class and for each immediate member 224 ClassDescriptor classDescriptor = classForInnerClassRecord(); 225 if (classDescriptor != null) { 226 if (parentCodegen != null) { 227 parentCodegen.innerClasses.add(classDescriptor); 228 } 229 230 for (MemberCodegen<?> codegen = this; codegen != null; codegen = codegen.getParentCodegen()) { 231 ClassDescriptor outerClass = codegen.classForInnerClassRecord(); 232 if (outerClass != null) { 233 innerClasses.add(outerClass); 234 } 235 } 236 } 237 238 for (ClassDescriptor innerClass : innerClasses) { 239 writeInnerClass(innerClass); 240 } 241 } 242 243 private void writeInnerClass(@NotNull ClassDescriptor innerClass) { 244 DeclarationDescriptor containing = innerClass.getContainingDeclaration(); 245 String outerClassInternalName = null; 246 if (containing instanceof ClassDescriptor) { 247 outerClassInternalName = typeMapper.mapClass((ClassDescriptor) containing).getInternalName(); 248 } /* disabled cause of KT-7775 249 else if (containing instanceof ScriptDescriptor) { 250 outerClassInternalName = asmTypeForScriptDescriptor(bindingContext, (ScriptDescriptor) containing).getInternalName(); 251 }*/ 252 253 String innerName = innerClass.getName().isSpecial() ? null : innerClass.getName().asString(); 254 255 String innerClassInternalName = typeMapper.mapClass(innerClass).getInternalName(); 256 v.visitInnerClass(innerClassInternalName, outerClassInternalName, innerName, calculateInnerClassAccessFlags(innerClass)); 257 } 258 259 protected void writeOuterClassAndEnclosingMethod() { 260 CodegenContext context = this.context.getParentContext(); 261 while (context instanceof MethodContext && ((MethodContext) context).isInliningLambda()) { 262 // If this is a lambda which will be inlined, skip its MethodContext and enclosing ClosureContext 263 //noinspection ConstantConditions 264 context = context.getParentContext().getParentContext(); 265 } 266 assert context != null : "Outermost context can't be null: " + this.context; 267 268 Type enclosingAsmType = computeOuterClass(context); 269 if (enclosingAsmType != null) { 270 Method method = computeEnclosingMethod(context); 271 272 v.visitOuterClass( 273 enclosingAsmType.getInternalName(), 274 method == null ? null : method.getName(), 275 method == null ? null : method.getDescriptor() 276 ); 277 } 278 } 279 280 @Nullable 281 private Type computeOuterClass(@NotNull CodegenContext<?> context) { 282 CodegenContext<? extends ClassOrPackageFragmentDescriptor> outermost = context.getClassOrPackageParentContext(); 283 if (outermost instanceof ClassContext) { 284 return typeMapper.mapType(((ClassContext) outermost).getContextDescriptor()); 285 } 286 else if (outermost instanceof PackageContext && !(outermost instanceof PackageFacadeContext)) { 287 return PackagePartClassUtils.getPackagePartType(element.getContainingJetFile()); 288 }/*disabled cause of KT-7775 289 else if (outermost instanceof ScriptContext) { 290 return asmTypeForScriptDescriptor(bindingContext, ((ScriptContext) outermost).getScriptDescriptor()); 291 }*/ 292 return null; 293 } 294 295 @Nullable 296 private Method computeEnclosingMethod(@NotNull CodegenContext context) { 297 if (context instanceof MethodContext) { 298 Method method = typeMapper.mapSignature(((MethodContext) context).getFunctionDescriptor()).getAsmMethod(); 299 if (!method.getName().equals("<clinit>")) { 300 return method; 301 } 302 } 303 return null; 304 } 305 306 @NotNull 307 public NameGenerator getInlineNameGenerator() { 308 if (inlineNameGenerator == null) { 309 String prefix = InlineCodegenUtil.getInlineName(context, typeMapper); 310 inlineNameGenerator = new NameGenerator(prefix); 311 } 312 return inlineNameGenerator; 313 } 314 315 @NotNull 316 protected ExpressionCodegen createOrGetClInitCodegen() { 317 DeclarationDescriptor descriptor = context.getContextDescriptor(); 318 if (clInit == null) { 319 MethodVisitor mv = v.newMethod(OtherOrigin(descriptor), ACC_STATIC, "<clinit>", "()V", null, null); 320 SimpleFunctionDescriptorImpl clInit = 321 SimpleFunctionDescriptorImpl.create(descriptor, Annotations.EMPTY, Name.special("<clinit>"), SYNTHESIZED, NO_SOURCE); 322 clInit.initialize(null, null, Collections.<TypeParameterDescriptor>emptyList(), 323 Collections.<ValueParameterDescriptor>emptyList(), 324 DescriptorUtilPackage.getModule(descriptor).getBuiltIns().getUnitType(), 325 null, Visibilities.PRIVATE); 326 327 this.clInit = new ExpressionCodegen(mv, new FrameMap(), Type.VOID_TYPE, context.intoFunction(clInit), state, this); 328 } 329 return clInit; 330 } 331 332 protected void generateInitializers(@NotNull Function0<ExpressionCodegen> createCodegen) { 333 NotNullLazyValue<ExpressionCodegen> codegen = LockBasedStorageManager.NO_LOCKS.createLazyValue(createCodegen); 334 for (JetDeclaration declaration : ((JetDeclarationContainer) element).getDeclarations()) { 335 if (declaration instanceof JetProperty) { 336 if (shouldInitializeProperty((JetProperty) declaration)) { 337 initializeProperty(codegen.invoke(), (JetProperty) declaration); 338 } 339 } 340 else if (declaration instanceof JetClassInitializer) { 341 JetExpression body = ((JetClassInitializer) declaration).getBody(); 342 if (body != null) { 343 codegen.invoke().gen(body, Type.VOID_TYPE); 344 } 345 } 346 } 347 } 348 349 private void initializeProperty(@NotNull ExpressionCodegen codegen, @NotNull JetProperty property) { 350 PropertyDescriptor propertyDescriptor = (PropertyDescriptor) bindingContext.get(VARIABLE, property); 351 assert propertyDescriptor != null; 352 353 JetExpression initializer = property.getDelegateExpressionOrInitializer(); 354 assert initializer != null : "shouldInitializeProperty must return false if initializer is null"; 355 356 StackValue.Property propValue = codegen.intermediateValueForProperty(propertyDescriptor, true, null, MethodKind.INITIALIZER, 357 StackValue.LOCAL_0); 358 359 propValue.store(codegen.gen(initializer), codegen.v); 360 361 ResolvedCall<FunctionDescriptor> pdResolvedCall = 362 bindingContext.get(BindingContext.DELEGATED_PROPERTY_PD_RESOLVED_CALL, propertyDescriptor); 363 if (pdResolvedCall != null) { 364 int index = PropertyCodegen.indexOfDelegatedProperty(property); 365 StackValue lastValue = PropertyCodegen.invokeDelegatedPropertyConventionMethod( 366 propertyDescriptor, codegen, typeMapper, pdResolvedCall, index, 0 367 ); 368 lastValue.put(Type.VOID_TYPE, codegen.v); 369 } 370 } 371 372 private boolean shouldInitializeProperty(@NotNull JetProperty property) { 373 if (!property.hasDelegateExpressionOrInitializer()) return false; 374 375 PropertyDescriptor propertyDescriptor = (PropertyDescriptor) bindingContext.get(VARIABLE, property); 376 assert propertyDescriptor != null; 377 378 JetExpression initializer = property.getInitializer(); 379 380 CompileTimeConstant<?> initializerValue; 381 if (property.isVar() && initializer != null) { 382 BindingTrace tempTrace = TemporaryBindingTrace.create(state.getBindingTrace(), "property initializer"); 383 initializerValue = ConstantExpressionEvaluator.evaluate(initializer, tempTrace, propertyDescriptor.getType()); 384 } 385 else { 386 initializerValue = propertyDescriptor.getCompileTimeInitializer(); 387 } 388 // we must write constant values for fields in light classes, 389 // because Java's completion for annotation arguments uses this information 390 if (initializerValue == null) return state.getClassBuilderMode() != ClassBuilderMode.LIGHT_CLASSES; 391 392 //TODO: OPTIMIZATION: don't initialize static final fields 393 394 Object value = initializerValue instanceof IntegerValueTypeConstant 395 ? ((IntegerValueTypeConstant) initializerValue).getValue(propertyDescriptor.getType()) 396 : initializerValue.getValue(); 397 JetType jetType = getPropertyOrDelegateType(property, propertyDescriptor); 398 Type type = typeMapper.mapType(jetType); 399 return !skipDefaultValue(propertyDescriptor, value, type); 400 } 401 402 @NotNull 403 private JetType getPropertyOrDelegateType(@NotNull JetProperty property, @NotNull PropertyDescriptor descriptor) { 404 JetExpression delegateExpression = property.getDelegateExpression(); 405 if (delegateExpression != null) { 406 JetType delegateType = bindingContext.getType(delegateExpression); 407 assert delegateType != null : "Type of delegate expression should be recorded"; 408 return delegateType; 409 } 410 return descriptor.getType(); 411 } 412 413 private static boolean skipDefaultValue(@NotNull PropertyDescriptor propertyDescriptor, Object value, @NotNull Type type) { 414 if (isPrimitive(type)) { 415 if (!propertyDescriptor.getType().isMarkedNullable() && value instanceof Number) { 416 if (type == Type.INT_TYPE && ((Number) value).intValue() == 0) { 417 return true; 418 } 419 if (type == Type.BYTE_TYPE && ((Number) value).byteValue() == 0) { 420 return true; 421 } 422 if (type == Type.LONG_TYPE && ((Number) value).longValue() == 0L) { 423 return true; 424 } 425 if (type == Type.SHORT_TYPE && ((Number) value).shortValue() == 0) { 426 return true; 427 } 428 if (type == Type.DOUBLE_TYPE && ((Number) value).doubleValue() == 0d) { 429 return true; 430 } 431 if (type == Type.FLOAT_TYPE && ((Number) value).floatValue() == 0f) { 432 return true; 433 } 434 } 435 if (type == Type.BOOLEAN_TYPE && value instanceof Boolean && !((Boolean) value)) { 436 return true; 437 } 438 if (type == Type.CHAR_TYPE && value instanceof Character && ((Character) value) == 0) { 439 return true; 440 } 441 } 442 else { 443 if (value == null) { 444 return true; 445 } 446 } 447 return false; 448 } 449 450 public static void generateReflectionObjectField( 451 @NotNull GenerationState state, 452 @NotNull Type thisAsmType, 453 @NotNull ClassBuilder classBuilder, 454 @NotNull Method factory, 455 @NotNull String fieldName, 456 @NotNull InstructionAdapter v 457 ) { 458 String type = factory.getReturnType().getDescriptor(); 459 // TODO: generic signature 460 classBuilder.newField(NO_ORIGIN, ACC_PUBLIC | ACC_STATIC | ACC_FINAL | ACC_SYNTHETIC, fieldName, type, null, null); 461 462 if (state.getClassBuilderMode() == ClassBuilderMode.LIGHT_CLASSES) return; 463 464 v.aconst(thisAsmType); 465 v.invokestatic(REFLECTION, factory.getName(), factory.getDescriptor(), false); 466 v.putstatic(thisAsmType.getInternalName(), fieldName, type); 467 } 468 469 protected void generatePropertyMetadataArrayFieldIfNeeded(@NotNull Type thisAsmType) { 470 List<JetProperty> delegatedProperties = new ArrayList<JetProperty>(); 471 for (JetDeclaration declaration : ((JetDeclarationContainer) element).getDeclarations()) { 472 if (declaration instanceof JetProperty) { 473 JetProperty property = (JetProperty) declaration; 474 if (property.hasDelegate()) { 475 delegatedProperties.add(property); 476 } 477 } 478 } 479 if (delegatedProperties.isEmpty()) return; 480 481 v.newField(NO_ORIGIN, ACC_PRIVATE | ACC_STATIC | ACC_FINAL | ACC_SYNTHETIC, JvmAbi.PROPERTY_METADATA_ARRAY_NAME, 482 "[" + PROPERTY_METADATA_TYPE, null, null); 483 484 if (state.getClassBuilderMode() == ClassBuilderMode.LIGHT_CLASSES) return; 485 486 InstructionAdapter iv = createOrGetClInitCodegen().v; 487 iv.iconst(delegatedProperties.size()); 488 iv.newarray(PROPERTY_METADATA_TYPE); 489 490 for (int i = 0, size = delegatedProperties.size(); i < size; i++) { 491 VariableDescriptor property = BindingContextUtils.getNotNull(bindingContext, VARIABLE, delegatedProperties.get(i)); 492 493 iv.dup(); 494 iv.iconst(i); 495 iv.anew(PROPERTY_METADATA_IMPL_TYPE); 496 iv.dup(); 497 iv.visitLdcInsn(property.getName().asString()); 498 iv.invokespecial(PROPERTY_METADATA_IMPL_TYPE.getInternalName(), "<init>", "(Ljava/lang/String;)V", false); 499 iv.astore(PROPERTY_METADATA_IMPL_TYPE); 500 } 501 502 iv.putstatic(thisAsmType.getInternalName(), JvmAbi.PROPERTY_METADATA_ARRAY_NAME, "[" + PROPERTY_METADATA_TYPE); 503 } 504 505 public String getClassName() { 506 return v.getThisName(); 507 } 508 509 @NotNull 510 public FieldOwnerContext<?> getContext() { 511 return context; 512 } 513 514 @NotNull 515 public ReifiedTypeParametersUsages getReifiedTypeParametersUsages() { 516 return reifiedTypeParametersUsages; 517 } 518 519 public MemberCodegen<?> getParentCodegen() { 520 return parentCodegen; 521 } 522 523 @Override 524 public String toString() { 525 return context.toString(); 526 } 527 528 @NotNull 529 public SourceMapper getOrCreateSourceMapper() { 530 if (sourceMapper == null) { 531 sourceMapper = new DefaultSourceMapper(SourceInfo.Companion.createInfo(element, getClassName()), null); 532 } 533 return sourceMapper; 534 } 535 }