View | Details | Raw Unified | Return to bug 186342 | Differences between
and this patch

Collapse All | Expand All

(-)batch/org/eclipse/jdt/internal/compiler/batch/Main.java (-3 / +26 lines)
Lines 1-5 Link Here
1
/*******************************************************************************
1
/*******************************************************************************
2
 * Copyright (c) 2000, 2010 IBM Corporation and others.
2
 * Copyright (c) 2000, 2011 IBM Corporation and others.
3
 * All rights reserved. This program and the accompanying materials
3
 * All rights reserved. This program and the accompanying materials
4
 * are made available under the terms of the Eclipse Public License v1.0
4
 * are made available under the terms of the Eclipse Public License v1.0
5
 * which accompanies this distribution, and is available at
5
 * which accompanies this distribution, and is available at
Lines 10-17 Link Here
10
 *     Tom Tromey - Contribution for bug 125961
10
 *     Tom Tromey - Contribution for bug 125961
11
 *     Tom Tromey - Contribution for bug 159641
11
 *     Tom Tromey - Contribution for bug 159641
12
 *     Benjamin Muskalla - Contribution for bug 239066
12
 *     Benjamin Muskalla - Contribution for bug 239066
13
 *     Stephan Herrmann  - Contribution for bug 236385
13
 *     Stephan Herrmann  - Contributions for 
14
 *     Stephan Herrmann  - Contribution for bug 295551
14
 *     							bug 236385 - [compiler] Warn for potential programming problem if an object is created but not used
15
 *     							bug 295551 - Add option to automatically promote all warnings to errors 
16
 *     							bug 186342 - [compiler][null]Using annotations for null checking
15
 *******************************************************************************/
17
 *******************************************************************************/
16
package org.eclipse.jdt.internal.compiler.batch;
18
package org.eclipse.jdt.internal.compiler.batch;
17
19
Lines 2388-2393 Link Here
2388
					mode = INSIDE_WARNINGS_PROPERTIES;
2390
					mode = INSIDE_WARNINGS_PROPERTIES;
2389
					continue;
2391
					continue;
2390
				}
2392
				}
2393
				if (currentArg.startsWith("-nullAnnotations:")) { //$NON-NLS-1$
2394
					StringTokenizer tokenizer =
2395
						new StringTokenizer(currentArg.substring("-nullAnnotations:".length()), ","); //$NON-NLS-1$ //$NON-NLS-2$
2396
					while (tokenizer.hasMoreTokens()) {
2397
						String token = tokenizer.nextToken();
2398
						if (token.startsWith("nullable=")) { //$NON-NLS-1$
2399
							this.options.put(CompilerOptions.OPTION_NullableAnnotationName, token.substring("nullable=".length())); //$NON-NLS-1$
2400
						} else if (token.startsWith("nonnull=")) { //$NON-NLS-1$
2401
							this.options.put(CompilerOptions.OPTION_NonNullAnnotationName, token.substring("nonnull=".length())); //$NON-NLS-1$
2402
						} else if (token.equals("emulate")) { //$NON-NLS-1$
2403
							this.options.put(CompilerOptions.OPTION_EmulateNullAnnotationTypes, CompilerOptions.ENABLED);
2404
						} else if (token.equals("import")) { //$NON-NLS-1$
2405
							this.options.put(CompilerOptions.OPTION_DefaultImportNullAnnotationTypes, CompilerOptions.ENABLED);
2406
						} else {
2407
							throw new IllegalArgumentException(
2408
								this.bind("configure.unrecognized.nullannotation.option", token)); //$NON-NLS-1$
2409
						}
2410
					}
2411
					mode = DEFAULT;
2412
					continue;
2413
				}
2391
				break;
2414
				break;
2392
			case INSIDE_TARGET :
2415
			case INSIDE_TARGET :
2393
				if (this.didSpecifyTarget) {
2416
				if (this.didSpecifyTarget) {
(-)batch/org/eclipse/jdt/internal/compiler/batch/messages.properties (-1 / +19 lines)
Lines 1-5 Link Here
1
###############################################################################
1
###############################################################################
2
# Copyright (c) 2000, 2010 IBM Corporation and others.
2
# Copyright (c) 2000, 2011 IBM Corporation and others.
3
# All rights reserved. This program and the accompanying materials
3
# All rights reserved. This program and the accompanying materials
4
# are made available under the terms of the Eclipse Public License v1.0
4
# are made available under the terms of the Eclipse Public License v1.0
5
# which accompanies this distribution, and is available at
5
# which accompanies this distribution, and is available at
Lines 8-13 Link Here
8
# Contributors:
8
# Contributors:
9
#     IBM Corporation - initial API and implementation
9
#     IBM Corporation - initial API and implementation
10
#		Benjamin Muskalla - Contribution for bug 239066
10
#		Benjamin Muskalla - Contribution for bug 239066
11
#       Stephan Herrmann  - Contribution for bug 186342 - [compiler][null]Using annotations for null checking
11
###############################################################################
12
###############################################################################
12
### JavaBatchCompiler messages.
13
### JavaBatchCompiler messages.
13
14
Lines 71-76 Link Here
71
72
72
## configure.directoryNotExist = directory does not exist: {0}
73
## configure.directoryNotExist = directory does not exist: {0}
73
configure.unrecognizedOption = Unrecognized option : {0}
74
configure.unrecognizedOption = Unrecognized option : {0}
75
configure.unrecognized.nullannotation.option = Unrecognized sub-option of -nullAnnotations: {0},\nlegal values are 'nullable=..', 'nonnull=..', 'emulate' and 'import'
74
configure.noClasspath = no classpath defined, using default directory instead
76
configure.noClasspath = no classpath defined, using default directory instead
75
configure.incorrectClasspath = incorrect classpath: {0}
77
configure.incorrectClasspath = incorrect classpath: {0}
76
configure.invalidexpansionargumentname = expansion argument file {0} does not exist or cannot be read
78
configure.invalidexpansionargumentname = expansion argument file {0} does not exist or cannot be read
Lines 222-227 Link Here
222
\    -classNames <className1[,className2,...]>\n\
224
\    -classNames <className1[,className2,...]>\n\
223
\                         qualified names of binary classes to process\n\
225
\                         qualified names of binary classes to process\n\
224
\ \n\
226
\ \n\
227
\ Null annotation options:\n\
228
\    -nullAnnotations:<suboptions>\n\
229
\                      enable use of annotations for specifying null contracts;\n\
230
\                      <suboptions> is a non-empty, comma-separated list of:\n\
231
\        nullable=<typename>\n\
232
\                      specifies the fully qualified name of an annotation type\n\
233
\                      to be used for marking types whose values include null\n\
234
\        nonnull=<typename>\n\
235
\                      specifies the fully qualified name of an annotation type\n\
236
\                      to be used for marking types whose values cannot be null\n\
237
\        emulate       tells the compiler to emulate the above annotation types\n\
238
\                      although they do not exist on the classpath\n\
239
\        import        tells the compiler to import the above annotation types\n\
240
\                      without specific mention in the sources such that their\n\
241
\                      simple names can be used without explicit imports\n\
242
\ \n\
225
\ Advanced options:\n\
243
\ Advanced options:\n\
226
\    @<file>            read command line arguments from file\n\
244
\    @<file>            read command line arguments from file\n\
227
\    -maxProblems <n>   max number of problems per compilation unit (100 by\n\
245
\    -maxProblems <n>   max number of problems per compilation unit (100 by\n\
(-)compiler/org/eclipse/jdt/core/compiler/IProblem.java (-2 / +37 lines)
Lines 1-5 Link Here
1
/*******************************************************************************
1
/*******************************************************************************
2
 * Copyright (c) 2000, 2010 IBM Corporation and others.
2
 * Copyright (c) 2000, 2011 IBM Corporation and others.
3
 * All rights reserved. This program and the accompanying materials
3
 * All rights reserved. This program and the accompanying materials
4
 * are made available under the terms of the Eclipse Public License v1.0
4
 * are made available under the terms of the Eclipse Public License v1.0
5
 * which accompanies this distribution, and is available at
5
 * which accompanies this distribution, and is available at
Lines 116-122 Link Here
116
 *		Benjamin Muskalla - added the following constants
116
 *		Benjamin Muskalla - added the following constants
117
 *									MissingSynchronizedModifierInInheritedMethod
117
 *									MissingSynchronizedModifierInInheritedMethod
118
 *		Stephan Herrmann  - added the following constants
118
 *		Stephan Herrmann  - added the following constants
119
 *									UnusedObjectAllocation									
119
 *									UnusedObjectAllocation
120
 *									DefiniteNullFromNonNullMethod
121
 *									PotentialNullFromNonNullMethod
122
 *									NonNullReturnInsufficientInfo
123
 *									DefiniteNullToNonnullParameter
124
 *									PotentialNullToNonnullParameter
125
 *									NonNullParameterInsufficientInfo
126
 *									ConflictingTypeEmulation
127
 *									IllegalRedefinitionToNullableReturn
128
 *									IllegalRedefinitionToNonNullParameter
120
 *******************************************************************************/
129
 *******************************************************************************/
121
package org.eclipse.jdt.core.compiler;
130
package org.eclipse.jdt.core.compiler;
122
131
Lines 1340-1345 Link Here
1340
	int JavadocTypeArgumentsForRawGenericConstructor = Javadoc + Internal + 859;
1349
	int JavadocTypeArgumentsForRawGenericConstructor = Javadoc + Internal + 859;
1341
1350
1342
	/**
1351
	/**
1352
	 * Null Annotations
1353
	 */
1354
	/** @since 3.7 */
1355
	int DefiniteNullFromNonNullMethod = MethodRelated + 880;
1356
	/** @since 3.7 */
1357
	int PotentialNullFromNonNullMethod = MethodRelated + 881;
1358
	/** @since 3.7 */
1359
	int NonNullReturnInsufficientInfo = MethodRelated + 882;
1360
	/** @since 3.7 */
1361
	int DefiniteNullToNonnullParameter = MethodRelated + 883;
1362
	/** @since 3.7 */
1363
	int PotentialNullToNonnullParameter = MethodRelated + 884;
1364
	/** @since 3.7 */
1365
	int NonNullParameterInsufficientInfo = MethodRelated + 885;
1366
	/** @since 3.7 */
1367
	int ConflictingTypeEmulation = ImportRelated + 886;
1368
	/** @since 3.7 */
1369
	int MissingNullAnnotationType = ImportRelated + 887;
1370
	/** @since 3.7 */
1371
	int IllegalRedefinitionToNullableReturn = MethodRelated + 888;
1372
	/** @since 3.7 */
1373
	int IllegalRedefinitionToNonNullParameter = MethodRelated + 889;
1374
	/** @since 3.7 */
1375
	int IllegalDefinitionToNonNullParameter = MethodRelated + 890;
1376
1377
	/**
1343
	 * External problems -- These are problems defined by other plugins
1378
	 * External problems -- These are problems defined by other plugins
1344
	 */
1379
	 */
1345
1380
(-)compiler/org/eclipse/jdt/internal/compiler/ast/AbstractMethodDeclaration.java (-2 / +8 lines)
Lines 1-5 Link Here
1
/*******************************************************************************
1
/*******************************************************************************
2
 * Copyright (c) 2000, 2010 IBM Corporation and others.
2
 * Copyright (c) 2000, 2011 IBM Corporation and others.
3
 * All rights reserved. This program and the accompanying materials
3
 * All rights reserved. This program and the accompanying materials
4
 * are made available under the terms of the Eclipse Public License v1.0
4
 * are made available under the terms of the Eclipse Public License v1.0
5
 * which accompanies this distribution, and is available at
5
 * which accompanies this distribution, and is available at
Lines 7-12 Link Here
7
 *
7
 *
8
 * Contributors:
8
 * Contributors:
9
 *     IBM Corporation - initial API and implementation
9
 *     IBM Corporation - initial API and implementation
10
 *     Stephan Herrmann - Contribution for Bug 186342 - [compiler][null]Using annotations for null checking
10
 *******************************************************************************/
11
 *******************************************************************************/
11
package org.eclipse.jdt.internal.compiler.ast;
12
package org.eclipse.jdt.internal.compiler.ast;
12
13
Lines 100-105 Link Here
100
				} else if (paramAnnotations != null) {
101
				} else if (paramAnnotations != null) {
101
					paramAnnotations[i] = Binding.NO_ANNOTATIONS;
102
					paramAnnotations[i] = Binding.NO_ANNOTATIONS;
102
				}
103
				}
104
				// transfer nullness info from the argument to the method:
105
				if ((argument.binding.tagBits & (TagBits.AnnotationNonNull|TagBits.AnnotationNullable)) != 0) {
106
					if (this.binding.parameterNonNullness == null)
107
						this.binding.parameterNonNullness = new Boolean[this.arguments.length];
108
					this.binding.parameterNonNullness[i] = Boolean.valueOf((argument.binding.tagBits & TagBits.AnnotationNonNull) != 0);
109
				}
103
			}
110
			}
104
			if (paramAnnotations != null)
111
			if (paramAnnotations != null)
105
				this.binding.setParameterAnnotations(paramAnnotations);
112
				this.binding.setParameterAnnotations(paramAnnotations);
Lines 415-421 Link Here
415
		}
422
		}
416
423
417
		try {
424
		try {
418
			bindArguments();
419
			bindThrownExceptions();
425
			bindThrownExceptions();
420
			resolveJavadoc();
426
			resolveJavadoc();
421
			resolveAnnotations(this.scope, this.annotations, this.binding);
427
			resolveAnnotations(this.scope, this.annotations, this.binding);
(-)compiler/org/eclipse/jdt/internal/compiler/ast/Annotation.java (-1 / +8 lines)
Lines 1-5 Link Here
1
/*******************************************************************************
1
/*******************************************************************************
2
 * Copyright (c) 2000, 2010 IBM Corporation and others.
2
 * Copyright (c) 2000, 2011 IBM Corporation and others.
3
 * All rights reserved. This program and the accompanying materials
3
 * All rights reserved. This program and the accompanying materials
4
 * are made available under the terms of the Eclipse Public License v1.0
4
 * are made available under the terms of the Eclipse Public License v1.0
5
 * which accompanies this distribution, and is available at
5
 * which accompanies this distribution, and is available at
Lines 7-12 Link Here
7
 *
7
 *
8
 * Contributors:
8
 * Contributors:
9
 *     IBM Corporation - initial API and implementation
9
 *     IBM Corporation - initial API and implementation
10
 *     Stephan Herrmann - Contribution for Bug 186342 - [compiler][null]Using annotations for null checking
10
 *******************************************************************************/
11
 *******************************************************************************/
11
package org.eclipse.jdt.internal.compiler.ast;
12
package org.eclipse.jdt.internal.compiler.ast;
12
13
Lines 161-166 Link Here
161
			case TypeIds.T_JavaLangSuppressWarnings :
162
			case TypeIds.T_JavaLangSuppressWarnings :
162
				tagBits |= TagBits.AnnotationSuppressWarnings;
163
				tagBits |= TagBits.AnnotationSuppressWarnings;
163
				break;
164
				break;
165
			case TypeIds.T_ConfiguredAnnotationNullable :
166
				tagBits |= TagBits.AnnotationNullable;
167
				break;
168
			case TypeIds.T_ConfiguredAnnotationNonNull :
169
				tagBits |= TagBits.AnnotationNonNull;
170
				break;
164
		}
171
		}
165
		return tagBits;
172
		return tagBits;
166
	}
173
	}
(-)compiler/org/eclipse/jdt/internal/compiler/ast/MessageSend.java (-2 / +21 lines)
Lines 1-5 Link Here
1
/*******************************************************************************
1
/*******************************************************************************
2
 * Copyright (c) 2000, 2010 IBM Corporation and others.
2
 * Copyright (c) 2000, 2011 IBM Corporation and others.
3
 * All rights reserved. This program and the accompanying materials
3
 * All rights reserved. This program and the accompanying materials
4
 * are made available under the terms of the Eclipse Public License v1.0
4
 * are made available under the terms of the Eclipse Public License v1.0
5
 * which accompanies this distribution, and is available at
5
 * which accompanies this distribution, and is available at
Lines 8-14 Link Here
8
 * Contributors:
8
 * Contributors:
9
 *     IBM Corporation - initial API and implementation
9
 *     IBM Corporation - initial API and implementation
10
 *     Nick Teryaev - fix for bug (https://bugs.eclipse.org/bugs/show_bug.cgi?id=40752)
10
 *     Nick Teryaev - fix for bug (https://bugs.eclipse.org/bugs/show_bug.cgi?id=40752)
11
 *     Stephan Herrmann - Contribution for bug 319201 - [null] no warning when unboxing SingleNameReference causes NPE
11
 *     Stephan Herrmann - Contributions for
12
 *     						bug 319201 - [null] no warning when unboxing SingleNameReference causes NPE
13
 *     						bug 186342 - [compiler][null]Using annotations for null checking
12
 *******************************************************************************/
14
 *******************************************************************************/
13
package org.eclipse.jdt.internal.compiler.ast;
15
package org.eclipse.jdt.internal.compiler.ast;
14
16
Lines 80-85 Link Here
80
				this.arguments[i].checkNPE(currentScope, flowContext, flowInfo);
82
				this.arguments[i].checkNPE(currentScope, flowContext, flowInfo);
81
			}
83
			}
82
			flowInfo = this.arguments[i].analyseCode(currentScope, flowContext, flowInfo).unconditionalInits();
84
			flowInfo = this.arguments[i].analyseCode(currentScope, flowContext, flowInfo).unconditionalInits();
85
			// compare actual null-status against parameter annotations of the called method:
86
			int nullStatus = this.arguments[i].nullStatus(flowInfo);
87
			if (nullStatus != FlowInfo.NON_NULL 
88
					&& this.binding.parameterNonNullness != null
89
					&& this.binding.parameterNonNullness[i].booleanValue()) // if @NonNull is required
90
			{
91
				char[][] annotationName = currentScope.environment().globalOptions.nonNullAnnotationName;
92
				currentScope.problemReporter().possiblyNullToNonNullParameter(this.arguments[i], nullStatus, annotationName[annotationName.length-1]);
93
			}
83
		}
94
		}
84
	}
95
	}
85
	ReferenceBinding[] thrownExceptions;
96
	ReferenceBinding[] thrownExceptions;
Lines 250-255 Link Here
250
	}
261
	}
251
}
262
}
252
public int nullStatus(FlowInfo flowInfo) {
263
public int nullStatus(FlowInfo flowInfo) {
264
	if (this.binding.isValidBinding()) {
265
		// try to retrieve null status of this message send from an annotation of the called method:
266
		long tagBits = this.binding.tagBits;
267
		if ((tagBits & TagBits.AnnotationNonNull) != 0)
268
			return FlowInfo.NON_NULL;
269
		if ((tagBits & TagBits.AnnotationNullable) != 0)
270
			return FlowInfo.POTENTIALLY_NULL;
271
	}
253
	return FlowInfo.UNKNOWN;
272
	return FlowInfo.UNKNOWN;
254
}
273
}
255
274
(-)compiler/org/eclipse/jdt/internal/compiler/ast/MethodDeclaration.java (-1 / +8 lines)
Lines 1-5 Link Here
1
/*******************************************************************************
1
/*******************************************************************************
2
 * Copyright (c) 2000, 2010 IBM Corporation and others.
2
 * Copyright (c) 2000, 2011 IBM Corporation and others.
3
 * All rights reserved. This program and the accompanying materials
3
 * All rights reserved. This program and the accompanying materials
4
 * are made available under the terms of the Eclipse Public License v1.0
4
 * are made available under the terms of the Eclipse Public License v1.0
5
 * which accompanies this distribution, and is available at
5
 * which accompanies this distribution, and is available at
Lines 7-12 Link Here
7
 *
7
 *
8
 * Contributors:
8
 * Contributors:
9
 *     IBM Corporation - initial API and implementation
9
 *     IBM Corporation - initial API and implementation
10
 *     Stephan Herrmann - Contribution for Bug 186342 - [compiler][null]Using annotations for null checking
10
 *******************************************************************************/
11
 *******************************************************************************/
11
package org.eclipse.jdt.internal.compiler.ast;
12
package org.eclipse.jdt.internal.compiler.ast;
12
13
Lines 89-94 Link Here
89
						if (this.binding != null && this.binding.declaringClass == declaringElement)
90
						if (this.binding != null && this.binding.declaringClass == declaringElement)
90
							this.bits &= ~ASTNode.CanBeStatic;
91
							this.bits &= ~ASTNode.CanBeStatic;
91
					}
92
					}
93
					// leverage null-info from parameter annotations:
94
					long argumentTagBits = this.arguments[i].binding.tagBits;
95
					if ((argumentTagBits & TagBits.AnnotationNullable) != 0)
96
						flowInfo.markPotentiallyNullBit(this.arguments[i].binding);
97
					else if ((argumentTagBits & TagBits.AnnotationNonNull) != 0)
98
						flowInfo.markAsDefinitelyNonNull(this.arguments[i].binding);
92
				}
99
				}
93
			}
100
			}
94
			if (this.binding.declaringClass instanceof MemberTypeBinding && !this.binding.declaringClass.isStatic()) {
101
			if (this.binding.declaringClass instanceof MemberTypeBinding && !this.binding.declaringClass.isStatic()) {
(-)compiler/org/eclipse/jdt/internal/compiler/ast/ReturnStatement.java (-2 / +16 lines)
Lines 1-5 Link Here
1
/*******************************************************************************
1
/*******************************************************************************
2
 * Copyright (c) 2000, 2010 IBM Corporation and others.
2
 * Copyright (c) 2000, 2011 IBM Corporation and others.
3
 * All rights reserved. This program and the accompanying materials
3
 * All rights reserved. This program and the accompanying materials
4
 * are made available under the terms of the Eclipse Public License v1.0
4
 * are made available under the terms of the Eclipse Public License v1.0
5
 * which accompanies this distribution, and is available at
5
 * which accompanies this distribution, and is available at
Lines 7-13 Link Here
7
 *
7
 *
8
 * Contributors:
8
 * Contributors:
9
 *     IBM Corporation - initial API and implementation
9
 *     IBM Corporation - initial API and implementation
10
 *     Stephan Herrmann - Contribution for bug 319201 - [null] no warning when unboxing SingleNameReference causes NPE
10
 *     Stephan Herrmann - Contributions for 
11
 *     						bug 319201 - [null] no warning when unboxing SingleNameReference causes NPE
12
 *     						bug 186342 - [compiler][null]Using annotations for null checking
11
 *******************************************************************************/
13
 *******************************************************************************/
12
package org.eclipse.jdt.internal.compiler.ast;
14
package org.eclipse.jdt.internal.compiler.ast;
13
15
Lines 40-45 Link Here
40
		if ((this.expression.implicitConversion & TypeIds.UNBOXING) != 0) {
42
		if ((this.expression.implicitConversion & TypeIds.UNBOXING) != 0) {
41
			this.expression.checkNPE(currentScope, flowContext, flowInfo);
43
			this.expression.checkNPE(currentScope, flowContext, flowInfo);
42
		}
44
		}
45
		if (this.expression.nullStatus(flowInfo) != FlowInfo.NON_NULL) {
46
			// if we can't prove non-null check against declared null-ness of the enclosing method:
47
			AbstractMethodDeclaration referenceMethod = currentScope.methodScope().referenceMethod();
48
			if (referenceMethod != null) {
49
				MethodBinding method = referenceMethod.binding;
50
				if ((method.tagBits & TagBits.AnnotationNonNull) != 0) {
51
					char[][] annotationName = currentScope.environment().globalOptions.nonNullAnnotationName;
52
					currentScope.problemReporter().possiblyNullFromNonNullMethod(this, this.expression.nullStatus(flowInfo), 
53
																				 annotationName[annotationName.length-1]);
54
				}
55
			}
56
		}
43
	}
57
	}
