Skip to main content
summaryrefslogtreecommitdiffstats
blob: fb166d1fc7b60f8099706769020cff205fd45f8e (plain) (blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
/*******************************************************************************
 * Copyright (c) 2000, 2012 IBM Corporation and others.
 * All rights reserved. This program and the accompanying materials
 * are made available under the terms of the Eclipse Public License v1.0
 * which accompanies this distribution, and is available at
 * http://www.eclipse.org/legal/epl-v10.html
 *
 * Contributors:
 *     IBM Corporation - initial API and implementation
 *     Technical University Berlin - extended API and implementation
 *     Patrick Wienands <pwienands@abit.de> - Contribution for bug 393749
 *******************************************************************************/
package org.eclipse.jdt.internal.compiler.ast;

import org.eclipse.jdt.internal.compiler.ASTVisitor;
import org.eclipse.jdt.internal.compiler.ClassFile;
import org.eclipse.jdt.internal.compiler.CompilationResult;
import org.eclipse.jdt.internal.compiler.codegen.BranchLabel;
import org.eclipse.jdt.internal.compiler.codegen.CodeStream;
import org.eclipse.jdt.internal.compiler.codegen.ConstantPool;
import org.eclipse.jdt.internal.compiler.codegen.Opcodes;
import org.eclipse.jdt.internal.compiler.flow.ExceptionHandlingFlowContext;
import org.eclipse.jdt.internal.compiler.flow.FlowInfo;
import org.eclipse.jdt.internal.compiler.flow.InitializationFlowContext;
import org.eclipse.jdt.internal.compiler.impl.Constant;
import org.eclipse.jdt.internal.compiler.lookup.Binding;
import org.eclipse.jdt.internal.compiler.lookup.ClassScope;
import org.eclipse.jdt.internal.compiler.lookup.FieldBinding;
import org.eclipse.jdt.internal.compiler.lookup.MethodScope;
import org.eclipse.jdt.internal.compiler.lookup.SourceTypeBinding;
import org.eclipse.jdt.internal.compiler.lookup.SyntheticMethodBinding;
import org.eclipse.jdt.internal.compiler.lookup.TypeConstants;
import org.eclipse.jdt.internal.compiler.parser.Parser;
import org.eclipse.jdt.internal.compiler.problem.AbortMethod;

/**
 * OTDT changes:
 * What: No assignment analysis for copied fields (initialized in copied code).
 *
 * What: detect and report roleCantInitializeStaticField().
 */
public class Clinit extends AbstractMethodDeclaration {
	private static int ENUM_CONSTANTS_THRESHOLD = 2000;

	private FieldBinding assertionSyntheticFieldBinding = null;
	private FieldBinding classLiteralSyntheticField = null;

	public Clinit(CompilationResult compilationResult) {
		super(compilationResult);
		this.modifiers = 0;
		this.selector = TypeConstants.CLINIT;
	}

	public void analyseCode(
		ClassScope classScope,
		InitializationFlowContext staticInitializerFlowContext,
		FlowInfo flowInfo) {

		if (this.ignoreFurtherInvestigation)
			return;
		try {
			ExceptionHandlingFlowContext clinitContext =
				new ExceptionHandlingFlowContext(
					staticInitializerFlowContext.parent,
					this,
					Binding.NO_EXCEPTIONS,
					staticInitializerFlowContext,
					this.scope,
					FlowInfo.DEAD_END);

			// check for missing returning path
			if ((flowInfo.tagBits & FlowInfo.UNREACHABLE_OR_DEAD) == 0) {
				this.bits |= ASTNode.NeedFreeReturn;
			}

			// check missing blank final field initializations
			flowInfo = flowInfo.mergedWith(staticInitializerFlowContext.initsOnReturn);
			FieldBinding[] fields = this.scope.enclosingSourceType().fields();
			for (int i = 0, count = fields.length; i < count; i++) {
				FieldBinding field;
				if ((field = fields[i]).isStatic()
					&& field.isFinal()
//{ObjectTeams: don't check copied fields:
					&& (field.copyInheritanceSrc == null)
// SH}
					&& (!flowInfo.isDefinitelyAssigned(fields[i]))) {
					this.scope.problemReporter().uninitializedBlankFinalField(
						field,
						this.scope.referenceType().declarationOf(field.original()));
					// can complain against the field decl, since only one <clinit>
				}
			}
			// check static initializers thrown exceptions
			staticInitializerFlowContext.checkInitializerExceptions(
				this.scope,
				clinitContext,
				flowInfo);
		} catch (AbortMethod e) {
			this.ignoreFurtherInvestigation = true;
		}
	}

	/**
	 * Bytecode generation for a <clinit> method
	 *
	 * @param classScope org.eclipse.jdt.internal.compiler.lookup.ClassScope
	 * @param classFile org.eclipse.jdt.internal.compiler.codegen.ClassFile
	 */
	public void generateCode(ClassScope classScope, ClassFile classFile) {

		int clinitOffset = 0;
		if (this.ignoreFurtherInvestigation) {
			// should never have to add any <clinit> problem method
			return;
		}
		boolean restart = false;
		do {
			try {
				clinitOffset = classFile.contentsOffset;
				this.generateCode(classScope, classFile, clinitOffset);
				restart = false;
			} catch (AbortMethod e) {
				// should never occur
				// the clinit referenceContext is the type declaration
				// All clinit problems will be reported against the type: AbortType instead of AbortMethod
				// reset the contentsOffset to the value before generating the clinit code
				// decrement the number of method info as well.
				// This is done in the addProblemMethod and addProblemConstructor for other
				// cases.
				if (e.compilationResult == CodeStream.RESTART_IN_WIDE_MODE) {
					// a branch target required a goto_w, restart code gen in wide mode.
					classFile.contentsOffset = clinitOffset;
					classFile.methodCount--;
					classFile.codeStream.resetInWideMode(); // request wide mode
					// restart method generation
					restart = true;
				} else if (e.compilationResult == CodeStream.RESTART_CODE_GEN_FOR_UNUSED_LOCALS_MODE) {
					classFile.contentsOffset = clinitOffset;
					classFile.methodCount--;
					classFile.codeStream.resetForCodeGenUnusedLocals();
					// restart method generation
					restart = true;
				} else {
					// produce a problem method accounting for this fatal error
					classFile.contentsOffset = clinitOffset;
					classFile.methodCount--;
					restart = false;
				}
			}
		} while (restart);
	}

	/**
	 * Bytecode generation for a <clinit> method
	 *
	 * @param classScope org.eclipse.jdt.internal.compiler.lookup.ClassScope
	 * @param classFile org.eclipse.jdt.internal.compiler.codegen.ClassFile
	 */
	private void generateCode(
		ClassScope classScope,
		ClassFile classFile,
		int clinitOffset) {

		ConstantPool constantPool = classFile.constantPool;
		int constantPoolOffset = constantPool.currentOffset;
		int constantPoolIndex = constantPool.currentIndex;
		classFile.generateMethodInfoHeaderForClinit();
		int codeAttributeOffset = classFile.contentsOffset;
		classFile.generateCodeAttributeHeader();
		CodeStream codeStream = classFile.codeStream;
		resolve(classScope);

		codeStream.reset(this, classFile);
		TypeDeclaration declaringType = classScope.referenceContext;

		// initialize local positions - including initializer scope.
		MethodScope staticInitializerScope = declaringType.staticInitializerScope;
		staticInitializerScope.computeLocalVariablePositions(0, codeStream);

		// 1.4 feature
		// This has to be done before any other initialization
		if (this.assertionSyntheticFieldBinding != null) {
			// generate code related to the activation of assertion for this class
			codeStream.generateClassLiteralAccessForType(
					classScope.outerMostClassScope().enclosingSourceType(),
					this.classLiteralSyntheticField);
			codeStream.invokeJavaLangClassDesiredAssertionStatus();
			BranchLabel falseLabel = new BranchLabel(codeStream);
			codeStream.ifne(falseLabel);
			codeStream.iconst_1();
			BranchLabel jumpLabel = new BranchLabel(codeStream);
			codeStream.decrStackSize(1);
			codeStream.goto_(jumpLabel);
			falseLabel.place();
			codeStream.iconst_0();
			jumpLabel.place();
			codeStream.fieldAccess(Opcodes.OPC_putstatic, this.assertionSyntheticFieldBinding, null /* default declaringClass */);
		}
		// generate static fields/initializers/enum constants
		final FieldDeclaration[] fieldDeclarations = declaringType.fields;
		int sourcePosition = -1;
		int remainingFieldCount = 0;
		if (TypeDeclaration.kind(declaringType.modifiers) == TypeDeclaration.ENUM_DECL) {
			int enumCount = declaringType.enumConstantsCounter;
			if (enumCount > ENUM_CONSTANTS_THRESHOLD) {
				// generate synthetic methods to initialize all the enum constants
				int begin = -1;
				int count = 0;
				if (fieldDeclarations != null) {
					int max = fieldDeclarations.length;
					for (int i = 0; i < max; i++) {
						FieldDeclaration fieldDecl = fieldDeclarations[i];
						if (fieldDecl.isStatic()) {
							if (fieldDecl.getKind() == AbstractVariableDeclaration.ENUM_CONSTANT) {
								if (begin == -1) {
									begin = i;
								}
								count++;
								if (count > ENUM_CONSTANTS_THRESHOLD) {
									SyntheticMethodBinding syntheticMethod = declaringType.binding.addSyntheticMethodForEnumInitialization(begin, i);
									codeStream.invoke(Opcodes.OPC_invokestatic, syntheticMethod, null /* default declaringClass */);
									begin = i;
									count = 1;
								}
							} else {
								remainingFieldCount++;
							}
						}
					}
					if (count != 0) {
						// add last synthetic method
						SyntheticMethodBinding syntheticMethod = declaringType.binding.addSyntheticMethodForEnumInitialization(begin, max);
						codeStream.invoke(Opcodes.OPC_invokestatic, syntheticMethod, null /* default declaringClass */);
					}
				}
			} else if (fieldDeclarations != null) {
				for (int i = 0, max = fieldDeclarations.length; i < max; i++) {
					FieldDeclaration fieldDecl = fieldDeclarations[i];
					if (fieldDecl.isStatic()) {
						if (fieldDecl.getKind() == AbstractVariableDeclaration.ENUM_CONSTANT) {
							fieldDecl.generateCode(staticInitializerScope, codeStream);
						} else {
							remainingFieldCount++;
						}
					}
				}
			}
			// enum need to initialize $VALUES synthetic cache of enum constants
			// $VALUES := new <EnumType>[<enumCount>]
			codeStream.generateInlinedValue(enumCount);
			codeStream.anewarray(declaringType.binding);
			if (enumCount > 0) {
				if (fieldDeclarations != null) {
					for (int i = 0, max = fieldDeclarations.length; i < max; i++) {
						FieldDeclaration fieldDecl = fieldDeclarations[i];
						// $VALUES[i] = <enum-constant-i>
						if (fieldDecl.getKind() == AbstractVariableDeclaration.ENUM_CONSTANT) {
							codeStream.dup();
							codeStream.generateInlinedValue(fieldDecl.binding.id);
							codeStream.fieldAccess(Opcodes.OPC_getstatic, fieldDecl.binding, null /* default declaringClass */);
							codeStream.aastore();
						}
					}
				}
			}
			codeStream.fieldAccess(Opcodes.OPC_putstatic, declaringType.enumValuesSyntheticfield, null /* default declaringClass */);
			if (remainingFieldCount != 0) {
				// if fields that are not enum constants need to be generated (static initializer/static field)
				for (int i = 0, max = fieldDeclarations.length; i < max && remainingFieldCount >= 0; i++) {
					FieldDeclaration fieldDecl = fieldDeclarations[i];
					switch (fieldDecl.getKind()) {
						case AbstractVariableDeclaration.ENUM_CONSTANT :
							break;
						case AbstractVariableDeclaration.INITIALIZER :
							if (!fieldDecl.isStatic())
								break;
							sourcePosition = ((Initializer) fieldDecl).block.sourceEnd;
							fieldDecl.generateCode(staticInitializerScope, codeStream);
							break;
						case AbstractVariableDeclaration.FIELD :
							if (!fieldDecl.binding.isStatic())
								break;
							sourcePosition = fieldDecl.declarationEnd;
							fieldDecl.generateCode(staticInitializerScope, codeStream);
							break;
					}
				}
			}
		} else {
			if (fieldDeclarations != null) {
				for (int i = 0, max = fieldDeclarations.length; i < max; i++) {
					FieldDeclaration fieldDecl = fieldDeclarations[i];
					switch (fieldDecl.getKind()) {
						case AbstractVariableDeclaration.INITIALIZER :
							if (!fieldDecl.isStatic())
								break;
//{ObjectTeams: note: static initializer in inner type is already prohibited in Java. SH}//
							sourcePosition = ((Initializer) fieldDecl).block.sourceEnd;
							fieldDecl.generateCode(staticInitializerScope, codeStream);
							break;
						case AbstractVariableDeclaration.FIELD :
							if (!fieldDecl.binding.isStatic())
								break;
//{ObjectTeams: roles cannot initialize static fields with non-constant values:
							int previousPosition = codeStream.position;
// orig:
							fieldDecl.generateCode(staticInitializerScope, codeStream);
// :giro
							if (  previousPosition != codeStream.position // field has indeed generated code
								&& classScope.referenceContext.isRole())
							{
								classScope.problemReporter().roleCantInitializeStaticField(fieldDecl);
							}
// SH}
							break;
					}
				}
			}
//{ObjectTeams: also analyze fields in the interface part:
			if (declaringType.isRole() && declaringType.getRoleModel() != null) {
				TypeDeclaration ifcPart = declaringType.getRoleModel().getInterfaceAst();
				if (ifcPart != null && ifcPart.fields != null)
					for (FieldDeclaration ifcField : ifcPart.fields)
						if (ifcField.binding.constant() == Constant.NotAConstant)
							classScope.problemReporter().roleCantInitializeStaticField(ifcField);
			}
// SH}
		}

		if (codeStream.position == 0) {
			// do not need to output a Clinit if no bytecodes
			// so we reset the offset inside the byte array contents.
			classFile.contentsOffset = clinitOffset;
			// like we don't addd a method we need to undo the increment on the method count
			classFile.methodCount--;
			// reset the constant pool to its state before the clinit
			constantPool.resetForClinit(constantPoolIndex, constantPoolOffset);
		} else {
			if ((this.bits & ASTNode.NeedFreeReturn) != 0) {
				int before = codeStream.position;
				codeStream.return_();
				if (sourcePosition != -1) {
					// expand the last initializer variables to include the trailing return
					codeStream.recordPositionsFrom(before, sourcePosition);
				}
			}
			// Record the end of the clinit: point to the declaration of the class
			codeStream.recordPositionsFrom(0, declaringType.sourceStart);
			classFile.completeCodeAttributeForClinit(codeAttributeOffset);
		}
	}

	public boolean isClinit() {

		return true;
	}

	public boolean isInitializationMethod() {

		return true;
	}

	public boolean isStatic() {

		return true;
	}

	public void parseStatements(Parser parser, CompilationUnitDeclaration unit) {
		//the clinit is filled by hand ....
	}

	public StringBuffer print(int tab, StringBuffer output) {

		printIndent(tab, output).append("<clinit>()"); //$NON-NLS-1$
		printBody(tab + 1, output);
		return output;
	}

	public void resolve(ClassScope classScope) {

		this.scope = new MethodScope(classScope, classScope.referenceContext, true);
	}

	public void traverse(
		ASTVisitor visitor,
		ClassScope classScope) {

		visitor.visit(this, classScope);
		visitor.endVisit(this, classScope);
	}

	public void setAssertionSupport(FieldBinding assertionSyntheticFieldBinding, boolean needClassLiteralField) {

		this.assertionSyntheticFieldBinding = assertionSyntheticFieldBinding;

		// we need to add the field right now, because the field infos are generated before the methods
		if (needClassLiteralField) {
			SourceTypeBinding sourceType =
				this.scope.outerMostClassScope().enclosingSourceType();
			// see https://bugs.eclipse.org/bugs/show_bug.cgi?id=22334
			if (!sourceType.isInterface() && !sourceType.isBaseType()) {
				this.classLiteralSyntheticField = sourceType.addSyntheticFieldForClassLiteral(sourceType, this.scope);
			}
		}
	}

}

Back to the top