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.google.common.collect.Lists; 020 import com.intellij.util.ArrayUtil; 021 import kotlin.Function1; 022 import kotlin.Unit; 023 import org.jetbrains.annotations.NotNull; 024 import org.jetbrains.annotations.Nullable; 025 import org.jetbrains.kotlin.builtins.KotlinBuiltIns; 026 import org.jetbrains.kotlin.codegen.binding.CalculatedClosure; 027 import org.jetbrains.kotlin.codegen.context.ClassContext; 028 import org.jetbrains.kotlin.codegen.signature.BothSignatureWriter; 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.impl.SimpleFunctionDescriptorImpl; 033 import org.jetbrains.kotlin.load.java.JvmAbi; 034 import org.jetbrains.kotlin.name.Name; 035 import org.jetbrains.kotlin.psi.JetElement; 036 import org.jetbrains.kotlin.resolve.BindingContext; 037 import org.jetbrains.kotlin.resolve.DescriptorUtils; 038 import org.jetbrains.kotlin.resolve.jvm.jvmSignature.JvmMethodSignature; 039 import org.jetbrains.kotlin.types.JetType; 040 import org.jetbrains.org.objectweb.asm.MethodVisitor; 041 import org.jetbrains.org.objectweb.asm.Type; 042 import org.jetbrains.org.objectweb.asm.commons.InstructionAdapter; 043 import org.jetbrains.org.objectweb.asm.commons.Method; 044 045 import java.util.ArrayList; 046 import java.util.Collections; 047 import java.util.List; 048 049 import static org.jetbrains.kotlin.codegen.AsmUtil.*; 050 import static org.jetbrains.kotlin.codegen.JvmCodegenUtil.isConst; 051 import static org.jetbrains.kotlin.codegen.binding.CodegenBinding.*; 052 import static org.jetbrains.kotlin.load.java.JvmAnnotationNames.KotlinSyntheticClass; 053 import static org.jetbrains.kotlin.resolve.jvm.diagnostics.DiagnosticsPackage.OtherOrigin; 054 import static org.jetbrains.org.objectweb.asm.Opcodes.*; 055 056 public class ClosureCodegen extends MemberCodegen<JetElement> { 057 private final FunctionDescriptor funDescriptor; 058 private final ClassDescriptor classDescriptor; 059 private final SamType samType; 060 private final JetType superClassType; 061 private final List<JetType> superInterfaceTypes; 062 private final FunctionGenerationStrategy strategy; 063 private final CalculatedClosure closure; 064 private final Type asmType; 065 private final int visibilityFlag; 066 private final KotlinSyntheticClass.Kind syntheticClassKind; 067 068 private Method constructor; 069 private Type superClassAsmType; 070 071 public ClosureCodegen( 072 @NotNull GenerationState state, 073 @NotNull JetElement element, 074 @NotNull FunctionDescriptor funDescriptor, 075 @Nullable SamType samType, 076 @NotNull ClassContext context, 077 @NotNull KotlinSyntheticClass.Kind syntheticClassKind, 078 @NotNull FunctionGenerationStrategy strategy, 079 @NotNull MemberCodegen<?> parentCodegen, 080 @NotNull ClassBuilder classBuilder, 081 @NotNull Type asmType 082 ) { 083 super(state, parentCodegen, context, element, classBuilder); 084 085 this.funDescriptor = funDescriptor; 086 this.samType = samType; 087 this.syntheticClassKind = syntheticClassKind; 088 this.strategy = strategy; 089 090 this.classDescriptor = context.getContextDescriptor(); 091 092 if (samType == null) { 093 this.superInterfaceTypes = new ArrayList<JetType>(); 094 095 JetType superClassType = null; 096 for (JetType supertype : classDescriptor.getTypeConstructor().getSupertypes()) { 097 ClassifierDescriptor classifier = supertype.getConstructor().getDeclarationDescriptor(); 098 if (DescriptorUtils.isTrait(classifier)) { 099 superInterfaceTypes.add(supertype); 100 } 101 else { 102 assert superClassType == null : "Closure class can't have more than one superclass: " + funDescriptor; 103 superClassType = supertype; 104 } 105 } 106 assert superClassType != null : "Closure class should have a superclass: " + funDescriptor; 107 108 this.superClassType = superClassType; 109 } 110 else { 111 this.superInterfaceTypes = Collections.singletonList(samType.getType()); 112 this.superClassType = KotlinBuiltIns.getInstance().getAnyType(); 113 } 114 115 this.closure = bindingContext.get(CLOSURE, classDescriptor); 116 assert closure != null : "Closure must be calculated for class: " + classDescriptor; 117 118 this.asmType = asmType; 119 120 visibilityFlag = AsmUtil.getVisibilityAccessFlagForAnonymous(classDescriptor); 121 } 122 123 @Override 124 protected void generateDeclaration() { 125 BothSignatureWriter sw = new BothSignatureWriter(BothSignatureWriter.Mode.CLASS); 126 if (samType != null) { 127 typeMapper.writeFormalTypeParameters(samType.getType().getConstructor().getParameters(), sw); 128 } 129 sw.writeSuperclass(); 130 superClassAsmType = typeMapper.mapSupertype(superClassType, sw); 131 sw.writeSuperclassEnd(); 132 String[] superInterfaceAsmTypes = new String[superInterfaceTypes.size()]; 133 for (int i = 0; i < superInterfaceTypes.size(); i++) { 134 JetType superInterfaceType = superInterfaceTypes.get(i); 135 sw.writeInterface(); 136 superInterfaceAsmTypes[i] = typeMapper.mapSupertype(superInterfaceType, sw).getInternalName(); 137 sw.writeInterfaceEnd(); 138 } 139 140 v.defineClass(element, 141 V1_6, 142 ACC_FINAL | ACC_SUPER | visibilityFlag, 143 asmType.getInternalName(), 144 sw.makeJavaGenericSignature(), 145 superClassAsmType.getInternalName(), 146 superInterfaceAsmTypes 147 ); 148 v.visitSource(element.getContainingFile().getName(), null); 149 } 150 151 @Nullable 152 @Override 153 protected ClassDescriptor classForInnerClassRecord() { 154 return JvmCodegenUtil.isLambdaWhichWillBeInlined(bindingContext, funDescriptor) ? null : classDescriptor; 155 } 156 157 @Override 158 protected void generateBody() { 159 FunctionDescriptor erasedInterfaceFunction; 160 if (samType == null) { 161 erasedInterfaceFunction = getErasedInvokeFunction(funDescriptor); 162 } 163 else { 164 erasedInterfaceFunction = samType.getAbstractMethod().getOriginal(); 165 } 166 167 JvmMethodSignature jvmMethodSignature = 168 typeMapper.mapSignature(funDescriptor).replaceName(erasedInterfaceFunction.getName().toString()); 169 generateBridge(typeMapper.mapSignature(erasedInterfaceFunction).getAsmMethod(), jvmMethodSignature.getAsmMethod()); 170 171 functionCodegen.generateMethod(OtherOrigin(element, funDescriptor), jvmMethodSignature, funDescriptor, strategy); 172 173 //TODO: rewrite cause ugly hack 174 if (samType != null) { 175 SimpleFunctionDescriptorImpl descriptorForBridges = SimpleFunctionDescriptorImpl 176 .create(funDescriptor.getContainingDeclaration(), funDescriptor.getAnnotations(), 177 erasedInterfaceFunction.getName(), 178 CallableMemberDescriptor.Kind.DECLARATION, funDescriptor.getSource()); 179 180 descriptorForBridges 181 .initialize(null, erasedInterfaceFunction.getDispatchReceiverParameter(), erasedInterfaceFunction.getTypeParameters(), 182 erasedInterfaceFunction.getValueParameters(), erasedInterfaceFunction.getReturnType(), Modality.OPEN, 183 erasedInterfaceFunction.getVisibility()); 184 185 descriptorForBridges.addOverriddenDescriptor(erasedInterfaceFunction); 186 functionCodegen.generateBridges(descriptorForBridges); 187 } 188 189 this.constructor = generateConstructor(superClassAsmType); 190 191 if (isConst(closure)) { 192 generateConstInstance(); 193 } 194 195 genClosureFields(closure, v, typeMapper); 196 197 functionCodegen.generateDefaultIfNeeded(context.intoFunction(funDescriptor), 198 typeMapper.mapSignature(funDescriptor), 199 funDescriptor, 200 context.getContextKind(), 201 DefaultParameterValueLoader.DEFAULT, 202 null); 203 } 204 205 @Override 206 protected void generateKotlinAnnotation() { 207 writeKotlinSyntheticClassAnnotation(v, syntheticClassKind); 208 } 209 210 @Override 211 protected void done() { 212 writeOuterClassAndEnclosingMethod(classDescriptor, funDescriptor, typeMapper, v); 213 super.done(); 214 } 215 216 @NotNull 217 public StackValue putInstanceOnStack(@NotNull final ExpressionCodegen codegen) { 218 return StackValue.operation(asmType, new Function1<InstructionAdapter, Unit>() { 219 @Override 220 public Unit invoke(InstructionAdapter v) { 221 if (isConst(closure)) { 222 v.getstatic(asmType.getInternalName(), JvmAbi.INSTANCE_FIELD, asmType.getDescriptor()); 223 } 224 else { 225 v.anew(asmType); 226 v.dup(); 227 228 codegen.pushClosureOnStack(classDescriptor, true, codegen.defaultCallGenerator); 229 v.invokespecial(asmType.getInternalName(), "<init>", constructor.getDescriptor(), false); 230 } 231 return Unit.INSTANCE$; 232 } 233 }); 234 } 235 236 237 private void generateConstInstance() { 238 MethodVisitor mv = v.newMethod(OtherOrigin(element, funDescriptor), ACC_STATIC | ACC_SYNTHETIC, "<clinit>", "()V", null, ArrayUtil.EMPTY_STRING_ARRAY); 239 InstructionAdapter iv = new InstructionAdapter(mv); 240 241 v.newField(OtherOrigin(element, funDescriptor), ACC_STATIC | ACC_FINAL | ACC_PUBLIC, JvmAbi.INSTANCE_FIELD, asmType.getDescriptor(), null, null); 242 243 if (state.getClassBuilderMode() == ClassBuilderMode.FULL) { 244 mv.visitCode(); 245 iv.anew(asmType); 246 iv.dup(); 247 iv.invokespecial(asmType.getInternalName(), "<init>", "()V", false); 248 iv.putstatic(asmType.getInternalName(), JvmAbi.INSTANCE_FIELD, asmType.getDescriptor()); 249 mv.visitInsn(RETURN); 250 FunctionCodegen.endVisit(mv, "<clinit>", element); 251 } 252 } 253 254 private void generateBridge(@NotNull Method bridge, @NotNull Method delegate) { 255 if (bridge.equals(delegate)) return; 256 257 MethodVisitor mv = 258 v.newMethod(OtherOrigin(element, funDescriptor), ACC_PUBLIC | ACC_BRIDGE, bridge.getName(), bridge.getDescriptor(), null, ArrayUtil.EMPTY_STRING_ARRAY); 259 260 if (state.getClassBuilderMode() != ClassBuilderMode.FULL) return; 261 262 mv.visitCode(); 263 264 InstructionAdapter iv = new InstructionAdapter(mv); 265 ImplementationBodyCodegen.markLineNumberForSyntheticFunction(DescriptorUtils.getParentOfType(funDescriptor, ClassDescriptor.class), iv); 266 267 iv.load(0, asmType); 268 269 ReceiverParameterDescriptor receiver = funDescriptor.getExtensionReceiverParameter(); 270 int count = 1; 271 if (receiver != null) { 272 StackValue.local(count, bridge.getArgumentTypes()[count - 1]).put(typeMapper.mapType(receiver.getType()), iv); 273 count++; 274 } 275 276 List<ValueParameterDescriptor> params = funDescriptor.getValueParameters(); 277 for (ValueParameterDescriptor param : params) { 278 StackValue.local(count, bridge.getArgumentTypes()[count - 1]).put(typeMapper.mapType(param.getType()), iv); 279 count++; 280 } 281 282 iv.invokevirtual(asmType.getInternalName(), delegate.getName(), delegate.getDescriptor(), false); 283 StackValue.onStack(delegate.getReturnType()).put(bridge.getReturnType(), iv); 284 285 iv.areturn(bridge.getReturnType()); 286 287 FunctionCodegen.endVisit(mv, "bridge", element); 288 } 289 290 @NotNull 291 private Method generateConstructor(@NotNull Type superClassAsmType) { 292 List<FieldInfo> args = calculateConstructorParameters(typeMapper, closure, asmType); 293 294 Type[] argTypes = fieldListToTypeArray(args); 295 296 Method constructor = new Method("<init>", Type.VOID_TYPE, argTypes); 297 MethodVisitor mv = v.newMethod(OtherOrigin(element, funDescriptor), visibilityFlag, "<init>", constructor.getDescriptor(), null, 298 ArrayUtil.EMPTY_STRING_ARRAY); 299 if (state.getClassBuilderMode() == ClassBuilderMode.FULL) { 300 mv.visitCode(); 301 InstructionAdapter iv = new InstructionAdapter(mv); 302 303 int k = 1; 304 for (FieldInfo fieldInfo : args) { 305 k = genAssignInstanceFieldFromParam(fieldInfo, k, iv); 306 } 307 308 iv.load(0, superClassAsmType); 309 iv.invokespecial(superClassAsmType.getInternalName(), "<init>", "()V", false); 310 311 iv.visitInsn(RETURN); 312 313 FunctionCodegen.endVisit(iv, "constructor", element); 314 } 315 return constructor; 316 } 317 318 @NotNull 319 public static List<FieldInfo> calculateConstructorParameters( 320 @NotNull JetTypeMapper typeMapper, 321 @NotNull CalculatedClosure closure, 322 @NotNull Type ownerType 323 ) { 324 BindingContext bindingContext = typeMapper.getBindingContext(); 325 List<FieldInfo> args = Lists.newArrayList(); 326 ClassDescriptor captureThis = closure.getCaptureThis(); 327 if (captureThis != null) { 328 Type type = typeMapper.mapType(captureThis); 329 args.add(FieldInfo.createForHiddenField(ownerType, type, CAPTURED_THIS_FIELD)); 330 } 331 JetType captureReceiverType = closure.getCaptureReceiverType(); 332 if (captureReceiverType != null) { 333 args.add(FieldInfo.createForHiddenField(ownerType, typeMapper.mapType(captureReceiverType), CAPTURED_RECEIVER_FIELD)); 334 } 335 336 for (DeclarationDescriptor descriptor : closure.getCaptureVariables().keySet()) { 337 if (descriptor instanceof VariableDescriptor && !(descriptor instanceof PropertyDescriptor)) { 338 Type sharedVarType = typeMapper.getSharedVarType(descriptor); 339 340 Type type = sharedVarType != null 341 ? sharedVarType 342 : typeMapper.mapType((VariableDescriptor) descriptor); 343 args.add(FieldInfo.createForHiddenField(ownerType, type, "$" + descriptor.getName().asString())); 344 } 345 else if (isLocalNamedFun(descriptor)) { 346 Type classType = asmTypeForAnonymousClass(bindingContext, (FunctionDescriptor) descriptor); 347 args.add(FieldInfo.createForHiddenField(ownerType, classType, "$" + descriptor.getName().asString())); 348 } 349 else if (descriptor instanceof FunctionDescriptor) { 350 assert captureReceiverType != null; 351 } 352 } 353 return args; 354 } 355 356 private static Type[] fieldListToTypeArray(List<FieldInfo> args) { 357 Type[] argTypes = new Type[args.size()]; 358 for (int i = 0; i != argTypes.length; ++i) { 359 argTypes[i] = args.get(i).getFieldType(); 360 } 361 return argTypes; 362 } 363 364 @NotNull 365 public static FunctionDescriptor getErasedInvokeFunction(@NotNull FunctionDescriptor elementDescriptor) { 366 int arity = elementDescriptor.getValueParameters().size(); 367 ClassDescriptor elementClass = elementDescriptor.getExtensionReceiverParameter() == null 368 ? KotlinBuiltIns.getInstance().getFunction(arity) 369 : KotlinBuiltIns.getInstance().getExtensionFunction(arity); 370 return elementClass.getDefaultType().getMemberScope().getFunctions(Name.identifier("invoke")).iterator().next(); 371 } 372 }