44
	this.initStateIndex =
58
	this.initStateIndex =
45
		currentScope.methodScope().recordInitializationStates(flowInfo);
59
		currentScope.methodScope().recordInitializationStates(flowInfo);
(-)compiler/org/eclipse/jdt/internal/compiler/impl/CompilerOptions.java (-2 / +84 lines)
Lines 8-15 Link Here
8
 * Contributors:
8
 * Contributors:
9
 *     IBM Corporation - initial API and implementation
9
 *     IBM Corporation - initial API and implementation
10
 *     Benjamin Muskalla - Contribution for bug 239066
10
 *     Benjamin Muskalla - Contribution for bug 239066
11
 *     Stephan Herrmann  - Contribution for bug 236385
11
 *     Stephan Herrmann  - Contributions for 
12
 *     Stephan Herrmann  - Contribution for bug 295551
12
 *     							bug 236385 - [compiler] Warn for potential programming problem if an object is created but not used 
13
 *     							bug 295551 - Add option to automatically promote all warnings to errors
14
 *     							bug 186342 - [compiler][null]Using annotations for null checking
13
 *******************************************************************************/
15
 *******************************************************************************/
14
package org.eclipse.jdt.internal.compiler.impl;
16
package org.eclipse.jdt.internal.compiler.impl;
15
17
Lines 106-111 Link Here
106
	public static final String OPTION_ReportNullReference = "org.eclipse.jdt.core.compiler.problem.nullReference"; //$NON-NLS-1$
108
	public static final String OPTION_ReportNullReference = "org.eclipse.jdt.core.compiler.problem.nullReference"; //$NON-NLS-1$
107
	public static final String OPTION_ReportPotentialNullReference = "org.eclipse.jdt.core.compiler.problem.potentialNullReference"; //$NON-NLS-1$
109
	public static final String OPTION_ReportPotentialNullReference = "org.eclipse.jdt.core.compiler.problem.potentialNullReference"; //$NON-NLS-1$
108
	public static final String OPTION_ReportRedundantNullCheck = "org.eclipse.jdt.core.compiler.problem.redundantNullCheck"; //$NON-NLS-1$
110
	public static final String OPTION_ReportRedundantNullCheck = "org.eclipse.jdt.core.compiler.problem.redundantNullCheck"; //$NON-NLS-1$
111
	public static final String OPTION_ReportNullContractViolation = "org.eclipse.jdt.core.compiler.problem.nullContractViolation";  //$NON-NLS-1$
112
	public static final String OPTION_ReportPotentialNullContractViolation = "org.eclipse.jdt.core.compiler.problem.potentialNullContractViolation";  //$NON-NLS-1$
113
	public static final String OPTION_ReportNullContractInsufficientInfo = "org.eclipse.jdt.core.compiler.problem.nullContractInsufficientInfo";  //$NON-NLS-1$
109
	public static final String OPTION_ReportAutoboxing = "org.eclipse.jdt.core.compiler.problem.autoboxing"; //$NON-NLS-1$
114
	public static final String OPTION_ReportAutoboxing = "org.eclipse.jdt.core.compiler.problem.autoboxing"; //$NON-NLS-1$
110
	public static final String OPTION_ReportAnnotationSuperInterface = "org.eclipse.jdt.core.compiler.problem.annotationSuperInterface"; //$NON-NLS-1$
115
	public static final String OPTION_ReportAnnotationSuperInterface = "org.eclipse.jdt.core.compiler.problem.annotationSuperInterface"; //$NON-NLS-1$
111
	public static final String OPTION_ReportMissingOverrideAnnotation = "org.eclipse.jdt.core.compiler.problem.missingOverrideAnnotation"; //$NON-NLS-1$
116
	public static final String OPTION_ReportMissingOverrideAnnotation = "org.eclipse.jdt.core.compiler.problem.missingOverrideAnnotation"; //$NON-NLS-1$
Lines 141-146 Link Here
141
	public static final String OPTION_ReportMissingAnnotation = "org.eclipse.jdt.core.compiler.problem.missingAnnotation"; //$NON-NLS-1$
146
	public static final String OPTION_ReportMissingAnnotation = "org.eclipse.jdt.core.compiler.problem.missingAnnotation"; //$NON-NLS-1$
142
	public static final String OPTION_ReportMissingJavadoc = "org.eclipse.jdt.core.compiler.problem.missingJavadoc"; //$NON-NLS-1$
147
	public static final String OPTION_ReportMissingJavadoc = "org.eclipse.jdt.core.compiler.problem.missingJavadoc"; //$NON-NLS-1$
143
148
149
	public static final String OPTION_NullableAnnotationName = "org.eclipse.jdt.core.compiler.annotation.nullable"; //$NON-NLS-1$
150
	public static final String OPTION_NonNullAnnotationName = "org.eclipse.jdt.core.compiler.annotation.nonnull"; //$NON-NLS-1$
151
	public static final String OPTION_EmulateNullAnnotationTypes = "org.eclipse.jdt.core.compiler.annotation.emulate"; //$NON-NLS-1$
152
	public static final String OPTION_DefaultImportNullAnnotationTypes = "org.eclipse.jdt.core.compiler.annotation.defaultImport"; //$NON-NLS-1$
153
144
	/**
154
	/**
145
	 * Possible values for configurable options
155
	 * Possible values for configurable options
146
	 */
156
	 */
Lines 170-175 Link Here
170
	public static final String NO_TAG = "no_tag";	//$NON-NLS-1$
180
	public static final String NO_TAG = "no_tag";	//$NON-NLS-1$
171
	public static final String ALL_STANDARD_TAGS = "all_standard_tags";	//$NON-NLS-1$
181
	public static final String ALL_STANDARD_TAGS = "all_standard_tags";	//$NON-NLS-1$
172
182
183
	private static final char[][] DEFAULT_NONNULL_ANNOTATION_NAME = CharOperation.splitOn('.', "org.eclipse.jdt.annotation.NonNull".toCharArray()); //$NON-NLS-1$
184
	private static final char[][] DEFAULT_NULLABLE_ANNOTATION_NAME = CharOperation.splitOn('.', "org.eclipse.jdt.annotation.Nullable".toCharArray()); //$NON-NLS-1$
185
173
	/**
186
	/**
174
	 * Bit mask for configurable problems (error/warning threshold)
187
	 * Bit mask for configurable problems (error/warning threshold)
175
	 * Note: bitmask assumes 3 highest bits to denote irritant group (to allow storing 8 groups of 29 bits each
188
	 * Note: bitmask assumes 3 highest bits to denote irritant group (to allow storing 8 groups of 29 bits each
Lines 243-248 Link Here
243
	public static final int UnusedObjectAllocation = IrritantSet.GROUP2 | ASTNode.Bit4;
256
	public static final int UnusedObjectAllocation = IrritantSet.GROUP2 | ASTNode.Bit4;
244
	public static final int MethodCanBeStatic = IrritantSet.GROUP2 | ASTNode.Bit5;
257
	public static final int MethodCanBeStatic = IrritantSet.GROUP2 | ASTNode.Bit5;
245
	public static final int MethodCanBePotentiallyStatic = IrritantSet.GROUP2 | ASTNode.Bit6;
258
	public static final int MethodCanBePotentiallyStatic = IrritantSet.GROUP2 | ASTNode.Bit6;
259
	public static final int NullContractViolation = IrritantSet.GROUP2 | ASTNode.Bit7;
260
	public static final int PotentialNullContractViolation = IrritantSet.GROUP2 | ASTNode.Bit8;
261
	public static final int NullContractInsufficientInfo = IrritantSet.GROUP2 | ASTNode.Bit9;
246
262
247
	// Severity level for handlers
263
	// Severity level for handlers
248
	/** 
264
	/** 
Lines 364-369 Link Here
364
	public boolean includeNullInfoFromAsserts;
380
	public boolean includeNullInfoFromAsserts;
365
	/** Controls whether forced generic type problems get reported  */
381
	/** Controls whether forced generic type problems get reported  */
366
	public boolean reportUnavoidableGenericTypeProblems;
382
	public boolean reportUnavoidableGenericTypeProblems;
383
	/** Fully qualified name of annotation to use as marker for nullable types. */
384
	public char[][] nullableAnnotationName;
385
	/** Fully qualified name of annotation to use as marker for nonnull types. */
386
	public char[][] nonNullAnnotationName;
387
	/** Should null annotation types be emulated by synthetic bindings? */
388
	public boolean emulateNullAnnotationTypes;
389
	/** Should null annotation types be imported by default? */
390
	public boolean defaultImportNullAnnotationTypes;
367
391
368
	// keep in sync with warningTokenToIrritant and warningTokenFromIrritant
392
	// keep in sync with warningTokenToIrritant and warningTokenFromIrritant
369
	public final static String[] warningTokens = {
393
	public final static String[] warningTokens = {
Lines 503-508 Link Here
503
				return OPTION_ReportPotentialNullReference;
527
				return OPTION_ReportPotentialNullReference;
504
			case RedundantNullCheck :
528
			case RedundantNullCheck :
505
				return OPTION_ReportRedundantNullCheck;
529
				return OPTION_ReportRedundantNullCheck;
530
			case NullContractViolation :
531
				return OPTION_ReportNullContractViolation;
532
			case PotentialNullContractViolation :
533
				return OPTION_ReportPotentialNullContractViolation;
534
			case NullContractInsufficientInfo :
535
				return OPTION_ReportNullContractInsufficientInfo;
506
			case AutoBoxing :
536
			case AutoBoxing :
507
				return OPTION_ReportAutoboxing;
537
				return OPTION_ReportAutoboxing;
508
			case AnnotationSuperInterface :
538
			case AnnotationSuperInterface :
Lines 748-753 Link Here
748
			case NullReference :
778
			case NullReference :
749
			case PotentialNullReference :
779
			case PotentialNullReference :
750
			case RedundantNullCheck :
780
			case RedundantNullCheck :
781
			case NullContractViolation :
782
			case PotentialNullContractViolation :
783
			case NullContractInsufficientInfo :
751
				return "null"; //$NON-NLS-1$
784
				return "null"; //$NON-NLS-1$
752
			case FallthroughCase :
785
			case FallthroughCase :
753
				return "fallthrough"; //$NON-NLS-1$
786
				return "fallthrough"; //$NON-NLS-1$
Lines 923-928 Link Here
923
		optionsMap.put(OPTION_ReportNullReference, getSeverityString(NullReference));
956
		optionsMap.put(OPTION_ReportNullReference, getSeverityString(NullReference));
924
		optionsMap.put(OPTION_ReportPotentialNullReference, getSeverityString(PotentialNullReference));
957
		optionsMap.put(OPTION_ReportPotentialNullReference, getSeverityString(PotentialNullReference));
925
		optionsMap.put(OPTION_ReportRedundantNullCheck, getSeverityString(RedundantNullCheck));
958
		optionsMap.put(OPTION_ReportRedundantNullCheck, getSeverityString(RedundantNullCheck));
959
		optionsMap.put(OPTION_ReportNullContractViolation, getSeverityString(NullContractViolation));
960
		optionsMap.put(OPTION_ReportPotentialNullContractViolation, getSeverityString(PotentialNullContractViolation));
961
		optionsMap.put(OPTION_ReportNullContractInsufficientInfo, getSeverityString(NullContractInsufficientInfo));
926
		optionsMap.put(OPTION_SuppressWarnings, this.suppressWarnings ? ENABLED : DISABLED);
962
		optionsMap.put(OPTION_SuppressWarnings, this.suppressWarnings ? ENABLED : DISABLED);
927
		optionsMap.put(OPTION_SuppressOptionalErrors, this.suppressOptionalErrors ? ENABLED : DISABLED);
963
		optionsMap.put(OPTION_SuppressOptionalErrors, this.suppressOptionalErrors ? ENABLED : DISABLED);
928
		optionsMap.put(OPTION_ReportUnhandledWarningToken, getSeverityString(UnhandledWarningToken));
964
		optionsMap.put(OPTION_ReportUnhandledWarningToken, getSeverityString(UnhandledWarningToken));
Lines 943-948 Link Here
943
		optionsMap.put(OPTION_IncludeNullInfoFromAsserts, this.includeNullInfoFromAsserts ? ENABLED : DISABLED);
979
		optionsMap.put(OPTION_IncludeNullInfoFromAsserts, this.includeNullInfoFromAsserts ? ENABLED : DISABLED);
944
		optionsMap.put(OPTION_ReportMethodCanBeStatic, getSeverityString(MethodCanBeStatic));
980
		optionsMap.put(OPTION_ReportMethodCanBeStatic, getSeverityString(MethodCanBeStatic));
945
		optionsMap.put(OPTION_ReportMethodCanBePotentiallyStatic, getSeverityString(MethodCanBePotentiallyStatic));
981
		optionsMap.put(OPTION_ReportMethodCanBePotentiallyStatic, getSeverityString(MethodCanBePotentiallyStatic));
982
		if (this.nullableAnnotationName != null) {
983
			char[] compoundName = CharOperation.concatWith(this.nullableAnnotationName, '.');
984
			optionsMap.put(OPTION_NullableAnnotationName, String.valueOf(compoundName));
985
		}
986
		if (this.nonNullAnnotationName != null) {
987
			char[] compoundName = CharOperation.concatWith(this.nonNullAnnotationName, '.');
988
			optionsMap.put(OPTION_NonNullAnnotationName, String.valueOf(compoundName));
989
		}
990
		optionsMap.put(OPTION_EmulateNullAnnotationTypes, this.emulateNullAnnotationTypes ? ENABLED : DISABLED);
991
		optionsMap.put(OPTION_DefaultImportNullAnnotationTypes, this.defaultImportNullAnnotationTypes ? ENABLED : DISABLED);
946
		return optionsMap;
992
		return optionsMap;
947
	}
993
	}
948
994
Lines 1351-1356 Link Here
1351
		if ((optionValue = optionsMap.get(OPTION_ReportNullReference)) != null) updateSeverity(NullReference, optionValue);
1397
		if ((optionValue = optionsMap.get(OPTION_ReportNullReference)) != null) updateSeverity(NullReference, optionValue);
1352
		if ((optionValue = optionsMap.get(OPTION_ReportPotentialNullReference)) != null) updateSeverity(PotentialNullReference, optionValue);
1398
		if ((optionValue = optionsMap.get(OPTION_ReportPotentialNullReference)) != null) updateSeverity(PotentialNullReference, optionValue);
1353
		if ((optionValue = optionsMap.get(OPTION_ReportRedundantNullCheck)) != null) updateSeverity(RedundantNullCheck, optionValue);
1399
		if ((optionValue = optionsMap.get(OPTION_ReportRedundantNullCheck)) != null) updateSeverity(RedundantNullCheck, optionValue);
1400
		if ((optionValue = optionsMap.get(OPTION_ReportNullContractViolation)) != null) updateSeverity(NullContractViolation, optionValue);
1401
		if ((optionValue = optionsMap.get(OPTION_ReportPotentialNullContractViolation)) != null) updateSeverity(PotentialNullContractViolation, optionValue);
1402
		if ((optionValue = optionsMap.get(OPTION_ReportNullContractInsufficientInfo)) != null) updateSeverity(NullContractInsufficientInfo, optionValue);
1354
		if ((optionValue = optionsMap.get(OPTION_ReportAutoboxing)) != null) updateSeverity(AutoBoxing, optionValue);
1403
		if ((optionValue = optionsMap.get(OPTION_ReportAutoboxing)) != null) updateSeverity(AutoBoxing, optionValue);
1355
		if ((optionValue = optionsMap.get(OPTION_ReportAnnotationSuperInterface)) != null) updateSeverity(AnnotationSuperInterface, optionValue);
1404
		if ((optionValue = optionsMap.get(OPTION_ReportAnnotationSuperInterface)) != null) updateSeverity(AnnotationSuperInterface, optionValue);
1356
		if ((optionValue = optionsMap.get(OPTION_ReportMissingOverrideAnnotation)) != null) updateSeverity(MissingOverrideAnnotation, optionValue);
1405
		if ((optionValue = optionsMap.get(OPTION_ReportMissingOverrideAnnotation)) != null) updateSeverity(MissingOverrideAnnotation, optionValue);
Lines 1485-1490 Link Here
1485
				this.storeAnnotations = false;
1534
				this.storeAnnotations = false;
1486
			}
1535
			}
1487
		}
1536
		}
1537
		if ((optionValue = optionsMap.get(OPTION_NullableAnnotationName)) != null) {
1538
			this.nullableAnnotationName = CharOperation.splitAndTrimOn('.', ((String)optionValue).toCharArray());
1539
		}
1540
		if ((optionValue = optionsMap.get(OPTION_NonNullAnnotationName)) != null) {
1541
			this.nonNullAnnotationName = CharOperation.splitAndTrimOn('.', ((String)optionValue).toCharArray());
1542
		}
1543
		if ((optionValue = optionsMap.get(OPTION_EmulateNullAnnotationTypes)) != null) {
1544
			if (ENABLED.equals(optionValue)) {
1545
				this.emulateNullAnnotationTypes = true;
1546
				// ensure that we actually have annotation names to emulate:
1547
				if (this.nullableAnnotationName == null)
1548
					this.nullableAnnotationName = DEFAULT_NULLABLE_ANNOTATION_NAME;
1549
				if (this.nonNullAnnotationName == null)
1550
					this.nonNullAnnotationName = DEFAULT_NONNULL_ANNOTATION_NAME;
1551
			} else if (DISABLED.equals(optionValue)) {
1552
				this.emulateNullAnnotationTypes = false;
1553
			}
1554
		}
1555
		if ((optionValue = optionsMap.get(OPTION_DefaultImportNullAnnotationTypes)) != null) {
1556
			if (ENABLED.equals(optionValue)) {
1557
				this.defaultImportNullAnnotationTypes = true;
1558
				// ensure that we actually have annotation names to be used for default imports:
1559
				if (this.nullableAnnotationName == null)
1560
					this.nullableAnnotationName = DEFAULT_NULLABLE_ANNOTATION_NAME;
1561
				if (this.nonNullAnnotationName == null)
1562
					this.nonNullAnnotationName = DEFAULT_NONNULL_ANNOTATION_NAME;
1563
			} else if (DISABLED.equals(optionValue)) {
1564
				this.defaultImportNullAnnotationTypes = false;
1565
			}
1566
		}
1488
	}
1567
	}
