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