001 /*
002 * Copyright 2010-2013 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.jet.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.jet.codegen.context.ClassContext;
024 import org.jetbrains.jet.codegen.context.CodegenContext;
025 import org.jetbrains.jet.codegen.context.FieldOwnerContext;
026 import org.jetbrains.jet.codegen.inline.InlineCodegenUtil;
027 import org.jetbrains.jet.codegen.inline.NameGenerator;
028 import org.jetbrains.jet.codegen.state.GenerationState;
029 import org.jetbrains.jet.lang.descriptors.*;
030 import org.jetbrains.jet.lang.descriptors.annotations.Annotations;
031 import org.jetbrains.jet.lang.descriptors.impl.SimpleFunctionDescriptorImpl;
032 import org.jetbrains.jet.lang.psi.*;
033 import org.jetbrains.jet.lang.resolve.BindingContext;
034 import org.jetbrains.jet.lang.resolve.BindingContextUtils;
035 import org.jetbrains.jet.lang.resolve.constants.CompileTimeConstant;
036 import org.jetbrains.jet.lang.resolve.java.JvmAbi;
037 import org.jetbrains.jet.lang.resolve.name.Name;
038 import org.jetbrains.jet.lang.resolve.name.SpecialNames;
039 import org.jetbrains.jet.lang.types.ErrorUtils;
040 import org.jetbrains.jet.lang.types.JetType;
041 import org.jetbrains.jet.storage.LockBasedStorageManager;
042 import org.jetbrains.jet.storage.NotNullLazyValue;
043 import org.jetbrains.org.objectweb.asm.MethodVisitor;
044 import org.jetbrains.org.objectweb.asm.Type;
045 import org.jetbrains.org.objectweb.asm.commons.InstructionAdapter;
046 import org.jetbrains.org.objectweb.asm.commons.Method;
047
048 import java.util.ArrayList;
049 import java.util.Collections;
050 import java.util.List;
051
052 import static org.jetbrains.jet.codegen.AsmUtil.boxType;
053 import static org.jetbrains.jet.codegen.AsmUtil.isPrimitive;
054 import static org.jetbrains.jet.lang.descriptors.CallableMemberDescriptor.Kind.SYNTHESIZED;
055 import static org.jetbrains.jet.lang.descriptors.SourceElement.NO_SOURCE;
056 import static org.jetbrains.jet.lang.resolve.BindingContext.VARIABLE;
057 import static org.jetbrains.jet.lang.resolve.java.AsmTypeConstants.*;
058 import static org.jetbrains.jet.lang.resolve.java.diagnostics.DiagnosticsPackage.OtherOrigin;
059 import static org.jetbrains.jet.lang.resolve.java.diagnostics.DiagnosticsPackage.TraitImpl;
060 import static org.jetbrains.jet.lang.resolve.java.diagnostics.JvmDeclarationOrigin.NO_ORIGIN;
061 import static org.jetbrains.org.objectweb.asm.Opcodes.*;
062
063 public abstract class MemberCodegen<T extends JetElement/* TODO: & JetDeclarationContainer*/> extends ParentCodegenAware {
064 protected final T element;
065 protected final FieldOwnerContext context;
066 protected final ClassBuilder v;
067 protected final FunctionCodegen functionCodegen;
068 protected final PropertyCodegen propertyCodegen;
069
070 protected ExpressionCodegen clInit;
071 private NameGenerator inlineNameGenerator;
072
073 public MemberCodegen(
074 @NotNull GenerationState state,
075 @Nullable MemberCodegen<?> parentCodegen,
076 @NotNull FieldOwnerContext context,
077 T element,
078 @NotNull ClassBuilder builder
079 ) {
080 super(state, parentCodegen);
081 this.element = element;
082 this.context = context;
083 this.v = builder;
084 this.functionCodegen = new FunctionCodegen(context, v, state, this);
085 this.propertyCodegen = new PropertyCodegen(context, v, functionCodegen, this);
086 }
087
088 public void generate() {
089 generateDeclaration();
090
091 generateBody();
092
093 generateSyntheticParts();
094
095 generateKotlinAnnotation();
096
097 done();
098 }
099
100 protected abstract void generateDeclaration();
101
102 protected abstract void generateBody();
103
104 protected void generateSyntheticParts() {
105 }
106
107 protected abstract void generateKotlinAnnotation();
108
109 private void done() {
110 if (clInit != null) {
111 clInit.v.visitInsn(RETURN);
112 FunctionCodegen.endVisit(clInit.v, "static initializer", element);
113 }
114
115 v.done();
116 }
117
118 public void genFunctionOrProperty(@NotNull JetDeclaration functionOrProperty) {
119 if (functionOrProperty instanceof JetNamedFunction) {
120 try {
121 functionCodegen.gen((JetNamedFunction) functionOrProperty);
122 }
123 catch (ProcessCanceledException e) {
124 throw e;
125 }
126 catch (CompilationException e) {
127 throw e;
128 }
129 catch (Exception e) {
130 throw new CompilationException("Failed to generate function " + functionOrProperty.getName(), e, functionOrProperty);
131 }
132 }
133 else if (functionOrProperty instanceof JetProperty) {
134 try {
135 propertyCodegen.gen((JetProperty) functionOrProperty);
136 }
137 catch (ProcessCanceledException e) {
138 throw e;
139 }
140 catch (CompilationException e) {
141 throw e;
142 }
143 catch (Exception e) {
144 throw new CompilationException("Failed to generate property " + functionOrProperty.getName(), e, functionOrProperty);
145 }
146 }
147 else {
148 throw new IllegalArgumentException("Unknown parameter: " + functionOrProperty);
149 }
150 }
151
152 public static void genClassOrObject(
153 @NotNull CodegenContext parentContext,
154 @NotNull JetClassOrObject aClass,
155 @NotNull GenerationState state,
156 @Nullable MemberCodegen<?> parentCodegen
157 ) {
158 ClassDescriptor descriptor = state.getBindingContext().get(BindingContext.CLASS, aClass);
159
160 if (descriptor == null || ErrorUtils.isError(descriptor)) {
161 badDescriptor(descriptor, state.getClassBuilderMode());
162 return;
163 }
164
165 if (descriptor.getName().equals(SpecialNames.NO_NAME_PROVIDED)) {
166 badDescriptor(descriptor, state.getClassBuilderMode());
167 }
168
169 Type classType = state.getTypeMapper().mapClass(descriptor);
170 ClassBuilder classBuilder = state.getFactory().newVisitor(OtherOrigin(aClass, descriptor), classType, aClass.getContainingFile());
171 ClassContext classContext = parentContext.intoClass(descriptor, OwnerKind.IMPLEMENTATION, state);
172 new ImplementationBodyCodegen(aClass, classContext, classBuilder, state, parentCodegen).generate();
173
174 if (aClass instanceof JetClass && ((JetClass) aClass).isTrait()) {
175 Type traitImplType = state.getTypeMapper().mapTraitImpl(descriptor);
176 ClassBuilder traitImplBuilder = state.getFactory().newVisitor(TraitImpl(aClass, descriptor), traitImplType, aClass.getContainingFile());
177 ClassContext traitImplContext = parentContext.intoClass(descriptor, OwnerKind.TRAIT_IMPL, state);
178 new TraitImplBodyCodegen(aClass, traitImplContext, traitImplBuilder, state, parentCodegen).generate();
179 }
180 }
181
182 private static void badDescriptor(ClassDescriptor descriptor, ClassBuilderMode mode) {
183 if (mode != ClassBuilderMode.LIGHT_CLASSES) {
184 throw new IllegalStateException("Generating bad descriptor in ClassBuilderMode = " + mode + ": " + descriptor);
185 }
186 }
187
188 public void genClassOrObject(JetClassOrObject aClass) {
189 genClassOrObject(context, aClass, state, this);
190 }
191
192 @NotNull
193 public NameGenerator getInlineNameGenerator() {
194 if (inlineNameGenerator == null) {
195 String prefix = InlineCodegenUtil.getInlineName(context, typeMapper);
196 inlineNameGenerator = new NameGenerator(prefix);
197 }
198 return inlineNameGenerator;
199 }
200
201 @NotNull
202 protected ExpressionCodegen createOrGetClInitCodegen() {
203 DeclarationDescriptor descriptor = context.getContextDescriptor();
204 if (clInit == null) {
205 MethodVisitor mv = v.newMethod(OtherOrigin(descriptor), ACC_STATIC, "<clinit>", "()V", null, null);
206 SimpleFunctionDescriptorImpl clInit =
207 SimpleFunctionDescriptorImpl.create(descriptor, Annotations.EMPTY, Name.special("<clinit>"), SYNTHESIZED, NO_SOURCE);
208 clInit.initialize(null, null, Collections.<TypeParameterDescriptor>emptyList(),
209 Collections.<ValueParameterDescriptor>emptyList(), null, null, Visibilities.PRIVATE);
210
211 this.clInit = new ExpressionCodegen(mv, new FrameMap(), Type.VOID_TYPE, context.intoFunction(clInit), state, this);
212 }
213 return clInit;
214 }
215
216 protected void generateInitializers(@NotNull Function0<ExpressionCodegen> createCodegen) {
217 NotNullLazyValue<ExpressionCodegen> codegen = LockBasedStorageManager.NO_LOCKS.createLazyValue(createCodegen);
218 for (JetDeclaration declaration : ((JetDeclarationContainer) element).getDeclarations()) {
219 if (declaration instanceof JetProperty) {
220 if (shouldInitializeProperty((JetProperty) declaration)) {
221 initializeProperty(codegen.invoke(), (JetProperty) declaration);
222 }
223 }
224 else if (declaration instanceof JetClassInitializer) {
225 codegen.invoke().gen(((JetClassInitializer) declaration).getBody(), Type.VOID_TYPE);
226 }
227 }
228 }
229
230 private void initializeProperty(@NotNull ExpressionCodegen codegen, @NotNull JetProperty property) {
231 PropertyDescriptor propertyDescriptor = (PropertyDescriptor) bindingContext.get(VARIABLE, property);
232 assert propertyDescriptor != null;
233
234 JetExpression initializer = property.getDelegateExpressionOrInitializer();
235 assert initializer != null : "shouldInitializeProperty must return false if initializer is null";
236
237 JetType jetType = getPropertyOrDelegateType(property, propertyDescriptor);
238
239 StackValue.Property propValue = codegen.intermediateValueForProperty(propertyDescriptor, true, null, MethodKind.INITIALIZER);
240
241 if (!propValue.isStatic) {
242 codegen.v.load(0, OBJECT_TYPE);
243 }
244
245 Type type = codegen.expressionType(initializer);
246 if (jetType.isNullable()) {
247 type = boxType(type);
248 }
249 codegen.gen(initializer, type);
250
251 propValue.store(type, codegen.v);
252 }
253
254 private boolean shouldInitializeProperty(@NotNull JetProperty property) {
255 if (!property.hasDelegateExpressionOrInitializer()) return false;
256
257 PropertyDescriptor propertyDescriptor = (PropertyDescriptor) bindingContext.get(VARIABLE, property);
258 assert propertyDescriptor != null;
259
260 CompileTimeConstant<?> compileTimeValue = propertyDescriptor.getCompileTimeInitializer();
261 // we must write constant values for fields in light classes,
262 // because Java's completion for annotation arguments uses this information
263 if (compileTimeValue == null) return state.getClassBuilderMode() != ClassBuilderMode.LIGHT_CLASSES;
264
265 //TODO: OPTIMIZATION: don't initialize static final fields
266
267 Object value = compileTimeValue.getValue();
268 JetType jetType = getPropertyOrDelegateType(property, propertyDescriptor);
269 Type type = typeMapper.mapType(jetType);
270 return !skipDefaultValue(propertyDescriptor, value, type);
271 }
272
273 @NotNull
274 private JetType getPropertyOrDelegateType(@NotNull JetProperty property, @NotNull PropertyDescriptor descriptor) {
275 JetExpression delegateExpression = property.getDelegateExpression();
276 if (delegateExpression != null) {
277 JetType delegateType = bindingContext.get(BindingContext.EXPRESSION_TYPE, delegateExpression);
278 assert delegateType != null : "Type of delegate expression should be recorded";
279 return delegateType;
280 }
281 return descriptor.getType();
282 }
283
284 private static boolean skipDefaultValue(@NotNull PropertyDescriptor propertyDescriptor, Object value, @NotNull Type type) {
285 if (isPrimitive(type)) {
286 if (!propertyDescriptor.getType().isNullable() && value instanceof Number) {
287 if (type == Type.INT_TYPE && ((Number) value).intValue() == 0) {
288 return true;
289 }
290 if (type == Type.BYTE_TYPE && ((Number) value).byteValue() == 0) {
291 return true;
292 }
293 if (type == Type.LONG_TYPE && ((Number) value).longValue() == 0L) {
294 return true;
295 }
296 if (type == Type.SHORT_TYPE && ((Number) value).shortValue() == 0) {
297 return true;
298 }
299 if (type == Type.DOUBLE_TYPE && ((Number) value).doubleValue() == 0d) {
300 return true;
301 }
302 if (type == Type.FLOAT_TYPE && ((Number) value).floatValue() == 0f) {
303 return true;
304 }
305 }
306 if (type == Type.BOOLEAN_TYPE && value instanceof Boolean && !((Boolean) value)) {
307 return true;
308 }
309 if (type == Type.CHAR_TYPE && value instanceof Character && ((Character) value) == 0) {
310 return true;
311 }
312 }
313 else {
314 if (value == null) {
315 return true;
316 }
317 }
318 return false;
319 }
320
321 public static void generateReflectionObjectField(
322 @NotNull GenerationState state,
323 @NotNull Type thisAsmType,
324 @NotNull ClassBuilder classBuilder,
325 @NotNull Method factory,
326 @NotNull String fieldName,
327 @NotNull InstructionAdapter v
328 ) {
329 String type = factory.getReturnType().getDescriptor();
330 // TODO: generic signature
331 classBuilder.newField(NO_ORIGIN, ACC_PUBLIC | ACC_STATIC | ACC_FINAL | ACC_SYNTHETIC, fieldName, type, null, null);
332
333 if (state.getClassBuilderMode() == ClassBuilderMode.LIGHT_CLASSES) return;
334
335 v.aconst(thisAsmType);
336 v.invokestatic(REFLECTION_INTERNAL_PACKAGE, factory.getName(), factory.getDescriptor(), false);
337 v.putstatic(thisAsmType.getInternalName(), fieldName, type);
338 }
339
340 protected void generatePropertyMetadataArrayFieldIfNeeded(@NotNull Type thisAsmType) {
341 List<JetProperty> delegatedProperties = new ArrayList<JetProperty>();
342 for (JetDeclaration declaration : ((JetDeclarationContainer) element).getDeclarations()) {
343 if (declaration instanceof JetProperty) {
344 JetProperty property = (JetProperty) declaration;
345 if (property.hasDelegate()) {
346 delegatedProperties.add(property);
347 }
348 }
349 }
350 if (delegatedProperties.isEmpty()) return;
351
352 v.newField(NO_ORIGIN, ACC_PRIVATE | ACC_STATIC | ACC_FINAL | ACC_SYNTHETIC, JvmAbi.PROPERTY_METADATA_ARRAY_NAME,
353 "[" + PROPERTY_METADATA_TYPE, null, null);
354
355 if (state.getClassBuilderMode() == ClassBuilderMode.LIGHT_CLASSES) return;
356
357 InstructionAdapter iv = createOrGetClInitCodegen().v;
358 iv.iconst(delegatedProperties.size());
359 iv.newarray(PROPERTY_METADATA_TYPE);
360
361 for (int i = 0, size = delegatedProperties.size(); i < size; i++) {
362 VariableDescriptor property = BindingContextUtils.getNotNull(bindingContext, VARIABLE, delegatedProperties.get(i));
363
364 iv.dup();
365 iv.iconst(i);
366 iv.anew(PROPERTY_METADATA_IMPL_TYPE);
367 iv.dup();
368 iv.visitLdcInsn(property.getName().asString());
369 iv.invokespecial(PROPERTY_METADATA_IMPL_TYPE.getInternalName(), "<init>", "(Ljava/lang/String;)V", false);
370 iv.astore(PROPERTY_METADATA_IMPL_TYPE);
371 }
372
373 iv.putstatic(thisAsmType.getInternalName(), JvmAbi.PROPERTY_METADATA_ARRAY_NAME, "[" + PROPERTY_METADATA_TYPE);
374 }
375
376 public String getClassName() {
377 return v.getThisName();
378 }
379 }