1489
	public String toString() {
1568
	public String toString() {
1490
		StringBuffer buf = new StringBuffer("CompilerOptions:"); //$NON-NLS-1$
1569
		StringBuffer buf = new StringBuffer("CompilerOptions:"); //$NON-NLS-1$
Lines 1560-1565 Link Here
1560
		buf.append("\n\t- null reference: ").append(getSeverityString(NullReference)); //$NON-NLS-1$
1639
		buf.append("\n\t- null reference: ").append(getSeverityString(NullReference)); //$NON-NLS-1$
1561
		buf.append("\n\t- potential null reference: ").append(getSeverityString(PotentialNullReference)); //$NON-NLS-1$
1640
		buf.append("\n\t- potential null reference: ").append(getSeverityString(PotentialNullReference)); //$NON-NLS-1$
1562
		buf.append("\n\t- redundant null check: ").append(getSeverityString(RedundantNullCheck)); //$NON-NLS-1$
1641
		buf.append("\n\t- redundant null check: ").append(getSeverityString(RedundantNullCheck)); //$NON-NLS-1$
1642
		buf.append("\n\t- null contract violation: ").append(getSeverityString(NullContractViolation)); //$NON-NLS-1$
1643
		buf.append("\n\t- potential null contract vialotation: ").append(getSeverityString(PotentialNullContractViolation)); //$NON-NLS-1$
1644
		buf.append("\n\t- insufficient information for checking null contract: ").append(getSeverityString(NullContractInsufficientInfo)); //$NON-NLS-1$
1563
		buf.append("\n\t- autoboxing: ").append(getSeverityString(AutoBoxing)); //$NON-NLS-1$
1645
		buf.append("\n\t- autoboxing: ").append(getSeverityString(AutoBoxing)); //$NON-NLS-1$
1564
		buf.append("\n\t- annotation super interface: ").append(getSeverityString(AnnotationSuperInterface)); //$NON-NLS-1$
1646
		buf.append("\n\t- annotation super interface: ").append(getSeverityString(AnnotationSuperInterface)); //$NON-NLS-1$
1565
		buf.append("\n\t- missing @Override annotation: ").append(getSeverityString(MissingOverrideAnnotation)); //$NON-NLS-1$
1647
		buf.append("\n\t- missing @Override annotation: ").append(getSeverityString(MissingOverrideAnnotation)); //$NON-NLS-1$
(-)compiler/org/eclipse/jdt/internal/compiler/impl/IrritantSet.java (-4 / +12 lines)
Lines 1-5 Link Here
1
/*******************************************************************************
1
/*******************************************************************************
2
 * Copyright (c) 2000, 2010 IBM Corporation and others.
2
 * Copyright (c) 2000, 2011 IBM Corporation and others.
3
 * All rights reserved. This program and the accompanying materials
3
 * All rights reserved. This program and the accompanying materials
4
 * are made available under the terms of the Eclipse Public License v1.0
4
 * are made available under the terms of the Eclipse Public License v1.0
5
 * which accompanies this distribution, and is available at
5
 * which accompanies this distribution, and is available at
Lines 7-12 Link Here
7
 *
7
 *
8
 * Contributors:
8
 * Contributors:
9
 *     IBM Corporation - initial API and implementation
9
 *     IBM Corporation - initial API and implementation
10
 *     Stephan Herrmann - Contribution for Bug 186342 - [compiler][null]Using annotations for null checking
10
 *******************************************************************************/
11
 *******************************************************************************/
11
12
12
package org.eclipse.jdt.internal.compiler.impl;
13
package org.eclipse.jdt.internal.compiler.impl;
Lines 58-66 Link Here
58
	public static final IrritantSet UNCHECKED = new IrritantSet(CompilerOptions.UncheckedTypeOperation);
59
	public static final IrritantSet UNCHECKED = new IrritantSet(CompilerOptions.UncheckedTypeOperation);
59
	public static final IrritantSet UNQUALIFIED_FIELD_ACCESS = new IrritantSet(CompilerOptions.UnqualifiedFieldAccess);
60
	public static final IrritantSet UNQUALIFIED_FIELD_ACCESS = new IrritantSet(CompilerOptions.UnqualifiedFieldAccess);
60
61
61
	public static final IrritantSet COMPILER_DEFAULT_ERRORS = new IrritantSet(0); // no optional error by default	
62
	public static final IrritantSet COMPILER_DEFAULT_ERRORS = new IrritantSet(0); // see static initializer below	
62
	public static final IrritantSet COMPILER_DEFAULT_WARNINGS = new IrritantSet(0); // see static initializer below
63
	public static final IrritantSet COMPILER_DEFAULT_WARNINGS = new IrritantSet(0); // see static initializer below
63
	static {
64
	static {
65
		COMPILER_DEFAULT_ERRORS
66
			.set(CompilerOptions.NullContractViolation
67
				 | CompilerOptions.PotentialNullContractViolation);
64
		COMPILER_DEFAULT_WARNINGS
68
		COMPILER_DEFAULT_WARNINGS
65
			// group-0 warnings enabled by default
69
			// group-0 warnings enabled by default
66
			.set(
70
			.set(
Lines 98-104 Link Here
98
			// group-2 warnings enabled by default
102
			// group-2 warnings enabled by default
99
			.set(
103
			.set(
100
				CompilerOptions.DeadCode
104
				CompilerOptions.DeadCode
101
				|CompilerOptions.Tasks);
105
				| CompilerOptions.Tasks
106
				| CompilerOptions.NullContractInsufficientInfo);
102
			
107
			
103
		ALL.setAll();
108
		ALL.setAll();
104
		HIDING
109
		HIDING
Lines 107-113 Link Here
107
			.set(CompilerOptions.TypeHiding);
112
			.set(CompilerOptions.TypeHiding);
108
		NULL
113
		NULL
109
			.set(CompilerOptions.PotentialNullReference)
114
			.set(CompilerOptions.PotentialNullReference)
110
			.set(CompilerOptions.RedundantNullCheck);
115
			.set(CompilerOptions.RedundantNullCheck)
116
			.set(CompilerOptions.NullContractViolation)
117
			.set(CompilerOptions.PotentialNullContractViolation)
118
			.set(CompilerOptions.NullContractInsufficientInfo);
111
		RESTRICTION.set(CompilerOptions.DiscouragedReference);
119
		RESTRICTION.set(CompilerOptions.DiscouragedReference);
112
		STATIC_ACCESS.set(CompilerOptions.NonStaticAccessToStatic);
120
		STATIC_ACCESS.set(CompilerOptions.NonStaticAccessToStatic);
113
		UNUSED
121
		UNUSED
(-)compiler/org/eclipse/jdt/internal/compiler/lookup/BinaryTypeBinding.java (+50 lines)
Lines 7-12 Link Here
7
 *
7
 *
8
 * Contributors:
8
 * Contributors:
9
 *     IBM Corporation - initial API and implementation
9
 *     IBM Corporation - initial API and implementation
10
 *     Stephan Herrmann - Contribution for Bug 186342 - [compiler][null]Using annotations for null checking
10
 *******************************************************************************/
11
 *******************************************************************************/
11
package org.eclipse.jdt.internal.compiler.lookup;
12
package org.eclipse.jdt.internal.compiler.lookup;
12
13
Lines 553-558 Link Here
553
			isAnnotationType() ? convertMemberValue(method.getDefaultValue(), this.environment, missingTypeNames) : null,
554
			isAnnotationType() ? convertMemberValue(method.getDefaultValue(), this.environment, missingTypeNames) : null,
554
			this.environment);
555
			this.environment);
555
556
557
	scanForNullAnnotation(method, result);
558
556
	if (use15specifics)
559
	if (use15specifics)
557
		result.tagBits |= method.getTagBits();
560
		result.tagBits |= method.getTagBits();
558
	result.typeVariables = typeVars;
561
	result.typeVariables = typeVars;
Lines 1092-1097 Link Here
1092
AnnotationBinding[] retrieveAnnotations(Binding binding) {
1095
AnnotationBinding[] retrieveAnnotations(Binding binding) {
1093
	return AnnotationBinding.addStandardAnnotations(super.retrieveAnnotations(binding), binding.getAnnotationTagBits(), this.environment);
1096
	return AnnotationBinding.addStandardAnnotations(super.retrieveAnnotations(binding), binding.getAnnotationTagBits(), this.environment);
1094
}
1097
}
1098
private void scanForNullAnnotation(IBinaryMethod method, MethodBinding result) {
1099
	char[][] nullableAnnotationName = this.environment.globalOptions.nullableAnnotationName;
1100
	char[][] nonNullAnnotationName = this.environment.globalOptions.nonNullAnnotationName;
1101
	if (nullableAnnotationName == null || nonNullAnnotationName == null)
1102
		return; // not configured to use null annotations
1103
1104
	IBinaryAnnotation[] annotations = method.getAnnotations();
1105
	if (annotations != null) {
1106
		for (int i = 0; i < annotations.length; i++) {
1107
			char[] annotationTypeName = annotations[i].getTypeName();
1108
			if (annotationTypeName[0] != 'L')
1109
				continue;
1110
			char[][] typeName = CharOperation.splitOn('/', annotationTypeName, 1, annotationTypeName.length-1); // cut of leading 'L' and trailing ';'
1111
			if (CharOperation.equals(typeName, nonNullAnnotationName)) {
1112
				result.tagBits |= TagBits.AnnotationNonNull;
1113
				return;
1114
			}
1115
			if (CharOperation.equals(typeName, nullableAnnotationName)) {
1116
				result.tagBits |= TagBits.AnnotationNullable;
1117
				return;
1118
			}
1119
		}
1120
	}
1121
1122
	for (int j = 0; j < result.parameters.length; j++) {
1123
		IBinaryAnnotation[] paramAnnotations = method.getParameterAnnotations(j); 
1124
		if (paramAnnotations != null) {
1125
			for (int i = 0; i < paramAnnotations.length; i++) {
1126
				char[] annotationTypeName = paramAnnotations[i].getTypeName();
1127
				if (annotationTypeName[0] != 'L')
1128
					continue;
1129
				char[][] typeName = CharOperation.splitOn('/', annotationTypeName, 1, annotationTypeName.length-1); // cut of leading 'L' and trailing ';'
1130
				if (CharOperation.equals(typeName, nonNullAnnotationName)) {
1131
					if (result.parameterNonNullness == null)
1132
						result.parameterNonNullness = new Boolean[result.parameters.length];
1133
					result.parameterNonNullness[j] = Boolean.TRUE;
1134
					break;
1135
				} else if (CharOperation.equals(typeName, nullableAnnotationName)) {
1136
					if (result.parameterNonNullness == null)
1137
						result.parameterNonNullness = new Boolean[result.parameters.length];
1138
					result.parameterNonNullness[j] = Boolean.FALSE;
1139
					break;
1140
				}
1141
			}
1142
		}
1143
	}
1144
}
1095
SimpleLookupTable storedAnnotations(boolean forceInitialize) {
1145
SimpleLookupTable storedAnnotations(boolean forceInitialize) {
1096
	if (forceInitialize && this.storedAnnotations == null) {
1146
	if (forceInitialize && this.storedAnnotations == null) {
1097
		if (!this.environment.globalOptions.storeAnnotations)
1147
		if (!this.environment.globalOptions.storeAnnotations)
(-)compiler/org/eclipse/jdt/internal/compiler/lookup/CompilationUnitScope.java (-8 / +43 lines)
Lines 1-5 Link Here
1
/*******************************************************************************
1
/*******************************************************************************
2
 * Copyright (c) 2000, 2010 IBM Corporation and others.
2
 * Copyright (c) 2000, 2011 IBM Corporation and others.
3
 * All rights reserved. This program and the accompanying materials
3
 * All rights reserved. This program and the accompanying materials
4
 * are made available under the terms of the Eclipse Public License v1.0
4
 * are made available under the terms of the Eclipse Public License v1.0
5
 * which accompanies this distribution, and is available at
5
 * which accompanies this distribution, and is available at
Lines 7-13 Link Here
7
 *
7
 *
8
 * Contributors:
8
 * Contributors:
9
 *     IBM Corporation - initial API and implementation
9
 *     IBM Corporation - initial API and implementation
10
 *     Erling Ellingsen -  patch for bug 125570
10
 *     Erling Ellingsen - patch for bug 125570
11
 *     Stephan Herrmann - Contribution for Bug 186342 - [compiler][null]Using annotations for null checking
11
 *******************************************************************************/
12
 *******************************************************************************/
12
package org.eclipse.jdt.internal.compiler.lookup;
13
package org.eclipse.jdt.internal.compiler.lookup;
13
14
Lines 160-166 Link Here
160
161
161
	// allocate the import array, add java.lang.* by default
162
	// allocate the import array, add java.lang.* by default
162
	int numberOfStatements = this.referenceContext.imports.length;
163
	int numberOfStatements = this.referenceContext.imports.length;
163
	int numberOfImports = numberOfStatements + 1;
164
	int numberOfDefaultImports = 1;
165
	if (this.environment.globalOptions.defaultImportNullAnnotationTypes)
166
		numberOfDefaultImports += 2;
167
	int numberOfImports = numberOfStatements + numberOfDefaultImports;
164
	for (int i = 0; i < numberOfStatements; i++) {
168
	for (int i = 0; i < numberOfStatements; i++) {
165
		ImportReference importReference = this.referenceContext.imports[i];
169
		ImportReference importReference = this.referenceContext.imports[i];
166
		if (((importReference.bits & ASTNode.OnDemand) != 0) && CharOperation.equals(TypeConstants.JAVA_LANG, importReference.tokens) && !importReference.isStatic()) {
170
		if (((importReference.bits & ASTNode.OnDemand) != 0) && CharOperation.equals(TypeConstants.JAVA_LANG, importReference.tokens) && !importReference.isStatic()) {
Lines 169-176 Link Here
169
		}
173
		}
170
	}
174
	}
171
	ImportBinding[] resolvedImports = new ImportBinding[numberOfImports];
175
	ImportBinding[] resolvedImports = new ImportBinding[numberOfImports];
172
	resolvedImports[0] = getDefaultImports()[0];
176
	ImportBinding[] defaultImports = getDefaultImports(); // consistent number of default imports is ensured in LookupEnvironment.makeNullAnnotationTypeImports()
173
	int index = 1;
177
	for (int i = 0; i < numberOfDefaultImports; i++) {
178
		resolvedImports[i] = defaultImports[i];
179
	}
180
	int index = numberOfDefaultImports;
174
181
175
	nextImport : for (int i = 0; i < numberOfStatements; i++) {
182
	nextImport : for (int i = 0; i < numberOfStatements; i++) {
176
		ImportReference importReference = this.referenceContext.imports[i];
183
		ImportReference importReference = this.referenceContext.imports[i];
Lines 303-308 Link Here
303
		return; // can be called when a field constant is resolved before static imports
310
		return; // can be called when a field constant is resolved before static imports
304
	if (this.referenceContext.imports == null) {
311
	if (this.referenceContext.imports == null) {
305
		this.typeOrPackageCache = new HashtableOfObject(1);
312
		this.typeOrPackageCache = new HashtableOfObject(1);
313
		for (int i = 0; i < this.imports.length; i++) {
314
			// cache default-imported null annotation types:
315
			if (!this.imports[i].onDemand) {
316
				char[][] importName = this.imports[i].compoundName;
317
				this.typeOrPackageCache.put(importName[importName.length-1], this.imports[i].resolvedImport);
318
			}
319
		}
306
		return;
320
		return;
307
	}
321
	}
308
322
Lines 327-335 Link Here
327
			break;
341
			break;
328
		}
342
		}
329
	}
343
	}
344
	int numberOfDefaultImports = 1;
345
	if (this.environment.globalOptions.defaultImportNullAnnotationTypes) {
346
		numberOfDefaultImports += 2;
347
		numberOfImports += 2;
348
	}
330
	ImportBinding[] resolvedImports = new ImportBinding[numberOfImports];
349
	ImportBinding[] resolvedImports = new ImportBinding[numberOfImports];
331
	resolvedImports[0] = getDefaultImports()[0];
350
	ImportBinding[] defaultImports = getDefaultImports(); // consistent number of default imports is ensured in LookupEnvironment.makeNullAnnotationTypeImports()
332
	int index = 1;
351
	for (int i = 0; i < numberOfDefaultImports; i++) {
352
		resolvedImports[i] = defaultImports[i];
353
	}
354
355
	int index = numberOfDefaultImports;
333
356
334
	// keep static imports with normal imports until there is a reason to split them up
357
	// keep static imports with normal imports until there is a reason to split them up
335
	// on demand imports continue to be packages & types. need to check on demand type imports for fields/methods
358
	// on demand imports continue to be packages & types. need to check on demand type imports for fields/methods
Lines 613-619 Link Here
613
		importBinding = missingObject.fPackage;
636
		importBinding = missingObject.fPackage;
614
	}
637
	}
615
638
616
	return this.environment.defaultImports = new ImportBinding[] {new ImportBinding(TypeConstants.JAVA_LANG, true, importBinding, null)};
639
	ImportBinding javaLangImport = new ImportBinding(TypeConstants.JAVA_LANG, true, importBinding, null);
640
	ImportBinding[] nullAnnotationImports = this.environment.makeNullAnnotationTypeImports(); // trigger regardless of option below
641
	if (this.environment.globalOptions.defaultImportNullAnnotationTypes) {
642
		ImportBinding[] allDefaultImports = new ImportBinding[nullAnnotationImports.length+1];// java.lang.* + null-annotations
643
		allDefaultImports[0] = javaLangImport;
644
		System.arraycopy(nullAnnotationImports, 0,
645
						 allDefaultImports, 1,
646
						 nullAnnotationImports.length);
647
		this.environment.defaultImports = allDefaultImports;
648
	} else {
649
		this.environment.defaultImports = new ImportBinding[] {javaLangImport};
650
	}
651
	return this.environment.defaultImports;
617
}
652
}
618
// NOT Public API
653
// NOT Public API
619
public final Binding getImport(char[][] compoundName, boolean onDemand, boolean isStaticImport) {
654
public final Binding getImport(char[][] compoundName, boolean onDemand, boolean isStaticImport) {
(-)compiler/org/eclipse/jdt/internal/compiler/lookup/LookupEnvironment.java (-1 / +68 lines)
Lines 1-5 Link Here
1
/*******************************************************************************
1
/*******************************************************************************
2
 * Copyright (c) 2000, 2010 IBM Corporation and others.
2
 * Copyright (c) 2000, 2011 IBM Corporation and others.
3
 * All rights reserved. This program and the accompanying materials
3
 * All rights reserved. This program and the accompanying materials
4
 * are made available under the terms of the Eclipse Public License v1.0
4
 * are made available under the terms of the Eclipse Public License v1.0
5
 * which accompanies this distribution, and is available at
5
 * which accompanies this distribution, and is available at
Lines 7-12 Link Here
7
 *
7
 *
8
 * Contributors:
8
 * Contributors:
9
 *     IBM Corporation - initial API and implementation
9
 *     IBM Corporation - initial API and implementation
10
 *     Stephan Herrmann - Contribution for Bug 186342 - [compiler][null]Using annotations for null checking
10
 *******************************************************************************/
11
 *******************************************************************************/
11
package org.eclipse.jdt.internal.compiler.lookup;
12
package org.eclipse.jdt.internal.compiler.lookup;
12
13
Lines 1314-1319 Link Here
1314
		return this.nameEnvironment.isPackage(null, name);
1315
		return this.nameEnvironment.isPackage(null, name);
1315
	return this.nameEnvironment.isPackage(compoundName, name);
1316
	return this.nameEnvironment.isPackage(compoundName, name);
1316
}
1317
}
1318
1319
private ReferenceBinding makeNullAnnotationType(char[][] compoundName, int typeId) {
1320
	char[][] packageName = CharOperation.subarray(compoundName, 0, compoundName.length-1);
1321
	PackageBinding packageBinding = createPackage(packageName);
1322
	ReferenceBinding typeBinding = packageBinding.getType(compoundName[compoundName.length-1]);
1323
	if (typeBinding != null && typeBinding.isValidBinding())
1324
		this.problemReporter.conflictingTypeEmulation(compoundName); // does not return
1325
1326
	BinaryTypeBinding emulatedType = new BinaryTypeBinding();
1327
	emulatedType.compoundName = compoundName;
1328
	emulatedType.modifiers = ClassFileConstants.AccAnnotation | ClassFileConstants.AccPublic;
1329
	emulatedType.fields = Binding.NO_FIELDS;
1330
	emulatedType.methods = Binding.NO_METHODS;
1331
	emulatedType.memberTypes = Binding.NO_MEMBER_TYPES;
1332
	emulatedType.superclass = getType(TypeConstants.JAVA_LANG_OBJECT);
1333
	emulatedType.superInterfaces = Binding.NO_SUPERINTERFACES;
1334
	emulatedType.fPackage = packageBinding;
1335
	emulatedType.typeVariables = Binding.NO_TYPE_VARIABLES;
1336
	emulatedType.tagBits = TagBits.AreFieldsComplete | TagBits.AreFieldsSorted 
1337
							| TagBits.AreMethodsComplete | TagBits.AreMethodsSorted 
1338
							| TagBits.HasNoMemberTypes | TagBits.TypeVariablesAreConnected
1339
							| TagBits.AnnotationClassRetention 
1340
							| TagBits.AnnotationForMethod | TagBits.AnnotationForParameter ;
1341
	emulatedType.id = typeId;
1342
	
1343
	packageBinding.addType(emulatedType);
1344
1345
	return emulatedType;
1346
}
1347
1348
protected ImportBinding[] makeNullAnnotationTypeImports() {
1349
	char[][] nullableAnnotationName = this.globalOptions.nullableAnnotationName;
1350
	char[][] nonNullAnnotationName = this.globalOptions.nonNullAnnotationName;
1351
	if (nullableAnnotationName == null || nonNullAnnotationName == null) {
1352
		if (this.globalOptions.emulateNullAnnotationTypes || this.globalOptions.defaultImportNullAnnotationTypes)
1353
			// shouldn't happen by construction of CompilerOptions.set(Map)
1354
			this.problemReporter.abortDueToInternalError("Inconsistent null annotation options"); //$NON-NLS-1$
1355
		return new ImportBinding[0];
1356
	}
1357
	// fetch annotation types for emulation and/or default import:
1358
	ReferenceBinding nullableAnnotationType = null;
1359
	ReferenceBinding nonNullAnnotationType = null;
1360
	if (this.globalOptions.emulateNullAnnotationTypes) {
1361
		nullableAnnotationType = makeNullAnnotationType(nullableAnnotationName, TypeIds.T_ConfiguredAnnotationNullable);
1362
		nonNullAnnotationType  = makeNullAnnotationType(nonNullAnnotationName, TypeIds.T_ConfiguredAnnotationNonNull);
1363
	} else { // not emulated means those types should exist (and need to be marked):
1364
		nullableAnnotationType = getType(nullableAnnotationName);
1365
		if (nullableAnnotationType != null && nullableAnnotationType.isValidBinding())
1366
			nullableAnnotationType.id = TypeIds.T_ConfiguredAnnotationNullable;
1367
		else if (this.globalOptions.defaultImportNullAnnotationTypes)
1368
			this.problemReporter.missingNullAnnotationType(nullableAnnotationName);
1369
1370
		nonNullAnnotationType  = getType(nonNullAnnotationName);
1371
		if (nonNullAnnotationType != null && nonNullAnnotationType.isValidBinding())
1372
			nonNullAnnotationType.id = TypeIds.T_ConfiguredAnnotationNonNull;
1373
		else if (this.globalOptions.defaultImportNullAnnotationTypes)
1374
			this.problemReporter.missingNullAnnotationType(nonNullAnnotationName);
1375
	}
1376
	if (this.globalOptions.defaultImportNullAnnotationTypes)
1377
		return new ImportBinding[] {
1378
				new ImportBinding(nullableAnnotationName, false, nullableAnnotationType, null),
1379
				new ImportBinding(nonNullAnnotationName, false, nonNullAnnotationType, null)
1380
		};
1381
	return new ImportBinding[0];
1382
}
1383
1317
// The method verifier is lazily initialized to guarantee the receiver, the compiler & the oracle are ready.
1384
// The method verifier is lazily initialized to guarantee the receiver, the compiler & the oracle are ready.
1318
public MethodVerifier methodVerifier() {
1385
public MethodVerifier methodVerifier() {
1319
	if (this.verifier == null)
1386
	if (this.verifier == null)
(-)compiler/org/eclipse/jdt/internal/compiler/lookup/MethodBinding.java (-1 / +3 lines)
Lines 1-5 Link Here
1
/*******************************************************************************
1
/*******************************************************************************
2
 * Copyright (c) 2000, 2010 IBM Corporation and others.
2
 * Copyright (c) 2000, 2011 IBM Corporation and others.
3
 * All rights reserved. This program and the accompanying materials
3
 * All rights reserved. This program and the accompanying materials
4
 * are made available under the terms of the Eclipse Public License v1.0
4
 * are made available under the terms of the Eclipse Public License v1.0
5
 * which accompanies this distribution, and is available at
5
 * which accompanies this distribution, and is available at
Lines 7-12 Link Here
7
 *
7
 *
8
 * Contributors:
8
 * Contributors:
9
 *     IBM Corporation - initial API and implementation
9
 *     IBM Corporation - initial API and implementation
10
 *     Stephan Herrmann - Contribution for Bug 186342 - [compiler][null]Using annotations for null checking
10
 *******************************************************************************/
11
 *******************************************************************************/
11
package org.eclipse.jdt.internal.compiler.lookup;
12
package org.eclipse.jdt.internal.compiler.lookup;
12
13
Lines 28-33 Link Here
28
	public char[] selector;
29
	public char[] selector;
29
	public TypeBinding returnType;
30
	public TypeBinding returnType;
30
	public TypeBinding[] parameters;
31
	public TypeBinding[] parameters;
32
	public Boolean[] parameterNonNullness; // TRUE means @NonNull declared, FALSE means @Nullable declared, null means nothing declared
31
	public ReferenceBinding[] thrownExceptions;
33
	public ReferenceBinding[] thrownExceptions;
32
	public ReferenceBinding declaringClass;
34
	public ReferenceBinding declaringClass;
33
	public TypeVariableBinding[] typeVariables = Binding.NO_TYPE_VARIABLES;
35
	public TypeVariableBinding[] typeVariables = Binding.NO_TYPE_VARIABLES;
(-)compiler/org/eclipse/jdt/internal/compiler/lookup/MethodVerifier.java (-2 / +6 lines)
Lines 1-5 Link Here
1
/*******************************************************************************
1
/*******************************************************************************
2
 * Copyright (c) 2000, 2010 IBM Corporation and others.
2
 * Copyright (c) 2000, 2011 IBM Corporation and others.
3
 * All rights reserved. This program and the accompanying materials
3
 * All rights reserved. This program and the accompanying materials
4
 * are made available under the terms of the Eclipse Public License v1.0
4
 * are made available under the terms of the Eclipse Public License v1.0
5
 * which accompanies this distribution, and is available at
5
 * which accompanies this distribution, and is available at
Lines 8-13 Link Here
8
 * Contributors:
8
 * Contributors:
9
 *     IBM Corporation - initial API and implementation
9
 *     IBM Corporation - initial API and implementation
10
 *     Benjamin Muskalla - Contribution for bug 239066
10
 *     Benjamin Muskalla - Contribution for bug 239066
11
 *     Stephan Herrmann  - Contribution for Bug 186342 - [compiler][null]Using annotations for null checking
11
 *******************************************************************************/
12
 *******************************************************************************/
12
package org.eclipse.jdt.internal.compiler.lookup;
13
package org.eclipse.jdt.internal.compiler.lookup;
13
14
Lines 152-157 Link Here
152
				// interface I { @Override Object clone(); } does not override Object#clone()
153
				// interface I { @Override Object clone(); } does not override Object#clone()
153
				currentMethod.modifiers |= ExtraCompilerModifiers.AccOverriding;
154
				currentMethod.modifiers |= ExtraCompilerModifiers.AccOverriding;
154
			}
155
			}
156
			checkNullContractCompatibility(currentMethod, inheritedMethod);
155
157
156
			if (!areReturnTypesCompatible(currentMethod, inheritedMethod)
158
			if (!areReturnTypesCompatible(currentMethod, inheritedMethod)
157
					&& (currentMethod.returnType.tagBits & TagBits.HasMissingType) == 0) {
159
					&& (currentMethod.returnType.tagBits & TagBits.HasMissingType) == 0) {
Lines 184-190 Link Here
184
		checkForBridgeMethod(currentMethod, inheritedMethod, allInheritedMethods);
186
		checkForBridgeMethod(currentMethod, inheritedMethod, allInheritedMethods);
185
	}
187
	}
186
}
188
}
187
189
protected void checkNullContractCompatibility(MethodBinding currentMethod, MethodBinding inheritedMethod) {
190
	// nothing to do here. Real action happens at 1.5+
191
}
188
public void reportRawReferences(MethodBinding currentMethod, MethodBinding inheritedMethod) {
192
public void reportRawReferences(MethodBinding currentMethod, MethodBinding inheritedMethod) {
189
	// nothing to do here. Real action happens at 1.5+
193
	// nothing to do here. Real action happens at 1.5+
190
}
194
}
(-)compiler/org/eclipse/jdt/internal/compiler/lookup/MethodVerifier15.java (-1 / +58 lines)
Lines 1-5 Link Here
1
/*******************************************************************************
1
/*******************************************************************************
2
 * Copyright (c) 2000, 2010 IBM Corporation and others.
2
 * Copyright (c) 2000, 2011 IBM Corporation and others.
3
 * All rights reserved. This program and the accompanying materials
3
 * All rights reserved. This program and the accompanying materials
4
 * are made available under the terms of the Eclipse Public License v1.0
4
 * are made available under the terms of the Eclipse Public License v1.0
5
 * which accompanies this distribution, and is available at
5
 * which accompanies this distribution, and is available at
Lines 7-12 Link Here
7
 *
7
 *
8
 * Contributors:
8
 * Contributors:
9
 *     IBM Corporation - initial API and implementation
9
 *     IBM Corporation - initial API and implementation
10
 *     Stephan Herrmann - Contribution for Bug 186342 - [compiler][null]Using annotations for null checking
10
 *******************************************************************************/
