1 /*******************************************************************************
2  * Copyright (c) 2000, 2013 IBM Corporation and others.
3  * All rights reserved. This program and the accompanying materials
4  * are made available under the terms of the Eclipse Public License v1.0
5  * which accompanies this distribution, and is available at
6  * http://www.eclipse.org/legal/epl-v10.html
7  *
8  * Contributors:
9  *     IBM Corporation - initial API and implementation
10  *     Stephan Herrmann <stephan@cs.tu-berlin.de> - Contributions for
11  *								bug 185682 - Increment/decrement operators mark local variables as read
12  *								bug 331649 - [compiler][null] consider null annotations for fields
13  *								Bug 417295 - [1.8[[null] Massage type annotated null analysis to gel well with deep encoded type bindings.
14  *******************************************************************************/
15 package org.eclipse.jdt.internal.compiler.lookup;
16 
17 import org.eclipse.jdt.core.compiler.CharOperation;
18 import org.eclipse.jdt.internal.compiler.ast.ASTNode;
19 import org.eclipse.jdt.internal.compiler.ast.FieldDeclaration;
20 import org.eclipse.jdt.internal.compiler.ast.TypeDeclaration;
21 import org.eclipse.jdt.internal.compiler.classfmt.ClassFileConstants;
22 import org.eclipse.jdt.internal.compiler.impl.Constant;
23 
24 public class FieldBinding extends VariableBinding {
25 	public ReferenceBinding declaringClass;
26 	public int compoundUseFlag = 0; // number or accesses via postIncrement or compoundAssignment
27 
FieldBinding()28 protected FieldBinding() {
29 	super(null, null, 0, null);
30 	// for creating problem field
31 }
FieldBinding(char[] name, TypeBinding type, int modifiers, ReferenceBinding declaringClass, Constant constant)32 public FieldBinding(char[] name, TypeBinding type, int modifiers, ReferenceBinding declaringClass, Constant constant) {
33 	super(name, type, modifiers, constant);
34 	this.declaringClass = declaringClass;
35 }
36 // special API used to change field declaring class for runtime visibility check
FieldBinding(FieldBinding initialFieldBinding, ReferenceBinding declaringClass)37 public FieldBinding(FieldBinding initialFieldBinding, ReferenceBinding declaringClass) {
38 	super(initialFieldBinding.name, initialFieldBinding.type, initialFieldBinding.modifiers, initialFieldBinding.constant());
39 	this.declaringClass = declaringClass;
40 	this.id = initialFieldBinding.id;
41 	setAnnotations(initialFieldBinding.getAnnotations());
42 }
43 /* API
44 * Answer the receiver's binding type from Binding.BindingID.
45 */
FieldBinding(FieldDeclaration field, TypeBinding type, int modifiers, ReferenceBinding declaringClass)46 public FieldBinding(FieldDeclaration field, TypeBinding type, int modifiers, ReferenceBinding declaringClass) {
47 	this(field.name, type, modifiers, declaringClass, null);
48 	field.binding = this; // record binding in declaration
49 }
50 
canBeSeenBy(PackageBinding invocationPackage)51 public final boolean canBeSeenBy(PackageBinding invocationPackage) {
52 	if (isPublic()) return true;
53 	if (isPrivate()) return false;
54 
55 	// isProtected() or isDefault()
56 	return invocationPackage == this.declaringClass.getPackage();
57 }
58 /* Answer true if the receiver is visible to the type provided by the scope.
59 * InvocationSite implements isSuperAccess() to provide additional information
60 * if the receiver is protected.
61 *
62 * NOTE: Cannot invoke this method with a compilation unit scope.
63 */
64 
canBeSeenBy(TypeBinding receiverType, InvocationSite invocationSite, Scope scope)65 public final boolean canBeSeenBy(TypeBinding receiverType, InvocationSite invocationSite, Scope scope) {
66 	if (isPublic()) return true;
67 
68 	SourceTypeBinding invocationType = scope.enclosingSourceType();
69 	if (TypeBinding.equalsEquals(invocationType, this.declaringClass) && TypeBinding.equalsEquals(invocationType, receiverType)) return true;
70 
71 	if (invocationType == null) // static import call
72 		return !isPrivate() && scope.getCurrentPackage() == this.declaringClass.fPackage;
73 
74 	if (isProtected()) {
75 		// answer true if the invocationType is the declaringClass or they are in the same package
76 		// OR the invocationType is a subclass of the declaringClass
77 		//    AND the receiverType is the invocationType or its subclass
78 		//    OR the method is a static method accessed directly through a type
79 		//    OR previous assertions are true for one of the enclosing type
80 		if (TypeBinding.equalsEquals(invocationType, this.declaringClass)) return true;
81 		if (invocationType.fPackage == this.declaringClass.fPackage) return true;
82 
83 		ReferenceBinding currentType = invocationType;
84 		int depth = 0;
85 		ReferenceBinding receiverErasure = (ReferenceBinding)receiverType.erasure();
86 		ReferenceBinding declaringErasure = (ReferenceBinding) this.declaringClass.erasure();
87 		do {
88 			if (currentType.findSuperTypeOriginatingFrom(declaringErasure) != null) {
89 				if (invocationSite.isSuperAccess())
90 					return true;
91 				// receiverType can be an array binding in one case... see if you can change it
92 				if (receiverType instanceof ArrayBinding)
93 					return false;
94 				if (isStatic()) {
95 					if (depth > 0) invocationSite.setDepth(depth);
96 					return true; // see 1FMEPDL - return invocationSite.isTypeAccess();
97 				}
98 				if (TypeBinding.equalsEquals(currentType, receiverErasure) || receiverErasure.findSuperTypeOriginatingFrom(currentType) != null) {
99 					if (depth > 0) invocationSite.setDepth(depth);
100 					return true;
101 				}
102 			}
103 			depth++;
104 			currentType = currentType.enclosingType();
105 		} while (currentType != null);
106 		return false;
107 	}
108 
109 	if (isPrivate()) {
110 		// answer true if the receiverType is the declaringClass
111 		// AND the invocationType and the declaringClass have a common enclosingType
112 		receiverCheck: {
113 			if (TypeBinding.notEquals(receiverType, this.declaringClass)) {
114 				// special tolerance for type variable direct bounds, but only if compliance <= 1.6, see: https://bugs.eclipse.org/bugs/show_bug.cgi?id=334622
115 				if (scope.compilerOptions().complianceLevel <= ClassFileConstants.JDK1_6 && receiverType.isTypeVariable() && ((TypeVariableBinding) receiverType).isErasureBoundTo(this.declaringClass.erasure()))
116 					break receiverCheck;
117 				return false;
118 			}
119 		}
120 
121 		if (TypeBinding.notEquals(invocationType, this.declaringClass)) {
122 			ReferenceBinding outerInvocationType = invocationType;
123 			ReferenceBinding temp = outerInvocationType.enclosingType();
124 			while (temp != null) {
125 				outerInvocationType = temp;
126 				temp = temp.enclosingType();
127 			}
128 
129 			ReferenceBinding outerDeclaringClass = (ReferenceBinding) this.declaringClass.erasure();
130 			temp = outerDeclaringClass.enclosingType();
131 			while (temp != null) {
132 				outerDeclaringClass = temp;
133 				temp = temp.enclosingType();
134 			}
135 			if (TypeBinding.notEquals(outerInvocationType, outerDeclaringClass)) return false;
136 		}
137 		return true;
138 	}
139 
140 	// isDefault()
141 	PackageBinding declaringPackage = this.declaringClass.fPackage;
142 	if (invocationType.fPackage != declaringPackage) return false;
143 
144 	// receiverType can be an array binding in one case... see if you can change it
145 	if (receiverType instanceof ArrayBinding)
146 		return false;
147 	TypeBinding originalDeclaringClass = this.declaringClass.original();
148 	ReferenceBinding currentType = (ReferenceBinding) receiverType;
149 	do {
150 		if (currentType.isCapture()) { // https://bugs.eclipse.org/bugs/show_bug.cgi?id=285002
151 			if (TypeBinding.equalsEquals(originalDeclaringClass, currentType.erasure().original())) return true;
152 		} else {
153 			if (TypeBinding.equalsEquals(originalDeclaringClass, currentType.original())) return true;
154 		}
155 		PackageBinding currentPackage = currentType.fPackage;
156 		// package could be null for wildcards/intersection types, ignore and recurse in superclass
157 		if (currentPackage != null && currentPackage != declaringPackage) return false;
158 	} while ((currentType = currentType.superclass()) != null);
159 	return false;
160 }
161 
162 /*
163  * declaringUniqueKey dot fieldName ) returnTypeUniqueKey
164  * p.X { X<T> x} --> Lp/X;.x)p/X<TT;>;
165  */
computeUniqueKey(boolean isLeaf)166 public char[] computeUniqueKey(boolean isLeaf) {
167 	// declaring key
168 	char[] declaringKey =
169 		this.declaringClass == null /*case of length field for an array*/
170 			? CharOperation.NO_CHAR
171 			: this.declaringClass.computeUniqueKey(false/*not a leaf*/);
172 	int declaringLength = declaringKey.length;
173 
174 	// name
175 	int nameLength = this.name.length;
176 
177 	// return type
178 	char[] returnTypeKey = this.type == null ? new char[] {'V'} : this.type.computeUniqueKey(false/*not a leaf*/);
179 	int returnTypeLength = returnTypeKey.length;
180 
181 	char[] uniqueKey = new char[declaringLength + 1 + nameLength + 1 + returnTypeLength];
182 	int index = 0;
183 	System.arraycopy(declaringKey, 0, uniqueKey, index, declaringLength);
184 	index += declaringLength;
185 	uniqueKey[index++] = '.';
186 	System.arraycopy(this.name, 0, uniqueKey, index, nameLength);
187 	index += nameLength;
188 	uniqueKey[index++] = ')';
189 	System.arraycopy(returnTypeKey, 0, uniqueKey, index, returnTypeLength);
190 	return uniqueKey;
191 }
constant()192 public Constant constant() {
193 	Constant fieldConstant = this.constant;
194 	if (fieldConstant == null) {
195 		if (isFinal()) {
196 			//The field has not been yet type checked.
197 			//It also means that the field is not coming from a class that
198 			//has already been compiled. It can only be from a class within
199 			//compilation units to process. Thus the field is NOT from a BinaryTypeBinbing
200 			FieldBinding originalField = original();
201 			if (originalField.declaringClass instanceof SourceTypeBinding) {
202 				SourceTypeBinding sourceType = (SourceTypeBinding) originalField.declaringClass;
203 				if (sourceType.scope != null) {
204 					TypeDeclaration typeDecl = sourceType.scope.referenceContext;
205 					FieldDeclaration fieldDecl = typeDecl.declarationOf(originalField);
206 					MethodScope initScope = originalField.isStatic() ? typeDecl.staticInitializerScope : typeDecl.initializerScope;
207 					boolean old = initScope.insideTypeAnnotation;
208 					try {
209 						initScope.insideTypeAnnotation = false;
210 						fieldDecl.resolve(initScope); //side effect on binding
211 					} finally {
212 						initScope.insideTypeAnnotation = old;
213 					}
214 					fieldConstant = originalField.constant == null ? Constant.NotAConstant : originalField.constant;
215 				} else {
216 					fieldConstant = Constant.NotAConstant; // shouldn't occur per construction (paranoid null check)
217 				}
218 			} else {
219 				fieldConstant = Constant.NotAConstant; // shouldn't occur per construction (paranoid null check)
220 			}
221 		} else {
222 			fieldConstant = Constant.NotAConstant;
223 		}
224 		this.constant = fieldConstant;
225 	}
226 	return fieldConstant;
227 }
228 
fillInDefaultNonNullness(FieldDeclaration sourceField, Scope scope)229 public void fillInDefaultNonNullness(FieldDeclaration sourceField, Scope scope) {
230 	LookupEnvironment environment = scope.environment();
231 	if (   this.type != null
232 		&& !this.type.isBaseType()
233 		&& (this.tagBits & TagBits.AnnotationNullMASK) == 0)
234 	{
235 		if (environment.globalOptions.sourceLevel < ClassFileConstants.JDK1_8)
236 			this.tagBits |= TagBits.AnnotationNonNull;
237 		else
238 			this.type = environment.createAnnotatedType(this.type, new AnnotationBinding[]{environment.getNonNullAnnotation()});
239 	} else if ((this.tagBits & TagBits.AnnotationNonNull) != 0) {
240 		scope.problemReporter().nullAnnotationIsRedundant(sourceField);
241 	}
242 }
243 
244 /**
245  * X<T> t   -->  LX<TT;>;
246  */
genericSignature()247 public char[] genericSignature() {
248     if ((this.modifiers & ExtraCompilerModifiers.AccGenericSignature) == 0) return null;
249     return this.type.genericTypeSignature();
250 }
getAccessFlags()251 public final int getAccessFlags() {
252 	return this.modifiers & ExtraCompilerModifiers.AccJustFlag;
253 }
254 
getAnnotations()255 public AnnotationBinding[] getAnnotations() {
256 	FieldBinding originalField = original();
257 	ReferenceBinding declaringClassBinding = originalField.declaringClass;
258 	if (declaringClassBinding == null) {
259 		return Binding.NO_ANNOTATIONS;
260 	}
261 	return declaringClassBinding.retrieveAnnotations(originalField);
262 }
263 
264 /**
265  * Compute the tagbits for standard annotations. For source types, these could require
266  * lazily resolving corresponding annotation nodes, in case of forward references.
267  * @see org.eclipse.jdt.internal.compiler.lookup.Binding#getAnnotationTagBits()
268  */
getAnnotationTagBits()269 public long getAnnotationTagBits() {
270 	FieldBinding originalField = original();
271 	if ((originalField.tagBits & TagBits.AnnotationResolved) == 0 && originalField.declaringClass instanceof SourceTypeBinding) {
272 		ClassScope scope = ((SourceTypeBinding) originalField.declaringClass).scope;
273 		if (scope == null) { // synthetic fields do not have a scope nor any annotations
274 			this.tagBits |= (TagBits.AnnotationResolved | TagBits.DeprecatedAnnotationResolved);
275 			return 0;
276 		}
277 		TypeDeclaration typeDecl = scope.referenceContext;
278 		FieldDeclaration fieldDecl = typeDecl.declarationOf(originalField);
279 		if (fieldDecl != null) {
280 			MethodScope initializationScope = isStatic() ? typeDecl.staticInitializerScope : typeDecl.initializerScope;
281 			FieldBinding previousField = initializationScope.initializedField;
282 			int previousFieldID = initializationScope.lastVisibleFieldID;
283 			try {
284 				initializationScope.initializedField = originalField;
285 				initializationScope.lastVisibleFieldID = originalField.id;
286 				ASTNode.resolveAnnotations(initializationScope, fieldDecl.annotations, originalField);
287 			} finally {
288 				initializationScope.initializedField = previousField;
289 				initializationScope.lastVisibleFieldID = previousFieldID;
290 			}
291 		}
292 	}
293 	return originalField.tagBits;
294 }
295 
isDefault()296 public final boolean isDefault() {
297 	return !isPublic() && !isProtected() && !isPrivate();
298 }
299 /* Answer true if the receiver is a deprecated field
300 */
301 
302 /* Answer true if the receiver has default visibility
303 */
304 
isDeprecated()305 public final boolean isDeprecated() {
306 	return (this.modifiers & ClassFileConstants.AccDeprecated) != 0;
307 }
308 /* Answer true if the receiver has private visibility
309 */
310 
isPrivate()311 public final boolean isPrivate() {
312 	return (this.modifiers & ClassFileConstants.AccPrivate) != 0;
313 }
314 /* Answer true if the receiver has private visibility or is enclosed by a class that does.
315 */
316 
isOrEnclosedByPrivateType()317 public final boolean isOrEnclosedByPrivateType() {
318 	if ((this.modifiers & ClassFileConstants.AccPrivate) != 0)
319 		return true;
320 	return this.declaringClass != null && this.declaringClass.isOrEnclosedByPrivateType();
321 }
322 /* Answer true if the receiver has private visibility and is used locally
323 */
324 
isProtected()325 public final boolean isProtected() {
326 	return (this.modifiers & ClassFileConstants.AccProtected) != 0;
327 }
328 /* Answer true if the receiver has public visibility
329 */
330 
isPublic()331 public final boolean isPublic() {
332 	return (this.modifiers & ClassFileConstants.AccPublic) != 0;
333 }
334 /* Answer true if the receiver is a static field
335 */
336 
isStatic()337 public final boolean isStatic() {
338 	return (this.modifiers & ClassFileConstants.AccStatic) != 0;
339 }
340 /* Answer true if the receiver is not defined in the source of the declaringClass
341 */
342 
isSynthetic()343 public final boolean isSynthetic() {
344 	return (this.modifiers & ClassFileConstants.AccSynthetic) != 0;
345 }
346 /* Answer true if the receiver is a transient field
347 */
348 
isTransient()349 public final boolean isTransient() {
350 	return (this.modifiers & ClassFileConstants.AccTransient) != 0;
351 }
352 /* Answer true if the receiver's declaring type is deprecated (or any of its enclosing types)
353 */
354 
isUsed()355 public final boolean isUsed() {
356 	return (this.modifiers & ExtraCompilerModifiers.AccLocallyUsed) != 0 || this.compoundUseFlag > 0;
357 }
358 /* Answer true if the only use of this field is in compound assignment or post increment
359  */
360 
isUsedOnlyInCompound()361 public final boolean isUsedOnlyInCompound() {
362 	return (this.modifiers & ExtraCompilerModifiers.AccLocallyUsed) == 0 && this.compoundUseFlag > 0;
363 }
364 /* Answer true if the receiver has protected visibility
365 */
366 
isViewedAsDeprecated()367 public final boolean isViewedAsDeprecated() {
368 	return (this.modifiers & (ClassFileConstants.AccDeprecated | ExtraCompilerModifiers.AccDeprecatedImplicitly)) != 0;
369 }
370 /* Answer true if the receiver is a volatile field
371 */
372 
isVolatile()373 public final boolean isVolatile() {
374 	return (this.modifiers & ClassFileConstants.AccVolatile) != 0;
375 }
376 
kind()377 public final int kind() {
378 	return FIELD;
379 }
380 /* Answer true if the receiver is visible to the invocationPackage.
381 */
382 /**
383  * Returns the original field (as opposed to parameterized instances)
384  */
original()385 public FieldBinding original() {
386 	return this;
387 }
setAnnotations(AnnotationBinding[] annotations)388 public void setAnnotations(AnnotationBinding[] annotations) {
389 	this.declaringClass.storeAnnotations(this, annotations);
390 }
sourceField()391 public FieldDeclaration sourceField() {
392 	SourceTypeBinding sourceType;
393 	try {
394 		sourceType = (SourceTypeBinding) this.declaringClass;
395 	} catch (ClassCastException e) {
396 		return null;
397 	}
398 
399 	FieldDeclaration[] fields = sourceType.scope.referenceContext.fields;
400 	if (fields != null) {
401 		for (int i = fields.length; --i >= 0;)
402 			if (this == fields[i].binding)
403 				return fields[i];
404 	}
405 	return null;
406 }
407 }
408