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.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.OBJECT$.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).isTrait()) { 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 = 246 containing instanceof ClassDescriptor ? typeMapper.mapClass((ClassDescriptor) containing).getInternalName() : null; 247 248 String innerName = innerClass.getName().isSpecial() ? null : innerClass.getName().asString(); 249 250 String innerClassInternalName = typeMapper.mapClass(innerClass).getInternalName(); 251 v.visitInnerClass(innerClassInternalName, outerClassInternalName, innerName, calculateInnerClassAccessFlags(innerClass)); 252 } 253 254 protected void writeOuterClassAndEnclosingMethod() { 255 CodegenContext context = this.context.getParentContext(); 256 while (context instanceof MethodContext && ((MethodContext) context).isInliningLambda()) { 257 // If this is a lambda which will be inlined, skip its MethodContext and enclosing ClosureContext 258 //noinspection ConstantConditions 259 context = context.getParentContext().getParentContext(); 260 } 261 assert context != null : "Outermost context can't be null: " + this.context; 262 263 Type enclosingAsmType = computeOuterClass(context); 264 if (enclosingAsmType != null) { 265 Method method = computeEnclosingMethod(context); 266 267 v.visitOuterClass( 268 enclosingAsmType.getInternalName(), 269 method == null ? null : method.getName(), 270 method == null ? null : method.getDescriptor() 271 ); 272 } 273 } 274 275 @Nullable 276 private Type computeOuterClass(@NotNull CodegenContext<?> context) { 277 CodegenContext<? extends ClassOrPackageFragmentDescriptor> outermost = context.getClassOrPackageParentContext(); 278 if (outermost instanceof ClassContext) { 279 return typeMapper.mapType(((ClassContext) outermost).getContextDescriptor()); 280 } 281 else if (outermost instanceof PackageContext && !(outermost instanceof PackageFacadeContext)) { 282 return PackagePartClassUtils.getPackagePartType(element.getContainingJetFile()); 283 } 284 return null; 285 } 286 287 @Nullable 288 private Method computeEnclosingMethod(@NotNull CodegenContext context) { 289 if (context instanceof MethodContext) { 290 Method method = typeMapper.mapSignature(((MethodContext) context).getFunctionDescriptor()).getAsmMethod(); 291 if (!method.getName().equals("<clinit>")) { 292 return method; 293 } 294 } 295 return null; 296 } 297 298 @NotNull 299 public NameGenerator getInlineNameGenerator() { 300 if (inlineNameGenerator == null) { 301 String prefix = InlineCodegenUtil.getInlineName(context, typeMapper); 302 inlineNameGenerator = new NameGenerator(prefix); 303 } 304 return inlineNameGenerator; 305 } 306 307 @NotNull 308 protected ExpressionCodegen createOrGetClInitCodegen() { 309 DeclarationDescriptor descriptor = context.getContextDescriptor(); 310 if (clInit == null) { 311 MethodVisitor mv = v.newMethod(OtherOrigin(descriptor), ACC_STATIC, "<clinit>", "()V", null, null); 312 SimpleFunctionDescriptorImpl clInit = 313 SimpleFunctionDescriptorImpl.create(descriptor, Annotations.EMPTY, Name.special("<clinit>"), SYNTHESIZED, NO_SOURCE); 314 clInit.initialize(null, null, Collections.<TypeParameterDescriptor>emptyList(), 315 Collections.<ValueParameterDescriptor>emptyList(), 316 DescriptorUtilPackage.getModule(descriptor).getBuiltIns().getUnitType(), 317 null, Visibilities.PRIVATE); 318 319 this.clInit = new ExpressionCodegen(mv, new FrameMap(), Type.VOID_TYPE, context.intoFunction(clInit), state, this); 320 } 321 return clInit; 322 } 323 324 protected void generateInitializers(@NotNull Function0<ExpressionCodegen> createCodegen) { 325 NotNullLazyValue<ExpressionCodegen> codegen = LockBasedStorageManager.NO_LOCKS.createLazyValue(createCodegen); 326 for (JetDeclaration declaration : ((JetDeclarationContainer) element).getDeclarations()) { 327 if (declaration instanceof JetProperty) { 328 if (shouldInitializeProperty((JetProperty) declaration)) { 329 initializeProperty(codegen.invoke(), (JetProperty) declaration); 330 } 331 } 332 else if (declaration instanceof JetClassInitializer) { 333 JetExpression body = ((JetClassInitializer) declaration).getBody(); 334 if (body != null) { 335 codegen.invoke().gen(body, Type.VOID_TYPE); 336 } 337 } 338 } 339 } 340 341 private void initializeProperty(@NotNull ExpressionCodegen codegen, @NotNull JetProperty property) { 342 PropertyDescriptor propertyDescriptor = (PropertyDescriptor) bindingContext.get(VARIABLE, property); 343 assert propertyDescriptor != null; 344 345 JetExpression initializer = property.getDelegateExpressionOrInitializer(); 346 assert initializer != null : "shouldInitializeProperty must return false if initializer is null"; 347 348 StackValue.Property propValue = codegen.intermediateValueForProperty(propertyDescriptor, true, null, MethodKind.INITIALIZER, 349 StackValue.LOCAL_0); 350 351 propValue.store(codegen.gen(initializer), codegen.v); 352 353 ResolvedCall<FunctionDescriptor> pdResolvedCall = 354 bindingContext.get(BindingContext.DELEGATED_PROPERTY_PD_RESOLVED_CALL, propertyDescriptor); 355 if (pdResolvedCall != null) { 356 int index = PropertyCodegen.indexOfDelegatedProperty(property); 357 StackValue lastValue = PropertyCodegen.invokeDelegatedPropertyConventionMethod( 358 propertyDescriptor, codegen, typeMapper, pdResolvedCall, index, 0 359 ); 360 lastValue.put(Type.VOID_TYPE, codegen.v); 361 } 362 } 363 364 private boolean shouldInitializeProperty(@NotNull JetProperty property) { 365 if (!property.hasDelegateExpressionOrInitializer()) return false; 366 367 PropertyDescriptor propertyDescriptor = (PropertyDescriptor) bindingContext.get(VARIABLE, property); 368 assert propertyDescriptor != null; 369 370 JetExpression initializer = property.getInitializer(); 371 372 CompileTimeConstant<?> initializerValue; 373 if (property.isVar() && initializer != null) { 374 BindingTrace tempTrace = TemporaryBindingTrace.create(state.getBindingTrace(), "property initializer"); 375 initializerValue = ConstantExpressionEvaluator.evaluate(initializer, tempTrace, propertyDescriptor.getType()); 376 } 377 else { 378 initializerValue = propertyDescriptor.getCompileTimeInitializer(); 379 } 380 // we must write constant values for fields in light classes, 381 // because Java's completion for annotation arguments uses this information 382 if (initializerValue == null) return state.getClassBuilderMode() != ClassBuilderMode.LIGHT_CLASSES; 383 384 //TODO: OPTIMIZATION: don't initialize static final fields 385 386 Object value = initializerValue instanceof IntegerValueTypeConstant 387 ? ((IntegerValueTypeConstant) initializerValue).getValue(propertyDescriptor.getType()) 388 : initializerValue.getValue(); 389 JetType jetType = getPropertyOrDelegateType(property, propertyDescriptor); 390 Type type = typeMapper.mapType(jetType); 391 return !skipDefaultValue(propertyDescriptor, value, type); 392 } 393 394 @NotNull 395 private JetType getPropertyOrDelegateType(@NotNull JetProperty property, @NotNull PropertyDescriptor descriptor) { 396 JetExpression delegateExpression = property.getDelegateExpression(); 397 if (delegateExpression != null) { 398 JetType delegateType = bindingContext.get(BindingContext.EXPRESSION_TYPE, delegateExpression); 399 assert delegateType != null : "Type of delegate expression should be recorded"; 400 return delegateType; 401 } 402 return descriptor.getType(); 403 } 404 405 private static boolean skipDefaultValue(@NotNull PropertyDescriptor propertyDescriptor, Object value, @NotNull Type type) { 406 if (isPrimitive(type)) { 407 if (!propertyDescriptor.getType().isMarkedNullable() && value instanceof Number) { 408 if (type == Type.INT_TYPE && ((Number) value).intValue() == 0) { 409 return true; 410 } 411 if (type == Type.BYTE_TYPE && ((Number) value).byteValue() == 0) { 412 return true; 413 } 414 if (type == Type.LONG_TYPE && ((Number) value).longValue() == 0L) { 415 return true; 416 } 417 if (type == Type.SHORT_TYPE && ((Number) value).shortValue() == 0) { 418 return true; 419 } 420 if (type == Type.DOUBLE_TYPE && ((Number) value).doubleValue() == 0d) { 421 return true; 422 } 423 if (type == Type.FLOAT_TYPE && ((Number) value).floatValue() == 0f) { 424 return true; 425 } 426 } 427 if (type == Type.BOOLEAN_TYPE && value instanceof Boolean && !((Boolean) value)) { 428 return true; 429 } 430 if (type == Type.CHAR_TYPE && value instanceof Character && ((Character) value) == 0) { 431 return true; 432 } 433 } 434 else { 435 if (value == null) { 436 return true; 437 } 438 } 439 return false; 440 } 441 442 public static void generateReflectionObjectField( 443 @NotNull GenerationState state, 444 @NotNull Type thisAsmType, 445 @NotNull ClassBuilder classBuilder, 446 @NotNull Method factory, 447 @NotNull String fieldName, 448 @NotNull InstructionAdapter v 449 ) { 450 String type = factory.getReturnType().getDescriptor(); 451 // TODO: generic signature 452 classBuilder.newField(NO_ORIGIN, ACC_PUBLIC | ACC_STATIC | ACC_FINAL | ACC_SYNTHETIC, fieldName, type, null, null); 453 454 if (state.getClassBuilderMode() == ClassBuilderMode.LIGHT_CLASSES) return; 455 456 v.aconst(thisAsmType); 457 v.invokestatic(REFLECTION, factory.getName(), factory.getDescriptor(), false); 458 v.putstatic(thisAsmType.getInternalName(), fieldName, type); 459 } 460 461 protected void generatePropertyMetadataArrayFieldIfNeeded(@NotNull Type thisAsmType) { 462 List<JetProperty> delegatedProperties = new ArrayList<JetProperty>(); 463 for (JetDeclaration declaration : ((JetDeclarationContainer) element).getDeclarations()) { 464 if (declaration instanceof JetProperty) { 465 JetProperty property = (JetProperty) declaration; 466 if (property.hasDelegate()) { 467 delegatedProperties.add(property); 468 } 469 } 470 } 471 if (delegatedProperties.isEmpty()) return; 472 473 v.newField(NO_ORIGIN, ACC_PRIVATE | ACC_STATIC | ACC_FINAL | ACC_SYNTHETIC, JvmAbi.PROPERTY_METADATA_ARRAY_NAME, 474 "[" + PROPERTY_METADATA_TYPE, null, null); 475 476 if (state.getClassBuilderMode() == ClassBuilderMode.LIGHT_CLASSES) return; 477 478 InstructionAdapter iv = createOrGetClInitCodegen().v; 479 iv.iconst(delegatedProperties.size()); 480 iv.newarray(PROPERTY_METADATA_TYPE); 481 482 for (int i = 0, size = delegatedProperties.size(); i < size; i++) { 483 VariableDescriptor property = BindingContextUtils.getNotNull(bindingContext, VARIABLE, delegatedProperties.get(i)); 484 485 iv.dup(); 486 iv.iconst(i); 487 iv.anew(PROPERTY_METADATA_IMPL_TYPE); 488 iv.dup(); 489 iv.visitLdcInsn(property.getName().asString()); 490 iv.invokespecial(PROPERTY_METADATA_IMPL_TYPE.getInternalName(), "<init>", "(Ljava/lang/String;)V", false); 491 iv.astore(PROPERTY_METADATA_IMPL_TYPE); 492 } 493 494 iv.putstatic(thisAsmType.getInternalName(), JvmAbi.PROPERTY_METADATA_ARRAY_NAME, "[" + PROPERTY_METADATA_TYPE); 495 } 496 497 public String getClassName() { 498 return v.getThisName(); 499 } 500 501 @NotNull 502 public FieldOwnerContext<?> getContext() { 503 return context; 504 } 505 506 @NotNull 507 public ReifiedTypeParametersUsages getReifiedTypeParametersUsages() { 508 return reifiedTypeParametersUsages; 509 } 510 511 public MemberCodegen<?> getParentCodegen() { 512 return parentCodegen; 513 } 514 515 @Override 516 public String toString() { 517 return context.toString(); 518 } 519 520 @NotNull 521 public SourceMapper getOrCreateSourceMapper() { 522 if (sourceMapper == null) { 523 sourceMapper = new DefaultSourceMapper(SourceInfo.OBJECT$.createInfo(element, getClassName()), null); 524 } 525 return sourceMapper; 526 } 527 }