11
 *******************************************************************************/
11
package org.eclipse.jdt.internal.compiler.lookup;
12
package org.eclipse.jdt.internal.compiler.lookup;
12
13
Lines 407-412 Link Here
407
	return false;
408
	return false;
408
}
409
}
409
410
411
protected void checkNullContractCompatibility(MethodBinding currentMethod, MethodBinding inheritedMethod) {
412
	// return type:
413
	if ((inheritedMethod.tagBits & TagBits.AnnotationNonNull) != 0) {
414
		if ((currentMethod.tagBits & TagBits.AnnotationNullable) != 0) {
415
			AbstractMethodDeclaration methodDecl = currentMethod.sourceMethod();
416
			this.type.scope.problemReporter().illegalRedefinitionToNullableReturn(methodDecl, inheritedMethod.declaringClass, 
417
																			this.environment.globalOptions.nonNullAnnotationName);
418
		}
419
	}
420
	if ((currentMethod.tagBits & (TagBits.AnnotationNonNull|TagBits.AnnotationNullable)) == 0)
421
		currentMethod.tagBits |= (inheritedMethod.tagBits & (TagBits.AnnotationNonNull|TagBits.AnnotationNullable));
422
423
	// parameters:
424
	if (inheritedMethod.parameterNonNullness != null) {
425
		// inherited method has null-annotations, check and possibly transfer:
426
		
427
		// prepare for transfering (contract inheritance):
428
		if (currentMethod.parameterNonNullness == null)
429
			currentMethod.parameterNonNullness = new Boolean[currentMethod.parameters.length];
430
		
431
		for (int i = 0; i < inheritedMethod.parameterNonNullness.length; i++) {
432
			
433
			Boolean inheritedNonNullNess = inheritedMethod.parameterNonNullness[i];
434
			if (inheritedNonNullNess != Boolean.TRUE) { 	 				 // super parameter is not restricted to @NonNull
435
				if (currentMethod.parameterNonNullness[i] == Boolean.TRUE) { // current parameter is restricted to @NonNull
436
					this.type.scope.problemReporter().illegalRedefinitionToNonNullParameter(
437
																	currentMethod.sourceMethod().arguments[i],
438
																	inheritedMethod.declaringClass,
439
																	inheritedNonNullNess == null
440
																	? null
441
																	: this.environment.globalOptions.nullableAnnotationName);
442
					continue;
443
				} 
444
			}
445
			
446
			if (currentMethod.parameterNonNullness[i] == null && inheritedNonNullNess != null) {
447
				// inherit this annotation as the current method has no annotation:
448
				currentMethod.parameterNonNullness[i] = inheritedNonNullNess;
449
				VariableBinding argumentBinding = currentMethod.sourceMethod().arguments[i].binding;
450
				argumentBinding.tagBits |= inheritedNonNullNess.booleanValue()
451
												? TagBits.AnnotationNonNull : TagBits.AnnotationNullable;
452
			}
453
		}
454
	} else if (currentMethod.parameterNonNullness != null) {
455
		// super method has no annotations but current has
456
		for (int i = 0; i < currentMethod.parameterNonNullness.length; i++) {
457
			if (currentMethod.parameterNonNullness[i] == Boolean.TRUE) { // tightening from unconstrained to @NonNull
458
				this.type.scope.problemReporter().illegalRedefinitionToNonNullParameter(
459
																currentMethod.sourceMethod().arguments[i],
460
																inheritedMethod.declaringClass,
461
																null);
462
			}
463
		}
464
	}
465
}
466
410
void reportRawReferences() {
467
void reportRawReferences() {
411
	CompilerOptions compilerOptions = this.type.scope.compilerOptions();
468
	CompilerOptions compilerOptions = this.type.scope.compilerOptions();
412
	if (compilerOptions.sourceLevel < ClassFileConstants.JDK1_5 // shouldn't whine at all
469
	if (compilerOptions.sourceLevel < ClassFileConstants.JDK1_5 // shouldn't whine at all
(-)compiler/org/eclipse/jdt/internal/compiler/lookup/SourceTypeBinding.java (-2 / +5 lines)
Lines 7-12 Link Here
7
 *
7
 *
8
 * Contributors:
8
 * Contributors:
9
 *     IBM Corporation - initial API and implementation
9
 *     IBM Corporation - initial API and implementation
10
 *     Stephan Herrmann - Contribution for Bug 186342 - [compiler][null]Using annotations for null checking
10
 *******************************************************************************/
11
 *******************************************************************************/
11
package org.eclipse.jdt.internal.compiler.lookup;
12
package org.eclipse.jdt.internal.compiler.lookup;
12
13
Lines 1420-1428 Link Here
1420
			}
1421
			}
1421
		}
1422
		}
1422
		// only assign parameters if no problems are found
1423
		// only assign parameters if no problems are found
1423
		if (!foundArgProblem) {
1424
		if (foundArgProblem) {
1425
			methodDecl.binding = null;
1426
		} else {
1424
			method.parameters = newParameters;
1427
			method.parameters = newParameters;
1425
		}
1428
		}
1429
		methodDecl.bindArguments();
1426
	}
1430
	}
1427
1431
1428
	boolean foundReturnTypeProblem = false;
1432
	boolean foundReturnTypeProblem = false;
Lines 1465-1471 Link Here
1465
		}
1469
		}
1466
	}
1470
	}
1467
	if (foundArgProblem) {
1471
	if (foundArgProblem) {
1468
		methodDecl.binding = null;
1469
		method.parameters = Binding.NO_PARAMETERS; // see 107004
1472
		method.parameters = Binding.NO_PARAMETERS; // see 107004
1470
		// nullify type parameter bindings as well as they have a backpointer to the method binding
1473
		// nullify type parameter bindings as well as they have a backpointer to the method binding
1471
		// (see https://bugs.eclipse.org/bugs/show_bug.cgi?id=81134)
1474
		// (see https://bugs.eclipse.org/bugs/show_bug.cgi?id=81134)
(-)compiler/org/eclipse/jdt/internal/compiler/lookup/TagBits.java (-4 / +8 lines)
Lines 1-5 Link Here
1
/*******************************************************************************
1
/*******************************************************************************
2
 * Copyright (c) 2000, 2010 IBM Corporation and others.
2
 * Copyright (c) 2000, 2011 IBM Corporation and others.
3
 * All rights reserved. This program and the accompanying materials
3
 * All rights reserved. This program and the accompanying materials
4
 * are made available under the terms of the Eclipse Public License v1.0
4
 * are made available under the terms of the Eclipse Public License v1.0
5
 * which accompanies this distribution, and is available at
5
 * which accompanies this distribution, and is available at
Lines 7-12 Link Here
7
 *
7
 *
8
 * Contributors:
8
 * Contributors:
9
 *     IBM Corporation - initial API and implementation
9
 *     IBM Corporation - initial API and implementation
10
 *     Stephan Herrmann - Contribution for Bug 186342 - [compiler][null]Using annotations for null checking
10
 *******************************************************************************/
11
 *******************************************************************************/
11
package org.eclipse.jdt.internal.compiler.lookup;
12
package org.eclipse.jdt.internal.compiler.lookup;
12
13
Lines 119-128 Link Here
119
	long AnnotationInherited = ASTNode.Bit49L;
120
	long AnnotationInherited = ASTNode.Bit49L;
120
	long AnnotationOverride = ASTNode.Bit50L;
121
	long AnnotationOverride = ASTNode.Bit50L;
121
	long AnnotationSuppressWarnings = ASTNode.Bit51L;
122
	long AnnotationSuppressWarnings = ASTNode.Bit51L;
122
	long AllStandardAnnotationsMask = AnnotationTargetMASK | AnnotationRetentionMASK | AnnotationDeprecated | AnnotationDocumented | AnnotationInherited |  AnnotationOverride | AnnotationSuppressWarnings;
123
	long AnnotationNullable = ASTNode.Bit52L;
124
	long AnnotationNonNull = ASTNode.Bit53L;
125
	long AllStandardAnnotationsMask = AnnotationTargetMASK | AnnotationRetentionMASK | AnnotationDeprecated | AnnotationDocumented 
126
				| AnnotationInherited |  AnnotationOverride | AnnotationSuppressWarnings | AnnotationNullable | AnnotationNonNull;
123
127
124
	long DefaultValueResolved = ASTNode.Bit52L;
128
	long DefaultValueResolved = ASTNode.Bit54L;
125
129
126
	// set when type contains non-private constructor(s)
130
	// set when type contains non-private constructor(s)
127
	long HasNonPrivateConstructor = ASTNode.Bit53L;
131
	long HasNonPrivateConstructor = ASTNode.Bit55L;
128
}
132
}
(-)compiler/org/eclipse/jdt/internal/compiler/lookup/TypeIds.java (-1 / +5 lines)
Lines 1-5 Link Here
1
/*******************************************************************************
1
/*******************************************************************************
2
 * Copyright (c) 2000, 2009 IBM Corporation and others.
2
 * Copyright (c) 2000, 2011 IBM Corporation and others.
3
 * All rights reserved. This program and the accompanying materials
3
 * All rights reserved. This program and the accompanying materials
4
 * are made available under the terms of the Eclipse Public License v1.0
4
 * are made available under the terms of the Eclipse Public License v1.0
5
 * which accompanies this distribution, and is available at
5
 * which accompanies this distribution, and is available at
Lines 7-12 Link Here
7
 *
7
 *
8
 * Contributors:
8
 * Contributors:
9
 *     IBM Corporation - initial API and implementation
9
 *     IBM Corporation - initial API and implementation
10
 *     Stephan Herrmann - Contribution for Bug 186342 - [compiler][null]Using annotations for null checking
10
 *******************************************************************************/
11
 *******************************************************************************/
11
package org.eclipse.jdt.internal.compiler.lookup;
12
package org.eclipse.jdt.internal.compiler.lookup;
12
13
Lines 89-94 Link Here
89
	
90
	
90
	final int T_JavaUtilCollection = 59;
91
	final int T_JavaUtilCollection = 59;
91
92
93
	final int T_ConfiguredAnnotationNullable = 60;
94
	final int T_ConfiguredAnnotationNonNull = 61;
95
92
	final int NoId = Integer.MAX_VALUE;
96
	final int NoId = Integer.MAX_VALUE;
93
97
94
	public static final int IMPLICIT_CONVERSION_MASK = 0xFF;
98
	public static final int IMPLICIT_CONVERSION_MASK = 0xFF;
(-)compiler/org/eclipse/jdt/internal/compiler/problem/ProblemReporter.java (-2 / +91 lines)
Lines 1-5 Link Here
1
/*******************************************************************************
1
/*******************************************************************************
2
 * Copyright (c) 2000, 2010 IBM Corporation and others.
2
 * Copyright (c) 2000, 2011 IBM Corporation and others.
3
 * All rights reserved. This program and the accompanying materials
3
 * All rights reserved. This program and the accompanying materials
4
 * are made available under the terms of the Eclipse Public License v1.0
4
 * are made available under the terms of the Eclipse Public License v1.0
5
 * which accompanies this distribution, and is available at
5
 * which accompanies this distribution, and is available at
Lines 8-14 Link Here
8
 * Contributors:
8
 * Contributors:
9
 *     IBM Corporation - initial API and implementation
9
 *     IBM Corporation - initial API and implementation
10
 *     Benjamin Muskalla - Contribution for bug 239066
10
 *     Benjamin Muskalla - Contribution for bug 239066
11
 *     Stephan Herrmann  - Contribution for bug 236385
11
 *     Stephan Herrmann  - Contributions for 
12
 *     							bug 236385 - [compiler] Warn for potential programming problem if an object is created but not used
13
 *     							bug 186342 - [compiler][null]Using annotations for null checking
12
 *******************************************************************************/
14
 *******************************************************************************/
13
package org.eclipse.jdt.internal.compiler.problem;
15
package org.eclipse.jdt.internal.compiler.problem;
14
16
Lines 81-86 Link Here
81
import org.eclipse.jdt.internal.compiler.classfmt.ClassFileConstants;
83
import org.eclipse.jdt.internal.compiler.classfmt.ClassFileConstants;
82
import org.eclipse.jdt.internal.compiler.env.AccessRestriction;
84
import org.eclipse.jdt.internal.compiler.env.AccessRestriction;
83
import org.eclipse.jdt.internal.compiler.env.ICompilationUnit;
85
import org.eclipse.jdt.internal.compiler.env.ICompilationUnit;
86
import org.eclipse.jdt.internal.compiler.flow.FlowInfo;
84
import org.eclipse.jdt.internal.compiler.impl.CompilerOptions;
87
import org.eclipse.jdt.internal.compiler.impl.CompilerOptions;
85
import org.eclipse.jdt.internal.compiler.impl.ReferenceContext;
88
import org.eclipse.jdt.internal.compiler.impl.ReferenceContext;
86
import org.eclipse.jdt.internal.compiler.lookup.ArrayBinding;
89
import org.eclipse.jdt.internal.compiler.lookup.ArrayBinding;
Lines 293-298 Link Here
293
		case IProblem.NullLocalVariableInstanceofYieldsFalse:
296
		case IProblem.NullLocalVariableInstanceofYieldsFalse:
294
			return CompilerOptions.RedundantNullCheck;
297
			return CompilerOptions.RedundantNullCheck;
295
298
299
		case IProblem.DefiniteNullFromNonNullMethod:
300
		case IProblem.DefiniteNullToNonnullParameter:
301
		case IProblem.IllegalRedefinitionToNullableReturn:
302
		case IProblem.IllegalRedefinitionToNonNullParameter:
303
		case IProblem.IllegalDefinitionToNonNullParameter:
304
			return CompilerOptions.NullContractViolation;
305
		case IProblem.PotentialNullFromNonNullMethod:
306
		case IProblem.PotentialNullToNonnullParameter:
307
			return CompilerOptions.PotentialNullContractViolation;
308
		case IProblem.NonNullParameterInsufficientInfo:
309
		case IProblem.NonNullReturnInsufficientInfo:
310
			return CompilerOptions.NullContractInsufficientInfo;
311
296
		case IProblem.BoxingConversion :
312
		case IProblem.BoxingConversion :
297
		case IProblem.UnboxingConversion :
313
		case IProblem.UnboxingConversion :
298
			return CompilerOptions.AutoBoxing;
314
			return CompilerOptions.AutoBoxing;
Lines 469-474 Link Here
469
			case CompilerOptions.NullReference :
485
			case CompilerOptions.NullReference :
470
			case CompilerOptions.PotentialNullReference :
486
			case CompilerOptions.PotentialNullReference :
471
			case CompilerOptions.RedundantNullCheck :
487
			case CompilerOptions.RedundantNullCheck :
488
			case CompilerOptions.NullContractViolation :
489
			case CompilerOptions.PotentialNullContractViolation :
490
			case CompilerOptions.NullContractInsufficientInfo :
472
			case CompilerOptions.IncompleteEnumSwitch :
491
			case CompilerOptions.IncompleteEnumSwitch :
473
			case CompilerOptions.FallthroughCase :
492
			case CompilerOptions.FallthroughCase :
474
			case CompilerOptions.OverridingMethodWithoutSuperInvocation :
493
			case CompilerOptions.OverridingMethodWithoutSuperInvocation :
Lines 530-535 Link Here
530
	switch (problemID) {
549
	switch (problemID) {
531
		case IProblem.IsClassPathCorrect :
550
		case IProblem.IsClassPathCorrect :
532
		case IProblem.CorruptedSignature :
551
		case IProblem.CorruptedSignature :
552
		case IProblem.ConflictingTypeEmulation :
553
		case IProblem.MissingNullAnnotationType :
533
			return CategorizedProblem.CAT_BUILDPATH;
554
			return CategorizedProblem.CAT_BUILDPATH;
534
555
535
		default :
556
		default :
Lines 1331-1336 Link Here
1331
		importRef.sourceStart,
1352
		importRef.sourceStart,
1332
		importRef.sourceEnd);
1353
		importRef.sourceEnd);
1333
}
1354
}
1355
public void conflictingTypeEmulation(char[][] compoundName) {
1356
	String[] arguments = new String[] {CharOperation.toString(compoundName)};
1357
	this.handle(
1358
		IProblem.ConflictingTypeEmulation,
1359
		arguments,
1360
		arguments,
1361
		ProblemSeverities.Error | ProblemSeverities.Abort | ProblemSeverities.Fatal, // not configurable
1362
		0, 0);	
1363
}
1334
public void constantOutOfRange(Literal literal, TypeBinding literalType) {
1364
public void constantOutOfRange(Literal literal, TypeBinding literalType) {
1335
	String[] arguments = new String[] {new String(literalType.readableName()), new String(literal.source())};
1365
	String[] arguments = new String[] {new String(literalType.readableName()), new String(literal.source())};
1336
	this.handle(
1366
	this.handle(
Lines 2437-2442 Link Here
2437
		qualifiedTypeReference.sourceStart,
2467
		qualifiedTypeReference.sourceStart,
2438
		qualifiedTypeReference.sourceEnd);
2468
		qualifiedTypeReference.sourceEnd);
2439
}
2469
}
2470
public void illegalRedefinitionToNonNullParameter(Argument argument, ReferenceBinding declaringClass, char[][] inheritedAnnotationName) {
2471
	if (inheritedAnnotationName == null) {
2472
		this.handle(
2473
			IProblem.IllegalDefinitionToNonNullParameter, 
2474
			new String[] { new String(argument.name), new String(declaringClass.readableName()) },
2475
			new String[] { new String(argument.name), new String(declaringClass.shortReadableName()) },
2476
			argument.sourceStart, 
2477
			argument.sourceEnd);
2478
		
2479
	} else {
2480
		this.handle(
2481
			IProblem.IllegalRedefinitionToNonNullParameter, 
2482
			new String[] { new String(argument.name), new String(declaringClass.readableName()), CharOperation.toString(inheritedAnnotationName)},
2483
			new String[] { new String(argument.name), new String(declaringClass.shortReadableName()), new String(inheritedAnnotationName[inheritedAnnotationName.length-1])},
2484
			argument.sourceStart, 
2485
			argument.sourceEnd);
2486
	}
2487
}
2488
public void illegalRedefinitionToNullableReturn(AbstractMethodDeclaration methodDecl, ReferenceBinding declaringClass, char[][] nonNullAnnotationName) {
2489
	this.handle(
2490
		IProblem.IllegalRedefinitionToNullableReturn, 
2491
		new String[] { new String(declaringClass.readableName()), CharOperation.toString(nonNullAnnotationName)},
2492
		new String[] { new String(declaringClass.shortReadableName()), new String(nonNullAnnotationName[nonNullAnnotationName.length-1])},
2493
		methodDecl.sourceStart, 
2494
		methodDecl.sourceEnd);	
2495
}
2440
public void illegalStaticModifierForMemberType(SourceTypeBinding type) {
2496
public void illegalStaticModifierForMemberType(SourceTypeBinding type) {
2441
	String[] arguments = new String[] {new String(type.sourceName())};
2497
	String[] arguments = new String[] {new String(type.sourceName())};
2442
	this.handle(
2498
	this.handle(
Lines 5116-5121 Link Here
5116
		switchStatement.expression.sourceStart,
5172
		switchStatement.expression.sourceStart,
5117
		switchStatement.expression.sourceEnd);
5173
		switchStatement.expression.sourceEnd);
5118
}
5174
}
5175
5176
public void missingNullAnnotationType(char[][] nullAnnotationName) {
5177
	String[] args = { new String(CharOperation.concatWith(nullAnnotationName, '.')) };
5178
	this.handle(IProblem.MissingNullAnnotationType, args, args, 0, 0);	
5179
}
5119
public void missingOverrideAnnotation(AbstractMethodDeclaration method) {
5180
public void missingOverrideAnnotation(AbstractMethodDeclaration method) {
5120
	int severity = computeSeverity(IProblem.MissingOverrideAnnotation);
5181
	int severity = computeSeverity(IProblem.MissingOverrideAnnotation);
5121
	if (severity == ProblemSeverities.Ignore) return;
5182
	if (severity == ProblemSeverities.Ignore) return;
Lines 6078-6083 Link Here
6078
		caseStatement.sourceStart,
6139
		caseStatement.sourceStart,
6079
		caseStatement.sourceEnd);
6140
		caseStatement.sourceEnd);
