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