6080
}
6141
}
6142
public void possiblyNullFromNonNullMethod(ReturnStatement returnStatement, int nullStatus, char[] annotationName) {
6143
	int problemId = IProblem.NonNullReturnInsufficientInfo;
6144
	if ((nullStatus & FlowInfo.NULL) != 0)
6145
		problemId = IProblem.DefiniteNullFromNonNullMethod;
6146
	if ((nullStatus & FlowInfo.POTENTIALLY_NULL) != 0)
6147
		problemId = IProblem.PotentialNullFromNonNullMethod;
6148
	String[] arguments = new String[] { String.valueOf(annotationName) };
6149
	this.handle(
6150
		problemId,
6151
		arguments,
6152
		arguments,
6153
		returnStatement.sourceStart,
6154
		returnStatement.sourceEnd);
6155
}
6156
public void possiblyNullToNonNullParameter(Expression argument, int nullStatus, char[] annotationName) {
6157
	int problemId = IProblem.NonNullParameterInsufficientInfo;
6158
	if ((nullStatus & FlowInfo.NULL) != 0)
6159
		problemId = IProblem.DefiniteNullToNonnullParameter;
6160
	else if ((nullStatus & FlowInfo.POTENTIALLY_NULL) != 0)
6161
		problemId = IProblem.PotentialNullToNonnullParameter;
6162
	String[] arguments = new String[] { String.valueOf(annotationName) };
6163
	this.handle(
6164
		problemId,
6165
		arguments,
6166
		arguments,
6167
		argument.sourceStart,
6168
		argument.sourceEnd);
6169
}
6081
public void publicClassMustMatchFileName(CompilationUnitDeclaration compUnitDecl, TypeDeclaration typeDecl) {
6170
public void publicClassMustMatchFileName(CompilationUnitDeclaration compUnitDecl, TypeDeclaration typeDecl) {
6082
	this.referenceContext = typeDecl; // report the problem against the type not the entire compilation unit
6171
	this.referenceContext = typeDecl; // report the problem against the type not the entire compilation unit
6083
	String[] arguments = new String[] {new String(compUnitDecl.getFileName()), new String(typeDecl.name)};
6172
	String[] arguments = new String[] {new String(compUnitDecl.getFileName()), new String(typeDecl.name)};
(-)compiler/org/eclipse/jdt/internal/compiler/problem/messages.properties (-2 / +17 lines)
Lines 1-5 Link Here
1
###############################################################################
1
###############################################################################
2
# Copyright (c) 2000, 2010 IBM Corporation and others.
2
# Copyright (c) 2000, 2011 IBM Corporation and others.
3
# All rights reserved. This program and the accompanying materials
3
# All rights reserved. This program and the accompanying materials
4
# are made available under the terms of the Eclipse Public License v1.0
4
# are made available under the terms of the Eclipse Public License v1.0
5
# which accompanies this distribution, and is available at
5
# which accompanies this distribution, and is available at
Lines 8-14 Link Here
8
# Contributors:
8
# Contributors:
9
#     IBM Corporation - initial API and implementation
9
#     IBM Corporation - initial API and implementation
10
#		Benjamin Muskalla - Contribution for bug 239066
10
#		Benjamin Muskalla - Contribution for bug 239066
11
#		Stephan Herrmann <stephan@cs.tu-berlin.de> - Contribution for bug 185682 - Increment/decrement operators mark local variables as read
11
#		Stephan Herrmann <stephan@cs.tu-berlin.de> - Contributions for
12
#						bug 185682 - Increment/decrement operators mark local variables as read
13
#				 		bug 186342 - [compiler][null]Using annotations for null checking
12
###############################################################################
14
###############################################################################
13
0 = {0}
15
0 = {0}
14
1 = super cannot be used in java.lang.Object
16
1 = super cannot be used in java.lang.Object
Lines 619-624 Link Here
619
858 = The parameterized constructor <{3}>{0}({1}) of type {2} is not applicable for the arguments ({4})
621
858 = The parameterized constructor <{3}>{0}({1}) of type {2} is not applicable for the arguments ({4})
620
859 = The constructor {0}({1}) of raw type {2} is no longer generic; it cannot be parameterized with arguments <{3}>
622
859 = The constructor {0}({1}) of raw type {2} is no longer generic; it cannot be parameterized with arguments <{3}>
621
623
624
### NULL ANNOTATIONS
625
880 = Null contract violation: returning null from a method declared as @{0}.
626
881 = Null contract violation: return value can be null but method is declared as @{0}.
627
882 = Potential null contract violation: insufficient nullness information regarding return value while the method is declared as @{0}.
628
883 = Null contract violation: passing null to a parameter declared as @{0}.
629
884 = Null contract violation: potentially passing null to a parameter declared as @{0}.
630
885 = Potential null contract violation: insufficient nullness information regarding a value that is passed to a parameter declared as @{0}.
631
886 = Buildpath problem: emulation of type {0} is requested (for null annotations) but a type of this name exists on the build path.
632
887 = Buildpath problem: the type {0} which is configured as a null annotation type cannot be resolved.
633
888 = Cannot relax null contract for method return, inherited method from {0} is declared as @{1}.
634
889 = Cannot tighten null contract for parameter {0}, inherited method from {1} declares this parameter as @{2}.
635
890 = Cannot tighten null contract for parameter {0}, inherited method from {1} does not constrain this parameter.
636
622
### ELABORATIONS
637
### ELABORATIONS
623
## Access restrictions
638
## Access restrictions
624
78592 = The type {1} is not accessible due to restriction on classpath entry {0}
639
78592 = The type {1} is not accessible due to restriction on classpath entry {0}
(-)model/org/eclipse/jdt/core/JavaCore.java (-3 / +177 lines)
Lines 1-5 Link Here
1
/*******************************************************************************
1
/*******************************************************************************
2
 * Copyright (c) 2000, 2010 IBM Corporation and others.
2
 * Copyright (c) 2000, 2011 IBM Corporation and others.
3
 * All rights reserved. This program and the accompanying materials
3
 * All rights reserved. This program and the accompanying materials
4
 * are made available under the terms of the Eclipse Public License v1.0
4
 * are made available under the terms of the Eclipse Public License v1.0
5
 * which accompanies this distribution, and is available at
5
 * which accompanies this distribution, and is available at
Lines 81-88 Link Here
81
 *                                 COMPILER_PB_UNUSED_DECLARED_THROWN_EXCEPTION_EXEMPT_EXCEPTION_AND_THROWABLE
81
 *                                 COMPILER_PB_UNUSED_DECLARED_THROWN_EXCEPTION_EXEMPT_EXCEPTION_AND_THROWABLE
82
 *     IBM Corporation - added getOptionForConfigurableSeverity(int)
82
 *     IBM Corporation - added getOptionForConfigurableSeverity(int)
83
 *     Benjamin Muskalla - added COMPILER_PB_MISSING_SYNCHRONIZED_ON_INHERITED_METHOD
83
 *     Benjamin Muskalla - added COMPILER_PB_MISSING_SYNCHRONIZED_ON_INHERITED_METHOD
84
 *     Stephan Herrmann  - added COMPILER_PB_UNUSED_OBJECT_ALLOCATION
84
 *     Stephan Herrmann  - added the following constants:
85
 *     Stephan Herrmann  - added COMPILER_PB_SUPPRESS_OPTIONAL_ERRORS
85
 *     								COMPILER_PB_UNUSED_OBJECT_ALLOCATION
86
 *     								COMPILER_PB_SUPPRESS_OPTIONAL_ERRORS
87
 *     								COMPILER_NULLABLE_ANNOTATION_NAME
88
 *     								COMPILER_NONNULL_ANNOTATION_NAME
89
 *     								COMPILER_EMULATE_NULL_ANNOTATION_TYPES
90
 *     								COMPILER_DEFAULT_IMPORT_NULL_ANNOTATION_TYPES
91
 *     								COMPILER_PB_NULL_CONTRACT_VIOLATION
92
 *     							 	COMPILER_PB_POTENTIAL_NULL_CONTRACT_VIOLATION
93
 *     							 	COMPILER_PB_NULL_CONTRACT_INSUFFICIENT_INFO
86
 *******************************************************************************/
94
 *******************************************************************************/
87
95
88
package org.eclipse.jdt.core;
96
package org.eclipse.jdt.core;
Lines 1576-1581 Link Here
1576
	 */
1584
	 */
1577
	public static final String COMPILER_PB_POTENTIAL_NULL_REFERENCE = PLUGIN_ID + ".compiler.problem.potentialNullReference"; //$NON-NLS-1$
1585
	public static final String COMPILER_PB_POTENTIAL_NULL_REFERENCE = PLUGIN_ID + ".compiler.problem.potentialNullReference"; //$NON-NLS-1$
1578
	/**
1586
	/**
1587
	 * Compiler option ID: Name of Annotation Type for Nullable Types.
1588
	 * <p>This option defines a fully qualified Java type name that the compiler may use
1589
	 *    to perform special null analysis.</p>
1590
	 * <p>If the annotation specified by this option is applied to a type in a method
1591
	 *    signature or variable declaration this will be interpreted as a contract that 
1592
	 *    <code>null</code> is a legal value in that position. Currently supported
1593
	 *    positions are: method parameters and method return type.</p>
1594
	 * <p>If a value whose type
1595
	 *    is annotated with this annotation is dereferenced without checking for null
1596
	 *    the compiler will trigger a diagnostic as further controlled by 
1597
	 *    {@link #COMPILER_PB_POTENTIAL_NULL_REFERENCE}.</p>
1598
	 * <p>The compiler may furthermore check adherence to the null contract as further
1599
	 *    controlled by {@link #COMPILER_PB_NULL_CONTRACT_VIOLATION}, 
1600
	 *    {@link #COMPILER_PB_POTENTIAL_NULL_CONTRACT_VIOLATION} and
1601
	 *    {@link #COMPILER_PB_NULL_CONTRACT_INSUFFICIENT_INFO}.
1602
	 * </p>
1603
	 * <dt>Option id:</dt><dd><code>"org.eclipse.jdt.core.compiler.annotation.nullable"</code></dd>
1604
	 * <dt>Possible values:</dt><dd>any legal Java type name</dd>
1605
	 * <dt>Default:</dt><dd><code>"org.eclipse.jdt.annotation.Nullable"</code></dd>
1606
	 * @since 3.7
1607
	 * @category CompilerOptionID
1608
	 */
1609
	public static final String COMPILER_NULLABLE_ANNOTATION_NAME = PLUGIN_ID + ".compiler.annotation.nullable"; //$NON-NLS-1$
1610
	/**
1611
	 * Compiler option ID: Name of Annotation Type for Non-Null Types.
1612
	 * <p>This option defines a fully qualified Java type name that the compiler may use
1613
	 *    to perform special null analysis.</p>
1614
	 * <p>If the annotation specified by this option is applied to a type in a method
1615
	 *    signature or variable declaration this will be interpreted as a contract that 
1616
	 *    <code>null</code> is <b>not</b> a legal value in that position. Currently 
1617
	 *    supported positions are: method parameters and method return type.</p>
1618
	 * <p>For values declared with this annotation the compiler will never trigger a null
1619
	 *    reference diagnostic (as controlled by {@link #COMPILER_PB_POTENTIAL_NULL_REFERENCE}
1620
	 *    and {@link #COMPILER_PB_NULL_REFERENCE}), because the assumption is made that null
1621
	 *    will never occur at runtime in these positions.</p>
1622
	 * <p>The compiler may furthermore check adherence to the null contract as further
1623
	 *    controlled by {@link #COMPILER_PB_NULL_CONTRACT_VIOLATION}, 
1624
	 *    {@link #COMPILER_PB_POTENTIAL_NULL_CONTRACT_VIOLATION} and
1625
	 *    {@link #COMPILER_PB_NULL_CONTRACT_INSUFFICIENT_INFO}.
1626
	 * </p>
1627
	 * <dt>Option id:</dt><dd><code>"org.eclipse.jdt.core.compiler.annotation.nonnull"</code></dd>
1628
	 * <dt>Possible values:</dt><dd>any legal Java type name</dd>
1629
	 * <dt>Default:</dt><dd><code>"org.eclipse.jdt.annotation.NonNull"</code></dd>
1630
	 * @since 3.7
1631
	 * @category CompilerOptionID
1632
	 */
1633
	public static final String COMPILER_NONNULL_ANNOTATION_NAME = PLUGIN_ID + ".compiler.annotation.nonnull"; //$NON-NLS-1$
1634
	/**
1635
	 * Compiler option ID: Emulate Null Annotation Types.
1636
	 * <p>When enabled, the compiler will use the annotation types specified in
1637
	 *    {@link #COMPILER_NONNULL_ANNOTATION_NAME} and {@link #COMPILER_NULLABLE_ANNOTATION_NAME}
1638
	 *    without searching for a corresponding type definition, ie., these annotation
1639
	 *    types don't have to actually exist.</p>
1640
	 * <p>This option is used to make null contract analysis independent of any additional
1641
	 *    classes that would otherwise need to be supplied at compile time.</p>
1642
	 * <dt>Option id:</dt><dd><code>"org.eclipse.jdt.core.compiler.annotation.emulate"</code></dd>
1643
	 * <dt>Possible values:</dt><dd>{ "disabled", "enabled" }</dd>
1644
	 * <dt>Default:</dt><dd><code>"disabled"</code></dd>
1645
	 * @since 3.7
1646
	 * @category CompilerOptionID
1647
	 */
1648
	public static final String COMPILER_EMULATE_NULL_ANNOTATION_TYPES = PLUGIN_ID + ".compiler.annotation.emulate"; //$NON-NLS-1$
1649
	/**
1650
	 * Compiler option ID: Default Import of Null Annotation Types.
1651
	 * <p>When enabled, the compiler will be able to resolve the annotation types specified in
1652
	 *    {@link #COMPILER_NONNULL_ANNOTATION_NAME} and {@link #COMPILER_NULLABLE_ANNOTATION_NAME}
1653
	 *    by their simple names without an explicit import statement.</p>
1654
	 * <p>This option is used to avoid mentioning the fully qualified annotation names
1655
	 *    in any source files, as to facility the migration from one set of annotations
1656
	 *    to another, e.g., when standard annotations for this purpose will be defined
1657
	 *    in the future.
1658
	 * </p> 
1659
	 * <dt>Option id:</dt><dd><code>"org.eclipse.jdt.core.compiler.annotation.defaultImport"</code></dd>
1660
	 * <dt>Possible values:</dt><dd>{ "disabled", "enabled" }</dd>
1661
	 * <dt>Default:</dt><dd><code>"disabled"</code></dd>
1662
	 * @since 3.7
1663
	 * @category CompilerOptionID
1664
	 */
1665
	public static final String COMPILER_DEFAULT_IMPORT_NULL_ANNOTATION_TYPES = PLUGIN_ID + ".compiler.annotation.defaultImport"; //$NON-NLS-1$
1666
	/**
1667
	 * Compiler option ID: Reporting Violations of Null Contracts.
1668
	 * <p>When enabled, the compiler will issue an error or a warning whenever one of the 
1669
	 *    following situations is detected:
1670
	 *    <ol>
1671
	 *    <li>A method declared with a nonnull annotation returns an expression that is 
1672
	 *    	  statically known to evaluate to a null value.</li>
1673
	 *    <li>An expression that is statically known to evaluate to a null value is passed 
1674
	 *        as an argument in a method call where the corresponding parameter of the called
1675
	 *        method is declared with a nonnull annotation.</li>
1676
	 *    <li>A method that overrides an inherited method declared with a nonnull annotation
1677
	 *        tries to relax that contract by specifying a nullable annotation
1678
	 *        (prohibition of contravariant return).</li>
1679
	 *    <li>A method that overrides an inherited method which has a nullable declaration
1680
	 *        for at least one of its parameters, tries to tighten that null contract by
1681
	 *        specifying a nonnull annotation for its corresponding parameter
1682
	 *        (prohibition of covariant parameters).</li>
1683
	 *    </ol>         
1684
	 * </p>
1685
	 * <p>The compiler options {@link #COMPILER_NONNULL_ANNOTATION_NAME} and
1686
	 *    {@link #COMPILER_NULLABLE_ANNOTATION_NAME} control which annotations the compiler
1687
	 *    shall interpret as nonnull or nullable annotations, respectively.
1688
	 * </p>
1689
	 * <dl>
1690
	 * <dt>Option id:</dt><dd><code>"org.eclipse.jdt.core.compiler.problem.nullContractViolation"</code></dd>
1691
	 * <dt>Possible values:</dt><dd><code>{ "error", "warning", "ignore" }</code></dd>
1692
	 * <dt>Default:</dt><dd><code>"error"</code></dd>
1693
	 * </dl>
1694
	 * @since 3.7
1695
	 * @category CompilerOptionID
1696
	 */
1697
	public static final String COMPILER_PB_NULL_CONTRACT_VIOLATION = PLUGIN_ID + ".compiler.problem.nullContractViolation"; //$NON-NLS-1$
1698
	/**
1699
	 * Compiler option ID: Reporting Violations of Null Contracts with Potential Null Value.
1700
	 * <p>When enabled, the compiler will issue an error or a warning whenever one of the 
1701
	 *    following situations is detected:
1702
	 *    <ol>
1703
	 *    <li>A method declared with a nonnull annotation returns an expression that is 
1704
	 *    	  statically known to evaluate to a null value on some flow.</li>
1705
	 *    <li>An expression that is statically known to evaluate to a null value on some flow
1706
	 *        is passed as an argument in a method call where the corresponding parameter of 
1707
	 *        the called method is declared with a nonnull annotation.</li>
1708
	 *    </ol>         
1709
	 * </p>
1710
	 * <p>The compiler options {@link #COMPILER_NONNULL_ANNOTATION_NAME} and
1711
	 *    {@link #COMPILER_NULLABLE_ANNOTATION_NAME} control which annotations the compiler
1712
	 *    shall interpret as nonnull or nullable annotations, respectively.
1713
	 * </p>
1714
	 * <dl>
1715
	 * <dt>Option id:</dt><dd><code>"org.eclipse.jdt.core.compiler.problem.potentialNullContractViolation"</code></dd>
1716
	 * <dt>Possible values:</dt><dd><code>{ "error", "warning", "ignore" }</code></dd>
1717
	 * <dt>Default:</dt><dd><code>"error"</code></dd>
1718
	 * </dl>
1719
	 * @since 3.7
1720
	 * @category CompilerOptionID
1721
	 */
1722
	public static final String COMPILER_PB_POTENTIAL_NULL_CONTRACT_VIOLATION = PLUGIN_ID + ".compiler.problem.potentialNullContractViolation"; //$NON-NLS-1$
1723
	/**
1724
	 * Compiler option ID: Reporting Insufficient Information for Analysing Adherence to Null Contracts.
1725
	 * <p>When enabled, the compiler will issue an error or a warning whenever one of the 
1726
	 *    following situations is detected:
1727
	 *    <ol>
1728
	 *    <li>A method declared with a nonnull annotation returns an expression for which 
1729
	 *        insufficient nullness information is available for statically proving that no
1730
	 *        flow will pass a null value at runtime.</li>
1731
	 *    <li>An expression for which insufficient nullness information is available for 
1732
	 *        statically proving that it will never evaluate to a null value at runtime
1733
	 *        is passed as an argument in a method call where the corresponding parameter of 
1734
	 *        the called method is declared with a nonnull annotation.</li>
1735
	 *    </ol>
1736
	 *    Insufficient nullness information is usually a consequence of using other unannotated
1737
	 *    variables or methods.
1738
	 * </p>
1739
	 * <p>The compiler options {@link #COMPILER_NONNULL_ANNOTATION_NAME} and
1740
	 *    {@link #COMPILER_NULLABLE_ANNOTATION_NAME} control which annotations the compiler
1741
	 *    shall interpret as nonnull or nullable annotations, respectively.
1742
	 * </p>
1743
	 * <dl>
1744
	 * <dt>Option id:</dt><dd><code>"org.eclipse.jdt.core.compiler.problem.nullContractInsufficientInfo"</code></dd>
1745
	 * <dt>Possible values:</dt><dd><code>{ "error", "warning", "ignore" }</code></dd>
1746
	 * <dt>Default:</dt><dd><code>"warning"</code></dd>
1747
	 * </dl>
1748
	 * @since 3.7
1749
	 * @category CompilerOptionID
1750
	 */
1751
	public static final String COMPILER_PB_NULL_CONTRACT_INSUFFICIENT_INFO = PLUGIN_ID + ".compiler.problem.nullContractInsufficientInfo"; //$NON-NLS-1$
1752
	/**
1579
	 * Compiler option ID: Reporting Redundant Null Check.
1753
	 * Compiler option ID: Reporting Redundant Null Check.
1580
	 * <p>When enabled, the compiler will issue an error or a warning whenever a
1754
	 * <p>When enabled, the compiler will issue an error or a warning whenever a
1581
	 *    variable that is statically known to hold a null or a non-null value
1755
	 *    variable that is statically known to hold a null or a non-null value
(-)src/org/eclipse/jdt/core/tests/compiler/regression/BatchCompilerTest.java (-3 / +90 lines)
Lines 1-5 Link Here
1
/*******************************************************************************
1
/*******************************************************************************
2
 * Copyright (c) 2000, 2010 IBM Corporation and others.
2
 * Copyright (c) 2000, 2011 IBM Corporation and others.
3
 * All rights reserved. This program and the accompanying materials
3
 * All rights reserved. This program and the accompanying materials
4
 * are made available under the terms of the Eclipse Public License v1.0
4
 * are made available under the terms of the Eclipse Public License v1.0
5
 * which accompanies this distribution, and is available at
5
 * which accompanies this distribution, and is available at
Lines 10-16 Link Here
10
 *     Benjamin Muskalla - Contribution for bug 239066
10
 *     Benjamin Muskalla - Contribution for bug 239066
11
 *     Stephan Herrmann  - Contribution for bug 236385
11
 *     Stephan Herrmann  - Contribution for bug 236385
12
 *     Stephan Herrmann  - Contribution for bug 295551
12
 *     Stephan Herrmann  - Contribution for bug 295551
13
 *     Stephan Herrmann <stephan@cs.tu-berlin.de> - Contribution for bug 185682 - Increment/decrement operators mark local variables as read
13
 *     Stephan Herrmann <stephan@cs.tu-berlin.de> - Contributions for 
14
 *     						bug 185682 - Increment/decrement operators mark local variables as read
15
 *     						bug 186342 - [compiler][null]Using annotations for null checking
14
 *******************************************************************************/
16
 *******************************************************************************/
15
package org.eclipse.jdt.core.tests.compiler.regression;
17
package org.eclipse.jdt.core.tests.compiler.regression;
16
18
Lines 48-54 Link Here
48
	private static final Main MAIN = new Main(null/*outWriter*/, null/*errWriter*/, false/*systemExit*/, null/*options*/, null/*progress*/);
50
	private static final Main MAIN = new Main(null/*outWriter*/, null/*errWriter*/, false/*systemExit*/, null/*options*/, null/*progress*/);
49
51
50
	static {
52
	static {
51
//		TESTS_NAMES = new String[] { "test295_warn_options" };
53
//		TESTS_NAMES = new String[] { "testNullAnnotations" };
52
//		TESTS_NUMBERS = new int[] { 306 };
54
//		TESTS_NUMBERS = new int[] { 306 };
53
//		TESTS_RANGE = new int[] { 298, -1 };
55
//		TESTS_RANGE = new int[] { 298, -1 };
54
	}
56
	}
Lines 1589-1594 Link Here
1589
        "    -classNames <className1[,className2,...]>\n" +
1591
        "    -classNames <className1[,className2,...]>\n" +
1590
        "                         qualified names of binary classes to process\n" +
1592
        "                         qualified names of binary classes to process\n" +
1591
        " \n" +
1593
        " \n" +
1594
        " Null annotation options:\n" +
1595
		"    -nullAnnotations:<suboptions>\n" +
1596
		"                      enable use of annotations for specifying null contracts;\n" +
1597
		"                      <suboptions> is a non-empty, comma-separated list of:\n" +
1598
		"        nullable=<typename>\n" +
1599
		"                      specifies the fully qualified name of an annotation type\n" +
1600
		"                      to be used for marking types whose values include null\n" +
1601
		"        nonnull=<typename>\n" +
1602
		"                      specifies the fully qualified name of an annotation type\n" +
1603
		"                      to be used for marking types whose values cannot be null\n" +
1604
		"        emulate       tells the compiler to emulate the above annotation types\n" +
1605
		"                      although they do not exist on the classpath\n" +
1606
		"        import        tells the compiler to import the above annotation types\n" +
1607
		"                      without specific mention in the sources such that their\n" +
1608
		"                      simple names can be used without explicit imports\n" +
1609
		" \n" +
1592
        " Advanced options:\n" +
1610
        " Advanced options:\n" +
1593
        "    @<file>            read command line arguments from file\n" +
1611
        "    @<file>            read command line arguments from file\n" +
1594
        "    -maxProblems <n>   max number of problems per compilation unit (100 by\n" +
1612
        "    -maxProblems <n>   max number of problems per compilation unit (100 by\n" +
Lines 1793-1798 Link Here
1793
			"		<argument value=\"---OUTPUT_DIR_PLACEHOLDER---\"/>\n" + 
1811
			"		<argument value=\"---OUTPUT_DIR_PLACEHOLDER---\"/>\n" + 
1794
			"	</command_line>\n" + 
1812
			"	</command_line>\n" + 
1795
			"	<options>\n" + 
1813
			"	<options>\n" + 
1814
			"		<option key=\"org.eclipse.jdt.core.compiler.annotation.defaultImport\" value=\"disabled\"/>\n" + 
1815
			"		<option key=\"org.eclipse.jdt.core.compiler.annotation.emulate\" value=\"disabled\"/>\n" + 
1796
			"		<option key=\"org.eclipse.jdt.core.compiler.codegen.inlineJsrBytecode\" value=\"disabled\"/>\n" + 
1816
			"		<option key=\"org.eclipse.jdt.core.compiler.codegen.inlineJsrBytecode\" value=\"disabled\"/>\n" + 
1797
			"		<option key=\"org.eclipse.jdt.core.compiler.codegen.targetPlatform\" value=\"1.5\"/>\n" + 
1817
			"		<option key=\"org.eclipse.jdt.core.compiler.codegen.targetPlatform\" value=\"1.5\"/>\n" + 
1798
			"		<option key=\"org.eclipse.jdt.core.compiler.codegen.unusedLocal\" value=\"optimize out\"/>\n" + 
1818
			"		<option key=\"org.eclipse.jdt.core.compiler.codegen.unusedLocal\" value=\"optimize out\"/>\n" + 
Lines 1850-1860 Link Here
1850
			"		<option key=\"org.eclipse.jdt.core.compiler.problem.noEffectAssignment\" value=\"warning\"/>\n" + 
1870
			"		<option key=\"org.eclipse.jdt.core.compiler.problem.noEffectAssignment\" value=\"warning\"/>\n" + 
1851
			"		<option key=\"org.eclipse.jdt.core.compiler.problem.noImplicitStringConversion\" value=\"warning\"/>\n" + 
1871
			"		<option key=\"org.eclipse.jdt.core.compiler.problem.noImplicitStringConversion\" value=\"warning\"/>\n" + 
1852
			"		<option key=\"org.eclipse.jdt.core.compiler.problem.nonExternalizedStringLiteral\" value=\"ignore\"/>\n" + 
1872
			"		<option key=\"org.eclipse.jdt.core.compiler.problem.nonExternalizedStringLiteral\" value=\"ignore\"/>\n" + 
1873
			"		<option key=\"org.eclipse.jdt.core.compiler.problem.nullContractInsufficientInfo\" value=\"warning\"/>\n" + 
1874
			"		<option key=\"org.eclipse.jdt.core.compiler.problem.nullContractViolation\" value=\"error\"/>\n" + 
1853
			"		<option key=\"org.eclipse.jdt.core.compiler.problem.nullReference\" value=\"warning\"/>\n" + 
1875
			"		<option key=\"org.eclipse.jdt.core.compiler.problem.nullReference\" value=\"warning\"/>\n" + 
1854
			"		<option key=\"org.eclipse.jdt.core.compiler.problem.overridingMethodWithoutSuperInvocation\" value=\"ignore\"/>\n" + 
1876
			"		<option key=\"org.eclipse.jdt.core.compiler.problem.overridingMethodWithoutSuperInvocation\" value=\"ignore\"/>\n" + 
1855
			"		<option key=\"org.eclipse.jdt.core.compiler.problem.overridingPackageDefaultMethod\" value=\"warning\"/>\n" + 
1877
			"		<option key=\"org.eclipse.jdt.core.compiler.problem.overridingPackageDefaultMethod\" value=\"warning\"/>\n" + 
1856
			"		<option key=\"org.eclipse.jdt.core.compiler.problem.parameterAssignment\" value=\"ignore\"/>\n" + 
1878
			"		<option key=\"org.eclipse.jdt.core.compiler.problem.parameterAssignment\" value=\"ignore\"/>\n" + 
1857
			"		<option key=\"org.eclipse.jdt.core.compiler.problem.possibleAccidentalBooleanAssignment\" value=\"ignore\"/>\n" + 
1879
			"		<option key=\"org.eclipse.jdt.core.compiler.problem.possibleAccidentalBooleanAssignment\" value=\"ignore\"/>\n" + 
1880
			"		<option key=\"org.eclipse.jdt.core.compiler.problem.potentialNullContractViolation\" value=\"error\"/>\n" + 
1858
			"		<option key=\"org.eclipse.jdt.core.compiler.problem.potentialNullReference\" value=\"ignore\"/>\n" + 
1881
			"		<option key=\"org.eclipse.jdt.core.compiler.problem.potentialNullReference\" value=\"ignore\"/>\n" + 
1859
			"		<option key=\"org.eclipse.jdt.core.compiler.problem.rawTypeReference\" value=\"warning\"/>\n" + 
1882
			"		<option key=\"org.eclipse.jdt.core.compiler.problem.rawTypeReference\" value=\"warning\"/>\n" + 
1860
			"		<option key=\"org.eclipse.jdt.core.compiler.problem.redundantNullCheck\" value=\"ignore\"/>\n" + 
1883
			"		<option key=\"org.eclipse.jdt.core.compiler.problem.redundantNullCheck\" value=\"ignore\"/>\n" + 
Lines 12264-12267 Link Here
12264
		"3 problems (1 error, 2 warnings)",
12287
		"3 problems (1 error, 2 warnings)",
12265
		true);
12288
		true);
12266
}
12289
}
12290
// https://bugs.eclipse.org/bugs/show_bug.cgi?id=186342  -- minimal options passed
12291
public void testNullAnnotations1() {
12292
	this.runNegativeTest(
12293
		new String[] {
12294
			"X.java",
12295
			"public class X {\n" +
12296
			"    @org.eclipse.jdt.annotation.NonNull Object foo(boolean b) {\n" +
12297
			"          return null;\n" +
12298
			"    }\n" +
12299
			"}\n"
12300
		},
12301
		"\"" + OUTPUT_DIR +  File.separator + "X.java\""
12302
		+ " -1.5 -nullAnnotations:emulate -d \"" + OUTPUT_DIR + "\"",
12303
		"",
12304
		"----------\n" + 
12305
		"1. ERROR in ---OUTPUT_DIR_PLACEHOLDER---/X.java (at line 3)\n" + 
12306
		"	return null;\n" + 
12307
		"	^^^^^^^^^^^^\n" + 
12308
		"Null contract violation: returning null from a method declared as @NonNull.\n" +
12309
		"----------\n" + 
12310
		"1 problem (1 error)",
12311
		true);
12312
}
12313
// https://bugs.eclipse.org/bugs/show_bug.cgi?id=186342  -- full options passed
12314
public void testNullAnnotations2() {
12315
	this.runNegativeTest(
12316
		new String[] {
12317
			"X.java",
12318
			"public class X {\n" +
12319
			"    @NichtNull Object foo(boolean b) {\n" +
12320
			"          return null;\n" +
12321
			"    }\n" +
12322
			"}\n"
12323
		},
12324
		"\"" + OUTPUT_DIR +  File.separator + "X.java\""
12325
		+ " -1.5 -nullAnnotations:nullable=org.foo.Nullish,emulate,import,nonnull=de.foo.NichtNull -d \"" + OUTPUT_DIR + "\"",
12326
		"",
12327
		"----------\n" + 
12328
		"1. ERROR in ---OUTPUT_DIR_PLACEHOLDER---/X.java (at line 3)\n" + 
12329
		"	return null;\n" + 
12330
		"	^^^^^^^^^^^^\n" + 
12331
		"Null contract violation: returning null from a method declared as @NichtNull.\n" +
12332
		"----------\n" + 
12333
		"1 problem (1 error)",
12334
		true);
12335
}
12336
// https://bugs.eclipse.org/bugs/show_bug.cgi?id=186342  -- unrecognized sub-option
12337
public void testNullAnnotations3() {
12338
	this.runNegativeTest(
12339
		new String[] {
12340
			"X.java",
12341
			"public class X {\n" +
12342
			"    @NichtNull Object foo(boolean b) {\n" +
12343
			"          return null;\n" +
12344
			"    }\n" +
12345
			"}\n"
12346
		},
12347
		"\"" + OUTPUT_DIR +  File.separator + "X.java\""
12348
		+ " -1.5 -nullAnnotations:wrong -d \"" + OUTPUT_DIR + "\"",
12349
		"",
12350
		"Unrecognized sub-option of -nullAnnotations: wrong,\n" + 
12351
		"legal values are nullable=.., nonnull=.., emulate and import\n",
12352
		true);
12353
}
12267
}
12354
}
(-)src/org/eclipse/jdt/core/tests/compiler/regression/CompilerInvocationTests.java (-2 / +24 lines)
Lines 1-5 Link Here
1
/*******************************************************************************
1
/*******************************************************************************
2
 * Copyright (c) 2006, 2010 IBM Corporation and others.
2
 * Copyright (c) 2006, 2011 IBM Corporation and others.
3
 * All rights reserved. This program and the accompanying materials
3
 * All rights reserved. This program and the accompanying materials
4
 * are made available under the terms of the Eclipse Public License v1.0
4
 * are made available under the terms of the Eclipse Public License v1.0
5
 * which accompanies this distribution, and is available at
5
 * which accompanies this distribution, and is available at
Lines 8-14 Link Here
8
 * Contributors:
8
 * Contributors:
9
 *     IBM Corporation - initial API and implementation
9
 *     IBM Corporation - initial API and implementation
10
 *     Benjamin Muskalla - Contribution for bug 239066
10
 *     Benjamin Muskalla - Contribution for bug 239066
11
 *     Stephan Herrmann  - Contribution for bug 236385
11
 *     Stephan Herrmann  - Contributions for 
12
 *     							bug 236385 - [compiler] Warn for potential programming problem if an object is created but not used
13
 *     							bug 186342 - [compiler][null]Using annotations for null checking
12
 *******************************************************************************/
14
 *******************************************************************************/
13
package org.eclipse.jdt.core.tests.compiler.regression;
15
package org.eclipse.jdt.core.tests.compiler.regression;
14
16
Lines 386-394 Link Here
386
		expectedProblemAttributes.put("CodeSnippetMissingMethod", new ProblemAttributes(CategorizedProblem.CAT_INTERNAL));
388
		expectedProblemAttributes.put("CodeSnippetMissingMethod", new ProblemAttributes(CategorizedProblem.CAT_INTERNAL));
387
		expectedProblemAttributes.put("ComparingIdentical", new ProblemAttributes(CategorizedProblem.CAT_POTENTIAL_PROGRAMMING_PROBLEM));
389
		expectedProblemAttributes.put("ComparingIdentical", new ProblemAttributes(CategorizedProblem.CAT_POTENTIAL_PROGRAMMING_PROBLEM));
388
		expectedProblemAttributes.put("ConflictingImport", new ProblemAttributes(CategorizedProblem.CAT_IMPORT));
390
		expectedProblemAttributes.put("ConflictingImport", new ProblemAttributes(CategorizedProblem.CAT_IMPORT));
391
		expectedProblemAttributes.put("ConflictingTypeEmulation", new ProblemAttributes(CategorizedProblem.CAT_BUILDPATH));
389
		expectedProblemAttributes.put("ConstructorVarargsArgumentNeedCast", new ProblemAttributes(CategorizedProblem.CAT_POTENTIAL_PROGRAMMING_PROBLEM));
392
		expectedProblemAttributes.put("ConstructorVarargsArgumentNeedCast", new ProblemAttributes(CategorizedProblem.CAT_POTENTIAL_PROGRAMMING_PROBLEM));
390
		expectedProblemAttributes.put("CorruptedSignature", new ProblemAttributes(CategorizedProblem.CAT_BUILDPATH));
393
		expectedProblemAttributes.put("CorruptedSignature", new ProblemAttributes(CategorizedProblem.CAT_BUILDPATH));
391
		expectedProblemAttributes.put("DeadCode", new ProblemAttributes(CategorizedProblem.CAT_POTENTIAL_PROGRAMMING_PROBLEM));
394
		expectedProblemAttributes.put("DeadCode", new ProblemAttributes(CategorizedProblem.CAT_POTENTIAL_PROGRAMMING_PROBLEM));
395
		expectedProblemAttributes.put("DefiniteNullFromNonNullMethod", new ProblemAttributes(CategorizedProblem.CAT_POTENTIAL_PROGRAMMING_PROBLEM));
396
		expectedProblemAttributes.put("DefiniteNullToNonnullParameter", new ProblemAttributes(CategorizedProblem.CAT_POTENTIAL_PROGRAMMING_PROBLEM));
392
		expectedProblemAttributes.put("DirectInvocationOfAbstractMethod", new ProblemAttributes(CategorizedProblem.CAT_MEMBER));
397
		expectedProblemAttributes.put("DirectInvocationOfAbstractMethod", new ProblemAttributes(CategorizedProblem.CAT_MEMBER));
393
		expectedProblemAttributes.put("DisallowedTargetForAnnotation", new ProblemAttributes(CategorizedProblem.CAT_TYPE));
398
		expectedProblemAttributes.put("DisallowedTargetForAnnotation", new ProblemAttributes(CategorizedProblem.CAT_TYPE));
394
		expectedProblemAttributes.put("DiscouragedReference", new ProblemAttributes(CategorizedProblem.CAT_RESTRICTION));
399
		expectedProblemAttributes.put("DiscouragedReference", new ProblemAttributes(CategorizedProblem.CAT_RESTRICTION));
Lines 491-496 Link Here
491
		expectedProblemAttributes.put("IllegalPrimitiveOrArrayTypeForEnclosingInstance", new ProblemAttributes(CategorizedProblem.CAT_TYPE));
496
		expectedProblemAttributes.put("IllegalPrimitiveOrArrayTypeForEnclosingInstance", new ProblemAttributes(CategorizedProblem.CAT_TYPE));
492
		expectedProblemAttributes.put("IllegalQualifiedEnumConstantLabel", new ProblemAttributes(CategorizedProblem.CAT_MEMBER));
497
		expectedProblemAttributes.put("IllegalQualifiedEnumConstantLabel", new ProblemAttributes(CategorizedProblem.CAT_MEMBER));
493
		expectedProblemAttributes.put("IllegalQualifiedParameterizedTypeAllocation", new ProblemAttributes(CategorizedProblem.CAT_TYPE));
498
		expectedProblemAttributes.put("IllegalQualifiedParameterizedTypeAllocation", new ProblemAttributes(CategorizedProblem.CAT_TYPE));
499
		expectedProblemAttributes.put("IllegalRedefinitionToNullableReturn", new ProblemAttributes(CategorizedProblem.CAT_POTENTIAL_PROGRAMMING_PROBLEM));
500
		expectedProblemAttributes.put("IllegalRedefinitionToNonNullParameter", new ProblemAttributes(CategorizedProblem.CAT_POTENTIAL_PROGRAMMING_PROBLEM));
494
		expectedProblemAttributes.put("IllegalStaticModifierForMemberType", new ProblemAttributes(CategorizedProblem.CAT_TYPE));
501
		expectedProblemAttributes.put("IllegalStaticModifierForMemberType", new ProblemAttributes(CategorizedProblem.CAT_TYPE));
495
		expectedProblemAttributes.put("IllegalTypeVariableSuperReference", new ProblemAttributes(CategorizedProblem.CAT_INTERNAL));
502
		expectedProblemAttributes.put("IllegalTypeVariableSuperReference", new ProblemAttributes(CategorizedProblem.CAT_INTERNAL));
496
		expectedProblemAttributes.put("IllegalUsageOfQualifiedTypeReference", new ProblemAttributes(CategorizedProblem.CAT_SYNTAX));
503
		expectedProblemAttributes.put("IllegalUsageOfQualifiedTypeReference", new ProblemAttributes(CategorizedProblem.CAT_SYNTAX));
Lines 669-674 Link Here
669
		expectedProblemAttributes.put("MissingEnclosingInstance", new ProblemAttributes(CategorizedProblem.CAT_TYPE));
676
		expectedProblemAttributes.put("MissingEnclosingInstance", new ProblemAttributes(CategorizedProblem.CAT_TYPE));
670
		expectedProblemAttributes.put("MissingEnclosingInstanceForConstructorCall", new ProblemAttributes(CategorizedProblem.CAT_TYPE));
677
		expectedProblemAttributes.put("MissingEnclosingInstanceForConstructorCall", new ProblemAttributes(CategorizedProblem.CAT_TYPE));
671
		expectedProblemAttributes.put("MissingEnumConstantCase", new ProblemAttributes(CategorizedProblem.CAT_POTENTIAL_PROGRAMMING_PROBLEM));
678
		expectedProblemAttributes.put("MissingEnumConstantCase", new ProblemAttributes(CategorizedProblem.CAT_POTENTIAL_PROGRAMMING_PROBLEM));
679
		expectedProblemAttributes.put("MissingNullAnnotationType", new ProblemAttributes(CategorizedProblem.CAT_BUILDPATH));
672
		expectedProblemAttributes.put("MissingOverrideAnnotation", new ProblemAttributes(CategorizedProblem.CAT_CODE_STYLE));
680
		expectedProblemAttributes.put("MissingOverrideAnnotation", new ProblemAttributes(CategorizedProblem.CAT_CODE_STYLE));
673
		expectedProblemAttributes.put("MissingOverrideAnnotationForInterfaceMethodImplementation", new ProblemAttributes(CategorizedProblem.CAT_CODE_STYLE));
681
		expectedProblemAttributes.put("MissingOverrideAnnotationForInterfaceMethodImplementation", new ProblemAttributes(CategorizedProblem.CAT_CODE_STYLE));
674
		expectedProblemAttributes.put("MissingReturnType", new ProblemAttributes(CategorizedProblem.CAT_TYPE));
682
		expectedProblemAttributes.put("MissingReturnType", new ProblemAttributes(CategorizedProblem.CAT_TYPE));
Lines 697-702 Link Here
697
		expectedProblemAttributes.put("NonGenericMethod", new ProblemAttributes(CategorizedProblem.CAT_TYPE));
705
		expectedProblemAttributes.put("NonGenericMethod", new ProblemAttributes(CategorizedProblem.CAT_TYPE));
698
		expectedProblemAttributes.put("NonGenericType", new ProblemAttributes(CategorizedProblem.CAT_TYPE));
706
		expectedProblemAttributes.put("NonGenericType", new ProblemAttributes(CategorizedProblem.CAT_TYPE));
699
		expectedProblemAttributes.put("NonNullLocalVariableComparisonYieldsFalse", new ProblemAttributes(CategorizedProblem.CAT_POTENTIAL_PROGRAMMING_PROBLEM));
707
		expectedProblemAttributes.put("NonNullLocalVariableComparisonYieldsFalse", new ProblemAttributes(CategorizedProblem.CAT_POTENTIAL_PROGRAMMING_PROBLEM));
708
		expectedProblemAttributes.put("NonNullReturnInsufficientInfo", new ProblemAttributes(CategorizedProblem.CAT_POTENTIAL_PROGRAMMING_PROBLEM));
709
		expectedProblemAttributes.put("NonNullParameterInsufficientInfo", new ProblemAttributes(CategorizedProblem.CAT_POTENTIAL_PROGRAMMING_PROBLEM));
700
		expectedProblemAttributes.put("NonStaticAccessToStaticField", new ProblemAttributes(CategorizedProblem.CAT_CODE_STYLE));
710
		expectedProblemAttributes.put("NonStaticAccessToStaticField", new ProblemAttributes(CategorizedProblem.CAT_CODE_STYLE));
701
		expectedProblemAttributes.put("NonStaticAccessToStaticMethod", new ProblemAttributes(CategorizedProblem.CAT_CODE_STYLE));
711
		expectedProblemAttributes.put("NonStaticAccessToStaticMethod", new ProblemAttributes(CategorizedProblem.CAT_CODE_STYLE));
702
		expectedProblemAttributes.put("NonStaticContextForEnumMemberType", new ProblemAttributes(CategorizedProblem.CAT_INTERNAL));
712
		expectedProblemAttributes.put("NonStaticContextForEnumMemberType", new ProblemAttributes(CategorizedProblem.CAT_INTERNAL));
Lines 746-751 Link Here
746
		expectedProblemAttributes.put("ParsingErrorUnexpectedEOF", new ProblemAttributes(CategorizedProblem.CAT_SYNTAX));
756
		expectedProblemAttributes.put("ParsingErrorUnexpectedEOF", new ProblemAttributes(CategorizedProblem.CAT_SYNTAX));
747
		expectedProblemAttributes.put("PossibleAccidentalBooleanAssignment", new ProblemAttributes(CategorizedProblem.CAT_POTENTIAL_PROGRAMMING_PROBLEM));
757
		expectedProblemAttributes.put("PossibleAccidentalBooleanAssignment", new ProblemAttributes(CategorizedProblem.CAT_POTENTIAL_PROGRAMMING_PROBLEM));
748
		expectedProblemAttributes.put("PotentialNullLocalVariableReference", new ProblemAttributes(CategorizedProblem.CAT_POTENTIAL_PROGRAMMING_PROBLEM));
758
		expectedProblemAttributes.put("PotentialNullLocalVariableReference", new ProblemAttributes(CategorizedProblem.CAT_POTENTIAL_PROGRAMMING_PROBLEM));
759
		expectedProblemAttributes.put("PotentialNullFromNonNullMethod", new ProblemAttributes(CategorizedProblem.CAT_POTENTIAL_PROGRAMMING_PROBLEM));
760
		expectedProblemAttributes.put("PotentialNullToNonnullParameter", new ProblemAttributes(CategorizedProblem.CAT_POTENTIAL_PROGRAMMING_PROBLEM));
749
		expectedProblemAttributes.put("PublicClassMustMatchFileName", new ProblemAttributes(CategorizedProblem.CAT_TYPE));
761
		expectedProblemAttributes.put("PublicClassMustMatchFileName", new ProblemAttributes(CategorizedProblem.CAT_TYPE));
750
		expectedProblemAttributes.put("RawMemberTypeCannotBeParameterized", new ProblemAttributes(CategorizedProblem.CAT_TYPE));
762
		expectedProblemAttributes.put("RawMemberTypeCannotBeParameterized", new ProblemAttributes(CategorizedProblem.CAT_TYPE));
751
		expectedProblemAttributes.put("RawTypeReference", new ProblemAttributes(CategorizedProblem.CAT_UNCHECKED_RAW));
763
		expectedProblemAttributes.put("RawTypeReference", new ProblemAttributes(CategorizedProblem.CAT_UNCHECKED_RAW));
Lines 1023-1031 Link Here
1023
		expectedProblemAttributes.put("CodeSnippetMissingMethod", SKIP);
1035
		expectedProblemAttributes.put("CodeSnippetMissingMethod", SKIP);
1024
		expectedProblemAttributes.put("ComparingIdentical", new ProblemAttributes(JavaCore.COMPILER_PB_COMPARING_IDENTICAL));
1036
		expectedProblemAttributes.put("ComparingIdentical", new ProblemAttributes(JavaCore.COMPILER_PB_COMPARING_IDENTICAL));
1025
		expectedProblemAttributes.put("ConflictingImport", SKIP);
1037
		expectedProblemAttributes.put("ConflictingImport", SKIP);
1038
		expectedProblemAttributes.put("ConflictingTypeEmulation", SKIP);
1026
		expectedProblemAttributes.put("ConstructorVarargsArgumentNeedCast", new ProblemAttributes(JavaCore.COMPILER_PB_VARARGS_ARGUMENT_NEED_CAST));
1039
		expectedProblemAttributes.put("ConstructorVarargsArgumentNeedCast", new ProblemAttributes(JavaCore.COMPILER_PB_VARARGS_ARGUMENT_NEED_CAST));
1027
		expectedProblemAttributes.put("CorruptedSignature", SKIP);
1040
		expectedProblemAttributes.put("CorruptedSignature", SKIP);
1028
		expectedProblemAttributes.put("DeadCode", new ProblemAttributes(JavaCore.COMPILER_PB_DEAD_CODE));
1041
		expectedProblemAttributes.put("DeadCode", new ProblemAttributes(JavaCore.COMPILER_PB_DEAD_CODE));
1042
		expectedProblemAttributes.put("DefiniteNullFromNonNullMethod", new ProblemAttributes(JavaCore.COMPILER_PB_NULL_CONTRACT_VIOLATION));
1043
		expectedProblemAttributes.put("DefiniteNullToNonnullParameter", new ProblemAttributes(JavaCore.COMPILER_PB_NULL_CONTRACT_VIOLATION));
1029
		expectedProblemAttributes.put("DirectInvocationOfAbstractMethod", SKIP);
1044
		expectedProblemAttributes.put("DirectInvocationOfAbstractMethod", SKIP);
1030
		expectedProblemAttributes.put("DisallowedTargetForAnnotation", SKIP);
1045
		expectedProblemAttributes.put("DisallowedTargetForAnnotation", SKIP);
1031
		expectedProblemAttributes.put("DiscouragedReference", new ProblemAttributes(JavaCore.COMPILER_PB_DISCOURAGED_REFERENCE));
1046
		expectedProblemAttributes.put("DiscouragedReference", new ProblemAttributes(JavaCore.COMPILER_PB_DISCOURAGED_REFERENCE));
Lines 1128-1133 Link Here
1128
		expectedProblemAttributes.put("IllegalPrimitiveOrArrayTypeForEnclosingInstance", SKIP);
1143
		expectedProblemAttributes.put("IllegalPrimitiveOrArrayTypeForEnclosingInstance", SKIP);
1129
		expectedProblemAttributes.put("IllegalQualifiedEnumConstantLabel", SKIP);
1144
		expectedProblemAttributes.put("IllegalQualifiedEnumConstantLabel", SKIP);
1130
		expectedProblemAttributes.put("IllegalQualifiedParameterizedTypeAllocation", SKIP);
1145
		expectedProblemAttributes.put("IllegalQualifiedParameterizedTypeAllocation", SKIP);
1146
		expectedProblemAttributes.put("IllegalRedefinitionToNullableReturn", new ProblemAttributes(JavaCore.COMPILER_PB_NULL_CONTRACT_VIOLATION));
1147
		expectedProblemAttributes.put("IllegalRedefinitionToNonNullParameter", new ProblemAttributes(JavaCore.COMPILER_PB_NULL_CONTRACT_VIOLATION));
1131
		expectedProblemAttributes.put("IllegalStaticModifierForMemberType", SKIP);
1148
		expectedProblemAttributes.put("IllegalStaticModifierForMemberType", SKIP);
1132
		expectedProblemAttributes.put("IllegalTypeVariableSuperReference", SKIP);
1149
		expectedProblemAttributes.put("IllegalTypeVariableSuperReference", SKIP);
1133
		expectedProblemAttributes.put("IllegalUsageOfQualifiedTypeReference", SKIP);
1150
		expectedProblemAttributes.put("IllegalUsageOfQualifiedTypeReference", SKIP);
Lines 1306-1311 Link Here
1306
		expectedProblemAttributes.put("MissingEnclosingInstance", SKIP);
1323
		expectedProblemAttributes.put("MissingEnclosingInstance", SKIP);
1307
		expectedProblemAttributes.put("MissingEnclosingInstanceForConstructorCall", SKIP);
1324
		expectedProblemAttributes.put("MissingEnclosingInstanceForConstructorCall", SKIP);
1308
		expectedProblemAttributes.put("MissingEnumConstantCase", new ProblemAttributes(JavaCore.COMPILER_PB_INCOMPLETE_ENUM_SWITCH));
1325
		expectedProblemAttributes.put("MissingEnumConstantCase", new ProblemAttributes(JavaCore.COMPILER_PB_INCOMPLETE_ENUM_SWITCH));
1326
		expectedProblemAttributes.put("MissingNullAnnotationType", SKIP);
1309
		expectedProblemAttributes.put("MissingOverrideAnnotation", new ProblemAttributes(JavaCore.COMPILER_PB_MISSING_OVERRIDE_ANNOTATION));
1327
		expectedProblemAttributes.put("MissingOverrideAnnotation", new ProblemAttributes(JavaCore.COMPILER_PB_MISSING_OVERRIDE_ANNOTATION));
1310
		expectedProblemAttributes.put("MissingOverrideAnnotationForInterfaceMethodImplementation", SKIP);
1328
		expectedProblemAttributes.put("MissingOverrideAnnotationForInterfaceMethodImplementation", SKIP);
1311
		expectedProblemAttributes.put("MissingReturnType", SKIP);
1329
		expectedProblemAttributes.put("MissingReturnType", SKIP);
Lines 1334-1339 Link Here
1334
		expectedProblemAttributes.put("NonGenericMethod", SKIP);
1352
		expectedProblemAttributes.put("NonGenericMethod", SKIP);
1335
		expectedProblemAttributes.put("NonGenericType", SKIP);
1353
		expectedProblemAttributes.put("NonGenericType", SKIP);
1336
		expectedProblemAttributes.put("NonNullLocalVariableComparisonYieldsFalse", new ProblemAttributes(JavaCore.COMPILER_PB_REDUNDANT_NULL_CHECK));
1354
		expectedProblemAttributes.put("NonNullLocalVariableComparisonYieldsFalse", new ProblemAttributes(JavaCore.COMPILER_PB_REDUNDANT_NULL_CHECK));
1355
		expectedProblemAttributes.put("NonNullReturnInsufficientInfo", new ProblemAttributes(JavaCore.COMPILER_PB_NULL_CONTRACT_INSUFFICIENT_INFO));
1356
		expectedProblemAttributes.put("NonNullParameterInsufficientInfo", new ProblemAttributes(JavaCore.COMPILER_PB_NULL_CONTRACT_INSUFFICIENT_INFO));
1337
		expectedProblemAttributes.put("NonStaticAccessToStaticField", new ProblemAttributes(JavaCore.COMPILER_PB_STATIC_ACCESS_RECEIVER));
1357
		expectedProblemAttributes.put("NonStaticAccessToStaticField", new ProblemAttributes(JavaCore.COMPILER_PB_STATIC_ACCESS_RECEIVER));
1338
		expectedProblemAttributes.put("NonStaticAccessToStaticMethod", new ProblemAttributes(JavaCore.COMPILER_PB_STATIC_ACCESS_RECEIVER));
1358
		expectedProblemAttributes.put("NonStaticAccessToStaticMethod", new ProblemAttributes(JavaCore.COMPILER_PB_STATIC_ACCESS_RECEIVER));
1339
		expectedProblemAttributes.put("NonStaticContextForEnumMemberType", SKIP);
1359
		expectedProblemAttributes.put("NonStaticContextForEnumMemberType", SKIP);
Lines 1383-1388 Link Here
1383
		expectedProblemAttributes.put("ParsingErrorUnexpectedEOF", SKIP);
1403
		expectedProblemAttributes.put("ParsingErrorUnexpectedEOF", SKIP);
1384
		expectedProblemAttributes.put("PossibleAccidentalBooleanAssignment", new ProblemAttributes(JavaCore.COMPILER_PB_POSSIBLE_ACCIDENTAL_BOOLEAN_ASSIGNMENT));
1404
		expectedProblemAttributes.put("PossibleAccidentalBooleanAssignment", new ProblemAttributes(JavaCore.COMPILER_PB_POSSIBLE_ACCIDENTAL_BOOLEAN_ASSIGNMENT));
1385
		expectedProblemAttributes.put("PotentialNullLocalVariableReference", new ProblemAttributes(JavaCore.COMPILER_PB_POTENTIAL_NULL_REFERENCE));
1405
		expectedProblemAttributes.put("PotentialNullLocalVariableReference", new ProblemAttributes(JavaCore.COMPILER_PB_POTENTIAL_NULL_REFERENCE));
1406
		expectedProblemAttributes.put("PotentialNullFromNonNullMethod", new ProblemAttributes(JavaCore.COMPILER_PB_POTENTIAL_NULL_CONTRACT_VIOLATION));
1407
		expectedProblemAttributes.put("PotentialNullToNonnullParameter", new ProblemAttributes(JavaCore.COMPILER_PB_POTENTIAL_NULL_CONTRACT_VIOLATION));
1386
		expectedProblemAttributes.put("PublicClassMustMatchFileName", SKIP);
1408
		expectedProblemAttributes.put("PublicClassMustMatchFileName", SKIP);
1387
		expectedProblemAttributes.put("RawMemberTypeCannotBeParameterized", SKIP);
1409
		expectedProblemAttributes.put("RawMemberTypeCannotBeParameterized", SKIP);
1388
		expectedProblemAttributes.put("RawTypeReference", new ProblemAttributes(JavaCore.COMPILER_PB_RAW_TYPE_REFERENCE));
1410
		expectedProblemAttributes.put("RawTypeReference", new ProblemAttributes(JavaCore.COMPILER_PB_RAW_TYPE_REFERENCE));
(-)src/org/eclipse/jdt/core/tests/compiler/regression/NullAnnotationTest.java (+842 lines)
Added Link Here
1
/*******************************************************************************
2
 * Copyright (c) 2010, 2011 GK Software AG 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
 *     Stephan Herrmann - initial API and implementation 
10
 *******************************************************************************/
11
package org.eclipse.jdt.core.tests.compiler.regression;
12
13
import java.util.Map;
14
15
import junit.framework.Test;
16
17
import org.eclipse.jdt.internal.compiler.impl.CompilerOptions;
18
19
public class NullAnnotationTest extends AbstractComparableTest {
20
21
public NullAnnotationTest(String name) {
22
	super(name);
23
}
24
25
// Static initializer to specify tests subset using TESTS_* static variables
26
// All specified tests which do not belong to the class are skipped...
27
static {
28
//		TESTS_NAMES = new String[] { "test_parameter_contract_inheritance" };
29
//		TESTS_NUMBERS = new int[] { 561 };
30
//		TESTS_RANGE = new int[] { 1, 2049 };
31
}
32
33
public static Test suite() {
34
	return buildComparableTestSuite(testClass());
35
}
36
37
public static Class testClass() {
38
	return NullAnnotationTest.class;
39
}
40
41
// Conditionally augment problem detection settings
42
static boolean setNullRelatedOptions = true;
43
protected Map getCompilerOptions() {
44
    Map defaultOptions = super.getCompilerOptions();
45
    if (setNullRelatedOptions) {
46
	    defaultOptions.put(CompilerOptions.OPTION_ReportNullReference, CompilerOptions.ERROR);
47
	    defaultOptions.put(CompilerOptions.OPTION_ReportPotentialNullReference, CompilerOptions.ERROR);
48
	    defaultOptions.put(CompilerOptions.OPTION_ReportRedundantNullCheck, CompilerOptions.ERROR);
49
		defaultOptions.put(CompilerOptions.OPTION_ReportRawTypeReference, CompilerOptions.IGNORE);
50
		defaultOptions.put(CompilerOptions.OPTION_IncludeNullInfoFromAsserts, CompilerOptions.ENABLED);
51
		
52
		// leave new options at these defaults:
53
//		defaultOptions.put(CompilerOptions.OPTION_ReportNullContractViolation, CompilerOptions.ERROR);
54
//		defaultOptions.put(CompilerOptions.OPTION_ReportPotentialNullContractViolation, CompilerOptions.ERROR);
55
//		defaultOptions.put(CompilerOptions.OPTION_ReportNullContractInsufficientInfo, CompilerOptions.WARNING);
56
		
57
		defaultOptions.put(CompilerOptions.OPTION_NullableAnnotationName, "org.eclipse.jdt.annotation.Nullable");
58
		defaultOptions.put(CompilerOptions.OPTION_NonNullAnnotationName, "org.eclipse.jdt.annotation.NonNull");
59
		defaultOptions.put(CompilerOptions.OPTION_EmulateNullAnnotationTypes, CompilerOptions.ENABLED);
60
		defaultOptions.put(CompilerOptions.OPTION_DefaultImportNullAnnotationTypes, CompilerOptions.ENABLED);
61
    }
62
    return defaultOptions;
63
}
64
// a nullable argument is dereferenced without a check
65
public void test_nullable_paramter_001() {
66
	runNegativeTest(
67
		new String[] {
68
			"X.java",
69
			  "public class X {\n" +
70
			  "    void foo(@Nullable Object o) {\n" +
71
			  "        System.out.print(o.toString());\n" +
72
			  "    }\n" +
73
			  "}\n"},
74
	    "----------\n" + 
75
		"1. ERROR in X.java (at line 3)\n" + 
76
		"	System.out.print(o.toString());\n" + 
77
		"	                 ^\n" + 
78
		"Potential null pointer access: The variable o may be null at this location\n" + 
79
		"----------\n",
80
	    JavacTestOptions.Excuse.EclipseWarningConfiguredAsError);
81
}
82
83
// a null value is passed to a nullable argument
84
public void test_nullable_paramter_002() {
85
	runConformTest(
86
		new String[] {
87
			"X.java",
88
			  "public class X {\n" +
89
			  "    void foo(@Nullable Object o) {\n" +
90
			  "        // nop\n" +
91
			  "    }\n" +
92
			  "    void bar() {\n" +
93
			  "        foo(null);\n" +
94
			  "    }\n" +
95
			  "}\n"},
96
	    "");
97
}
98
99
// a non-null argument is checked for null
100
public void test_nonnull_parameter_001() {
101
	runNegativeTest(
102
		new String[] {
103
			"X.java",
104
			  "public class X {\n" +
105
			  "    void foo(@NonNull Object o) {\n" +
106
			  "        if (o != null)\n" +
107
			  "              System.out.print(o.toString());\n" +
108
			  "    }\n" +
109
			  "}\n"},
110
	    "----------\n" + 
111
		"1. ERROR in X.java (at line 3)\n" + 
112
		"	if (o != null)\n" + 
113
		"	    ^\n" + 
114
		"Redundant null check: The variable o cannot be null at this location\n" + 
115
		"----------\n",
116
	    JavacTestOptions.Excuse.EclipseWarningConfiguredAsError);
117
}
118
// a non-null argument is dereferenced without a check
119
public void test_nonnull_parameter_002() {
120
	runConformTest(
121
		new String[] {
122
			"X.java",
123
			  "public class X {\n" +
124
			  "    void foo(@NonNull Object o) {\n" +
125
			  "        System.out.print(o.toString());\n" +
126
			  "    }\n" +
127
			  "    public static void main(String... args) {\n" +
128
			  "        new X().foo(\"OK\");\n" +
129
			  "    }\n" +
130
			  "}\n"},
131
	    "OK");
132
}
133
// passing null to nonnull parameter 
134
public void test_nonnull_parameter_003() {
135
	runNegativeTest(
136
		new String[] {
137
			"X.java",
138
			  "public class X {\n" +
139
			  "    void foo(@NonNull Object o) {\n" +
140
			  "        System.out.print(o.toString());\n" +
141
			  "    }\n" +
142
			  "    void bar() {\n" +
143
			  "        foo(null);\n" +
144
			  "    }\n" +
145
			  "}\n"},
146
		"----------\n" + 
147
		"1. ERROR in X.java (at line 6)\n" + 
148
		"	foo(null);\n" + 
149
		"	    ^^^^\n" + 
150
		"Null contract violation: passing null to a parameter declared as @NonNull.\n" + 
151
		"----------\n",
152
	    JavacTestOptions.Excuse.EclipseWarningConfiguredAsError);
153
}
154
// passing potential null to nonnull parameter - target method is consumed from .class
155
public void test_nonnull_parameter_004() {
156
	runConformTest(
157
			new String[] {
158
				"Lib.java",
159
				"public class Lib {\n" +
160
				"    void setObject(@NonNull Object o) { }\n" +
161
				"}\n"
162
			});
163
	runNegativeTest(
164
		false /* flush output directory */,
165
		new String[] {
166
			"X.java",
167
			  "public class X {\n" +
168
			  "    void bar(Lib l, boolean b) {\n" +
169
			  "        Object o = null;\n" +
170
			  "        if (b) o = new Object();\n" +
171
			  "        l.setObject(o);\n" +
172
			  "    }\n" +
173
			  "}\n"},
174
		null /* no class libraries */,
175
		null /* no custom options */,
176
		"----------\n" + 
177
		"1. ERROR in X.java (at line 5)\n" + 
178
		"	l.setObject(o);\n" + 
179
		"	            ^\n" + 
180
		"Null contract violation: potentially passing null to a parameter declared as @NonNull.\n" + 
181
		"----------\n",
182
		"",/* expected output */
183
		"",/* expected error */
184
	    JavacTestOptions.Excuse.EclipseWarningConfiguredAsError);
185
}
186
// passing unknown value to nonnull parameter  - target method is consumed from .class
187
public void test_nonnull_parameter_005() {
188
	runConformTest(
189
			new String[] {
190
				"Lib.java",
191
				"public class Lib {\n" +
192
				"    void setObject(@NonNull Object o) { }\n" +
193
				"}\n"
194
			});
195
	runConformTest(
196
		false /* flush output directory */,
197
		new String[] {
198
			"X.java",
199
			  "public class X {\n" +
200
			  "    void bar(Lib l, Object o) {\n" +
201
			  "        l.setObject(o);\n" +
202
			  "    }\n" +
203
			  "}\n"},
204
		null /* no class libraries */,
205
		null /* no custom options */,
206
		"----------\n" + 
207
		"1. WARNING in X.java (at line 3)\n" + 
208
		"	l.setObject(o);\n" + 
209
		"	            ^\n" + 
210
		"Potential null contract violation: insufficient nullness information regarding a value that is passed to a parameter declared as @NonNull.\n" + 
211
		"----------\n",
212
		"",/* expected output */
213
		"",/* expected error */
214
	    JavacTestOptions.Excuse.EclipseWarningConfiguredAsError);
215
}
216
// a method tries to tighten the null contract, super declares parameter o as @Nullable
217
// other parameters: s is redefined from not constrained to @Nullable which is OK
218
//                   third is redefined from not constrained to @NonNull which is bad, too
219
public void test_parameter_contract_inheritance_001() {
220
	runConformTest(
221
		new String[] {
222
			"Lib.java",
223
			"public class Lib {\n" +
224
			"    void foo(String s, @Nullable Object o, Object third) { }\n" +
225
			"}\n"
226
		});
227
	runNegativeTest(
228
		false /* flush output directory */,
229
		new String[] {
230
			"X.java",
231
			"public class X extends Lib {\n" +
232
			"    @Override\n" +
233
			"    void foo(@Nullable String s, @NonNull Object o, @NonNull Object third) { System.out.print(o.toString()); }\n" +
234
			"}\n"
235
		},
236
		// compiler options
237
		null /* no class libraries */,
238
		null /* no custom options */,
239
		"----------\n" + 
240
		"1. ERROR in X.java (at line 3)\n" + 
241
		"	void foo(@Nullable String s, @NonNull Object o, @NonNull Object third) { System.out.print(o.toString()); }\n" + 
242
		"	                                             ^\n" + 
243
		"Cannot tighten null contract for parameter o, inherited method from Lib declares this parameter as @Nullable.\n" + 
244
		"----------\n" + 
245
		"2. ERROR in X.java (at line 3)\n" + 
246
		"	void foo(@Nullable String s, @NonNull Object o, @NonNull Object third) { System.out.print(o.toString()); }\n" + 
247
		"	                                                                ^^^^^\n" + 
248
		"Cannot tighten null contract for parameter third, inherited method from Lib does not constrain this parameter.\n" + 
249
		"----------\n",
250
		JavacTestOptions.Excuse.EclipseWarningConfiguredAsError);
251
}
252
// a method body fails to handle the inherited null contract, super declares parameter as @Nullable
253
public void test_parameter_contract_inheritance_002() {
254
	runConformTest(
255
		new String[] {
256
			"Lib.java",
257
			"public class Lib {\n" +
258
			"    void foo(@Nullable Object o) { }\n" +
259
			"}\n"
260
		});
261
	runNegativeTest(
262
		false /* flush output directory */,
263
		new String[] {
264
			"X.java",
265
			"public class X extends Lib {\n" +
266
			"    @Override\n" +
267
			"    void foo(Object o) {\n" +
268
			"        System.out.print(o.toString());\n" +
269
			"    }\n" +
270
			"}\n"
271
		},
272
		// compiler options
273
		null /* no class libraries */,
274
		null /* no custom options */,
275
		"----------\n" + 
276
		"1. ERROR in X.java (at line 4)\n" + 
277
		"	System.out.print(o.toString());\n" + 
278
		"	                 ^\n" + 
279
		"Potential null pointer access: The variable o may be null at this location\n" + 
280
		"----------\n",
281
		JavacTestOptions.Excuse.EclipseWarningConfiguredAsError);
282
}
283
// a method relaxes the parameter null contract, super declares parameter o as @NonNull
284
// other (first) parameter just repeats the inherited @NonNull
285
public void test_parameter_contract_inheritance_003() {
286
	runConformTest(
287
		new String[] {
288
			"Lib.java",
289
			"public class Lib {\n" +
290
			"    void foo(@NonNull String s, @NonNull Object o) { }\n" +
291
			"}\n",
292
			"X.java",
293
			"public class X extends Lib {\n" +
294
			"    @Override\n" +
295
			"    void foo(@NonNull String s, @Nullable Object o) { ; }\n" +
296
			"    void bar() { foo(\"OK\", null); }\n" +
297
			"}\n"
298
		},
299
		"");
300
}
301
// a method adds a @NonNull annotation, super has no null annotation
302
// changing other from unconstrained to @Nullable is OK
303
public void test_parameter_contract_inheritance_004() {
304
	runConformTest(
305
		new String[] {
306
			"Lib.java",
307
			"public class Lib {\n" +
308
			"    void foo(Object o, Object other) { }\n" +
309
			"}\n"
310
		});
311
	runNegativeTest(
312
		false /* flush output directory */,
313
		new String[] {
314
			"X.java",
315
			"public class X extends Lib {\n" +
316
			"    @Override\n" +
317
			"    void foo(@NonNull Object o, @Nullable Object other) { System.out.print(o.toString()); }\n" +
318
			"}\n"
319
		},
320
		// compiler options
321
		null /* no class libraries */,
322
		null /* no custom options */,
323
		"----------\n" + 
324
		"1. ERROR in X.java (at line 3)\n" + 
325
		"	void foo(@NonNull Object o, @Nullable Object other) { System.out.print(o.toString()); }\n" + 
326
		"	                         ^\n" + 
327
		"Cannot tighten null contract for parameter o, inherited method from Lib does not constrain this parameter.\n" + 
328
		"----------\n",
329
		JavacTestOptions.Excuse.EclipseWarningConfiguredAsError);
330
}
331
// a method tries to relax the null contract, super declares @NonNull return
332
public void test_parameter_contract_inheritance_005() {
333
	runConformTest(
334
		new String[] {
335
			"Lib.java",
336
			"public class Lib {\n" +
337
			"    @NonNull Object getObject() { return new Object(); }\n" +
338
			"}\n"
339
		});
340
	runNegativeTest(
341
		false /* flush output directory */,
342
		new String[] {
343
			"X.java",
344
			"public class X extends Lib {\n" +
345
			"    @Override\n" +
346
			"    @Nullable Object getObject() { return null; }\n" +
347
			"}\n"
348
		},
349
		// compiler options
350
		null /* no class libraries */,
351
		null /* no custom options */,
352
		"----------\n" + 
353
		"1. ERROR in X.java (at line 3)\n" + 
354
		"	@Nullable Object getObject() { return null; }\n" + 
355
		"	                 ^^^^^^^^^^^\n" + 
356
		"Cannot relax null contract for method return, inherited method from Lib is declared as @NonNull.\n" + 
357
		"----------\n",
358
		JavacTestOptions.Excuse.EclipseWarningConfiguredAsError);
359
}
360
// super has no contraint for return, sub method confirms the null contract as @Nullable 
361
public void test_parameter_contract_inheritance_006() {
362
	runConformTest(
363
		new String[] {
364
			"Lib.java",
365
			"public class Lib {\n" +
366
			"    Object getObject() { return null; }\n" +
367
			"}\n"
368
		});
369
	runConformTest(
370
		new String[] {
371
			"X.java",
372
			"public class X extends Lib {\n" +
373
			"    @Override\n" +
374
			"    @Nullable Object getObject() { return null; }\n" +
375
			"}\n"
376
		},
377
		"",
378
		null/*classLibs*/,
379
		false /* flush output directory */,
380
		null/*vmArguments*/,
381
		null/*customOptions*/,
382
		null/*compilerRequestor*/);
383
}
384
// a method body violates the inherited null contract, super declares @NonNull return
385
public void test_parameter_contract_inheritance_007() {
386
	runConformTest(
387
		new String[] {
388
			"Lib.java",
389
			"public class Lib {\n" +
390
			"    @NonNull Object getObject() { return new Object(); }\n" +
391
			"}\n"
392
		});
393
	runNegativeTest(
394
		false /* flush output directory */,
395
		new String[] {
396
			"X.java",
397
			"public class X extends Lib {\n" +
398
			"    @Override\n" +
399
			"    Object getObject() { return null; }\n" +
400
			"}\n"
401
		},
402
		// compiler options
403
		null /* no class libraries */,
404
		null /* no custom options */,
405
		"----------\n" + 
406
		"1. ERROR in X.java (at line 3)\n" + 
407
		"	Object getObject() { return null; }\n" + 
408
		"	                     ^^^^^^^^^^^^\n" + 
409
		"Null contract violation: returning null from a method declared as @NonNull.\n" + 
410
		"----------\n",
411
		JavacTestOptions.Excuse.EclipseWarningConfiguredAsError);
412
}
413
// a nullable return value is dereferenced without a check
414
public void test_nullable_return_001() {
415
	runNegativeTest(
416
		new String[] {
417
			"X.java",
418
			"public class X {\n" +
419
			"    @Nullable Object getObject() { return null; }\n" +
420
			"    void foo() {\n" +
421
			"        Object o = getObject();\n" +
422
			"        System.out.print(o.toString());\n" +
423
			"    }\n" +
424
			"}\n"
425
		},
426
		"----------\n" + 
427
		"1. ERROR in X.java (at line 5)\n" + 
428
		"	System.out.print(o.toString());\n" + 
429
		"	                 ^\n" + 
430
		"Potential null pointer access: The variable o may be null at this location\n" + 
431
		"----------\n",
432
		JavacTestOptions.Excuse.EclipseWarningConfiguredAsError);
433
}
434
// a nullable return value is dereferenced without a check, method is read from .class file
435
public void test_nullable_return_002() {
436
	runConformTest(
437
		new String[] {
438
			"Lib.java",
439
			"public class Lib {\n" +
440
			"    @Nullable Object getObject() { return null; }\n" +
441
			"}\n"
442
		});
443
	runNegativeTest(
444
		false /* flush output directory */,
445
		new String[] {
446
			"X.java",
447
			"public class X {\n" +
448
			"    void foo(Lib l) {\n" +
449
			"        Object o = l.getObject();\n" +
450
			"        System.out.print(o.toString());\n" +
451
			"    }\n" +
452
			"}\n"
453
		},
454
		// compiler options
455
		null /* no class libraries */,
456
		null /* no custom options */,
457
		"----------\n" + 
458
		"1. ERROR in X.java (at line 4)\n" + 
459
		"	System.out.print(o.toString());\n" + 
460
		"	                 ^\n" + 
461
		"Potential null pointer access: The variable o may be null at this location\n" + 
462
		"----------\n",
463
		JavacTestOptions.Excuse.EclipseWarningConfiguredAsError);
464
}
465
// a non-null return value is checked for null, method is read from .class file
466
public void test_nonnull_return_001() {
467
	runConformTest(
468
		new String[] {
469
			"Lib.java",
470
			"public class Lib {\n" +
471
			"    @NonNull Object getObject() { return new Object(); }\n" +
472
			"}\n"
473
		});
474
	runNegativeTest(
475
		false /* flush output directory */,
476
		new String[] {
477
			"X.java",
478
			"public class X {\n" +
479
			"    void foo(Lib l) {\n" +
480
			"        Object o = l.getObject();\n" +
481
			"        if (o != null)\n" +
482
			"            System.out.print(o.toString());\n" +
483
			"    }\n" +
484
			"}\n"
485
		},
486
		// compiler options
487
		null /* no class libraries */,
488
		null /* no custom options */,
489
		"----------\n" + 
490
		"1. ERROR in X.java (at line 4)\n" + 
491
		"	if (o != null)\n" + 
492
		"	    ^\n" + 
493
		"Redundant null check: The variable o cannot be null at this location\n" + 
494
		"----------\n",
495
		JavacTestOptions.Excuse.EclipseWarningConfiguredAsError);
496
}
497
// a non-null method returns null
498
public void test_nonnull_return_003() {
499
	runNegativeTest(
500
		new String[] {
501
			"X.java",
502
			"public class X {\n" +
503
			"    @NonNull Object getObject(boolean b) {\n" +
504
			"        if (b)\n" +
505
			"            return null;\n" + // definite contract violation despite enclosing "if"
506
			"        return new Object();\n" +
507
			"    }\n" +
508
			"}\n"
509
		},
510
		"----------\n" + 
511
		"1. ERROR in X.java (at line 4)\n" + 
512
		"	return null;\n" + 
513
		"	^^^^^^^^^^^^\n" + 
514
		"Null contract violation: returning null from a method declared as @NonNull.\n" + 
515
		"----------\n",
516
		JavacTestOptions.Excuse.EclipseWarningConfiguredAsError);
517
}
518
// a non-null method potentially returns null
519
public void test_nonnull_return_004() {
520
	runNegativeTest(
521
		new String[] {
522
			"X.java",
523
			"public class X {\n" +
524
			"    @NonNull Object getObject(@Nullable Object o) {\n" +
525
			"        return o;\n" + // 'o' is only potentially null
526
			"    }\n" +
527
			"}\n"
528
		},
529
		"----------\n" + 
530
		"1. ERROR in X.java (at line 3)\n" + 
531
		"	return o;\n" + 
532
		"	^^^^^^^^^\n" + 
533
		"Null contract violation: return value can be null but method is declared as @NonNull.\n" + 
534
		"----------\n");
535
}
536
// a non-null method returns its non-null argument
537
public void test_nonnull_return_005() {
538
	Map customOptions = getCompilerOptions();
539
	customOptions.put(CompilerOptions.OPTION_ReportNullReference, CompilerOptions.ERROR);
540
	runConformTest(
541
		new String[] {
542
			"X.java",
543
			"public class X {\n" +
544
			"    @NonNull Object getObject(@NonNull Object o) {\n" +
545
			"        return o;\n" +
546
			"    }\n" +
547
			"}\n"
548
		},
549
		"",
550
		null/*classLibs*/,
551
		true/*shouldFlushOutputDirectory*/,
552
		null/*vmArguments*/,
553
		customOptions,
554
		null/*compilerRequestor*/);
555
}
556
//a non-null method has insufficient nullness info for its return value
557
public void test_nonnull_return_006() {
558
	runNegativeTest(
559
		new String[] {
560
			"X.java",
561
			"public class X {\n" +
562
			"    @NonNull Object getObject(Object o) {\n" +
563
			"        return o;\n" +
564
			"    }\n" +
565
			"}\n"
566
		},
567
		"----------\n" + 
568
		"1. WARNING in X.java (at line 3)\n" + 
569
		"	return o;\n" + 
570
		"	^^^^^^^^^\n" + 
571
		"Potential null contract violation: insufficient nullness information regarding return value while the method is declared as @NonNull.\n" + 
572
		"----------\n");
573
}
574
// mixed use of fully qualified name / explicit import
575
public void test_annotation_import_001() {
576
	Map customOptions = getCompilerOptions();
577
	customOptions.put(CompilerOptions.OPTION_ReportNullReference, CompilerOptions.ERROR);
578
	customOptions.put(CompilerOptions.OPTION_NullableAnnotationName, "org.foo.Nullable");
579
	customOptions.put(CompilerOptions.OPTION_NonNullAnnotationName, "org.foo.NonNull");
580
	customOptions.put(CompilerOptions.OPTION_DefaultImportNullAnnotationTypes, CompilerOptions.DISABLED);
581
	runConformTest(
582
		new String[] {
583
			"Lib.java",
584
			"public class Lib {\n" +
585
			"    @org.foo.NonNull Object getObject() { return new Object(); }\n" + 	// FQN
586
			"}\n",
587
			"X.java",
588
			"import org.foo.NonNull;\n" +											// explicit import
589
			"public class X {\n" +
590
			"    @NonNull Object getObject(@NonNull Lib l) {\n" +
591
			"        return l.getObject();\n" +
592
			"    }\n" +
593
			"}\n"
594
		},
595
		"",
596
		null/*classLibs*/,
597
		true/*shouldFlushOutputDirectory*/,
598
		null/*vmArguments*/,
599
		customOptions,
600
		null/*compilerRequestor*/);
601
}
602
603
// use of explicit imports throughout
604
public void test_annotation_import_002() {
605
	Map customOptions = getCompilerOptions();
606
	customOptions.put(CompilerOptions.OPTION_ReportNullReference, CompilerOptions.ERROR);
607
	customOptions.put(CompilerOptions.OPTION_NullableAnnotationName, "org.foo.Nullable");
608
	customOptions.put(CompilerOptions.OPTION_NonNullAnnotationName, "org.foo.NonNull");
609
	customOptions.put(CompilerOptions.OPTION_DefaultImportNullAnnotationTypes, CompilerOptions.DISABLED);
610
	runConformTest(
611
		new String[] {
612
			"Lib.java",
613
			"import org.foo.NonNull;\n" +
614
			"public class Lib {\n" +
615
			"    @NonNull Object getObject() { return new Object(); }\n" +
616
			"}\n",
617
			"X.java",
618
			"import org.foo.NonNull;\n" +
619
			"public class X {\n" +
620
			"    @NonNull Object getObject(@org.foo.Nullable String dummy, @NonNull Lib l) {\n" +
621
			"        Object o = l.getObject();" +
622
			"        return o;\n" +
623
			"    }\n" +
624
			"}\n"
625
		},
626
		"",
627
		null/*classLibs*/,
628
		true/*shouldFlushOutputDirectory*/,
629
		null/*vmArguments*/,
630
		customOptions,
631
		null/*compilerRequestor*/);
632
}
633
// default import plus explicit ones
634
public void test_annotation_import_003() {
635
	Map customOptions = getCompilerOptions();
636
	customOptions.put(CompilerOptions.OPTION_ReportNullReference, CompilerOptions.ERROR);
637
	customOptions.put(CompilerOptions.OPTION_NullableAnnotationName, "org.foo.Nullable");
638
	customOptions.put(CompilerOptions.OPTION_NonNullAnnotationName, "org.foo.NonNull");
639
	customOptions.put(CompilerOptions.OPTION_DefaultImportNullAnnotationTypes, CompilerOptions.ENABLED);
640
	runConformTest(
641
		new String[] {
642
			"libpack/Lib.java",
643
			"package libpack;\n" +
644
			"public class Lib {\n" +
645
			"    public @NonNull Object getObject() { return new Object(); }\n" +
646
			"}\n",
647
			"X.java",
648
			"import libpack.Lib;\n" +
649
			"public class X {\n" +
650
			"    @NonNull Object getObject(@NonNull Lib l) {\n" +
651
			"        return l.getObject();\n" +
652
			"    }\n" +
653
			"}\n"
654
		},
655
		"",
656
		null/*classLibs*/,
657
		true/*shouldFlushOutputDirectory*/,
658
		null/*vmArguments*/,
659
		customOptions,
660
		null/*compilerRequestor*/);
661
}
662
// default import but unspecified annotation names
663
public void test_annotation_import_004() {
664
	Map customOptions = getCompilerOptions();
665
	customOptions.put(CompilerOptions.OPTION_ReportNullReference, CompilerOptions.ERROR);
666
	customOptions.put(CompilerOptions.OPTION_NullableAnnotationName, null);
667
	customOptions.put(CompilerOptions.OPTION_NonNullAnnotationName, null);
668
	customOptions.put(CompilerOptions.OPTION_DefaultImportNullAnnotationTypes, CompilerOptions.ENABLED);
669
	runConformTest(
670
		new String[] {
671
			"libpack/Lib.java",
672
			"package libpack;\n" +
673
			"public class Lib {\n" +
674
			"    public @NonNull Object getObject() { return new Object(); }\n" +
675
			"}\n",
676
			"X.java",
677
			"import libpack.Lib;\n" +
678
			"public class X {\n" +
679
			"    @NonNull Object getObject(@NonNull Lib l) {\n" +
680
			"        return l.getObject();\n" +
681
			"    }\n" +
682
			"}\n"
683
		},
684
		"",
685
		null/*classLibs*/,
686
		true/*shouldFlushOutputDirectory*/,
687
		null/*vmArguments*/,
688
		customOptions,
689
		null/*compilerRequestor*/);
690
}
691
// default import of existing annotation types
692
public void test_annotation_import_005() {
693
	Map customOptions = getCompilerOptions();
694
	customOptions.put(CompilerOptions.OPTION_ReportNullReference, CompilerOptions.ERROR);
695
	customOptions.put(CompilerOptions.OPTION_ReportNullContractInsufficientInfo, CompilerOptions.ERROR);
696
	customOptions.put(CompilerOptions.OPTION_NullableAnnotationName, "org.foo.MayBeNull");
697
	customOptions.put(CompilerOptions.OPTION_NonNullAnnotationName, "org.foo.MustNotBeNull");
698
	customOptions.put(CompilerOptions.OPTION_DefaultImportNullAnnotationTypes, CompilerOptions.ENABLED);
699
	customOptions.put(CompilerOptions.OPTION_EmulateNullAnnotationTypes, CompilerOptions.DISABLED);
700
	runNegativeTest(
701
		true/*shouldFlushOutputDirectory*/,
702
		new String[] {
703
			"Lib.java",
704
			"public class Lib {\n" +
705
			"    Object getObject() { return new Object(); }\n" +
706
			"}\n",
707
			"X.java",
708
			"public class X {\n" +
709
			"    @MustNotBeNull Object getObject(@MustNotBeNull Lib l) {\n" +
710
			"        return l.getObject();\n" +
711
			"    }\n" +
712
			"}\n",
713
			
714
			"org/foo/MayBeNull.java",
715
			"package org.foo;\n" +
716
			"import java.lang.annotation.*;\n" +
717
			"@Retention(RetentionPolicy.CLASS)\n" +
718
			"public @interface MayBeNull {}\n",
719
			
720
			"org/foo/MustNotBeNull.java",
721
			"package org.foo;\n" +
722
			"import java.lang.annotation.*;\n" +
723
			"@Retention(RetentionPolicy.CLASS)\n" +
724
			"public @interface MustNotBeNull {}\n",
725
		},
726
		null/*classLibs*/,
727
		customOptions,
728
		"----------\n" + 
729
		"1. ERROR in X.java (at line 3)\n" + 
730
		"	return l.getObject();\n" + 
731
		"	^^^^^^^^^^^^^^^^^^^^^\n" + 
732
		"Potential null contract violation: insufficient nullness information regarding return value while the method is declared as @MustNotBeNull.\n" +
733
//		"Potential null contract violation: insufficient nullness information for checking return value against declaration as @MustNotBeNull.\n" + 
734
		"----------\n",
735
		JavacTestOptions.SKIP);
736
}
737
// a non-null method returns a value obtained from an unannotated method, default import of missing annotation types
738
public void test_annotation_import_006() {
739
	Map customOptions = getCompilerOptions();
740
	customOptions.put(CompilerOptions.OPTION_ReportNullReference, CompilerOptions.ERROR);
741
	customOptions.put(CompilerOptions.OPTION_ReportNullContractInsufficientInfo, CompilerOptions.ERROR);
742
	customOptions.put(CompilerOptions.OPTION_NullableAnnotationName, "org.foo.MayBeNull");
743
	customOptions.put(CompilerOptions.OPTION_NonNullAnnotationName, "org.foo.MustNotBeNull");
744
	customOptions.put(CompilerOptions.OPTION_DefaultImportNullAnnotationTypes, CompilerOptions.ENABLED);
745
	customOptions.put(CompilerOptions.OPTION_EmulateNullAnnotationTypes, CompilerOptions.DISABLED);
746
	runNegativeTest(
747
		true/*shouldFlushOutputDirectory*/,
748
		new String[] {
749
			"Lib.java",
750
			"public class Lib {\n" +
751
			"    Object getObject() { return new Object(); }\n" +
752
			"}\n",
753
			"X.java",
754
			"public class X {\n" +
755
			"    @MustNotBeNull Object getObject(@MustNotBeNull Lib l) {\n" +
756
			"        return l.getObject();\n" +
757
			"    }\n" +
758
			"}\n"
759
		},
760
		null/*classLibs*/,
761
		customOptions,
762
		"----------\n" + 
763
		"1. ERROR in Lib.java (at line 0)\n" + 
764
		"	public class Lib {\n" + 
765
		"	^\n" + 
766
		"Buildpath problem: the type org.foo.MayBeNull which is configured as a null annotation type cannot be resolved.\n" + 
767
		"----------\n",
768
		JavacTestOptions.SKIP);
769
}
770
// emulation names conflict with existing types
771
public void test_annotation_emulation_001() {
772
	Map customOptions = getCompilerOptions();
773
	customOptions.put(CompilerOptions.OPTION_ReportNullReference, CompilerOptions.ERROR);
774
	customOptions.put(CompilerOptions.OPTION_NullableAnnotationName, "libpack.Lib");
775
	customOptions.put(CompilerOptions.OPTION_NonNullAnnotationName, "libpack.Lib");
776
	customOptions.put(CompilerOptions.OPTION_DefaultImportNullAnnotationTypes, CompilerOptions.ENABLED);
777
	runNegativeTest(
778
		true/*shouldFlushOutputDirectory*/,
779
		new String[] {
780
			"libpack/Lib.java",
781
			"package libpack;\n" +
782
			"public class Lib {\n" +
783
			"}\n",
784
		},
785
		null/*classLibs*/,
786
		customOptions,
787
		"----------\n" + 
788
		"1. ERROR in libpack\\Lib.java (at line 0)\n" + 
789
		"	package libpack;\n" + 
790
		"	^\n" + 
791
		"Buildpath problem: emulation of type libpack.Lib is requested (for null annotations) but a type of this name exists on the build path.\n" + 
792
		"----------\n",
793
		JavacTestOptions.SKIP);
794
}
795
// regular use (explicit import/FQN) of existing annotation types (=no emulation)
796
public void test_annotation_emulation_002() {
797
	Map customOptions = getCompilerOptions();
798
	customOptions.put(CompilerOptions.OPTION_ReportNullReference, CompilerOptions.ERROR);
799
	customOptions.put(CompilerOptions.OPTION_ReportPotentialNullContractViolation, CompilerOptions.ERROR);
800
	customOptions.put(CompilerOptions.OPTION_NullableAnnotationName, "org.foo.MayBeNull");
801
	customOptions.put(CompilerOptions.OPTION_NonNullAnnotationName, "org.foo.MustNotBeNull");
802
	customOptions.put(CompilerOptions.OPTION_DefaultImportNullAnnotationTypes, CompilerOptions.DISABLED);
803
	customOptions.put(CompilerOptions.OPTION_EmulateNullAnnotationTypes, CompilerOptions.DISABLED);
804
	runNegativeTest(
805
		true/*shouldFlushOutputDirectory*/,
806
		new String[] {
807
			"Lib.java",
808
			"public class Lib {\n" +
809
			"    @org.foo.MayBeNull Object getObject() { return new Object(); }\n" + 	// FQN
810
			"}\n",
811
			"X.java",
812
			"import org.foo.MustNotBeNull;\n" +											// explicit import
813
			"public class X {\n" +
814
			"    @MustNotBeNull Object getObject(@MustNotBeNull Lib l) {\n" +
815
			"        return l.getObject();\n" +
816
			"    }\n" +
817
			"}\n",
818
819
			"org/foo/MayBeNull.java",
820
			"package org.foo;\n" +
821
			"import java.lang.annotation.*;\n" +
822
			"@Retention(RetentionPolicy.CLASS)\n" +
823
			"public @interface MayBeNull {}\n",
824
			
825
			"org/foo/MustNotBeNull.java",
826
			"package org.foo;\n" +
827
			"import java.lang.annotation.*;\n" +
828
			"@Retention(RetentionPolicy.CLASS)\n" +
829
			"public @interface MustNotBeNull {}\n",
830
		},
831
		null/*classLibs*/,
832
		customOptions,
833
		"----------\n" + 
834
		"1. ERROR in X.java (at line 4)\n" + 
835
		"	return l.getObject();\n" + 
836
		"	^^^^^^^^^^^^^^^^^^^^^\n" + 
837
		"Null contract violation: return value can be null but method is declared as @MustNotBeNull.\n" + 
838
		"----------\n",
839
		JavacTestOptions.SKIP);
840
}
841
842
}
(-)src/org/eclipse/jdt/core/tests/compiler/regression/TestAll.java (-1 / +3 lines)
Lines 1-5 Link Here
1
/*******************************************************************************
1
/*******************************************************************************
2
 * Copyright (c) 2000, 2010 IBM Corporation and others.
2
 * Copyright (c) 2000, 2011 IBM Corporation and others.
3
 * All rights reserved. This program and the accompanying materials
3
 * All rights reserved. This program and the accompanying materials
4
 * are made available under the terms of the Eclipse Public License v1.0
4
 * are made available under the terms of the Eclipse Public License v1.0
5
 * which accompanies this distribution, and is available at
5
 * which accompanies this distribution, and is available at
Lines 7-12 Link Here
7
 *
7
 *
8
 * Contributors:
8
 * Contributors:
9
 *     IBM Corporation - initial API and implementation
9
 *     IBM Corporation - initial API and implementation
10
 *     Stephan Herrmann  - Contribution for bug 186342 - [compiler][null]Using annotations for null checking
10
 *******************************************************************************/
11
 *******************************************************************************/
11
package org.eclipse.jdt.core.tests.compiler.regression;
12
package org.eclipse.jdt.core.tests.compiler.regression;
12
13
Lines 63-68 Link Here
63
	if (UnconditionalFlowInfo.COVERAGE_TEST_FLAG) {
64
	if (UnconditionalFlowInfo.COVERAGE_TEST_FLAG) {
64
		standardTests.add(NullReferenceImplTests.class);
65
		standardTests.add(NullReferenceImplTests.class);
65
	}
66
	}
67
	standardTests.add(NullAnnotationTest.class);
66
	standardTests.add(CompilerInvocationTests.class);
68
	standardTests.add(CompilerInvocationTests.class);
67
	standardTests.add(InnerEmulationTest.class);
69
	standardTests.add(InnerEmulationTest.class);
68
	standardTests.add(SuperTypeTest.class);
70
	standardTests.add(SuperTypeTest.class);

Return to bug 186342