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

Collapse All | Expand All

(-)compiler/org/eclipse/jdt/core/compiler/IProblem.java (-1 / +16 lines)
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
 *									PotentiallyUnclosedCloseable
121
 *									PotentiallyUnclosedCloseableAtExit
122
 *									UnclosedCloseable
123
 *									UnclosedCloseableAtExit
124
 *									ExplicitlyClosedAutoCloseable
120
 *******************************************************************************/
125
 *******************************************************************************/
121
package org.eclipse.jdt.core.compiler;
126
package org.eclipse.jdt.core.compiler;
122
127
Lines 1392-1397 Link Here
1392
	int DiamondNotBelow17 =  TypeRelated + 883;
1397
	int DiamondNotBelow17 =  TypeRelated + 883;
1393
	/** @since 3.7.1 */
1398
	/** @since 3.7.1 */
1394
	int RedundantSpecificationOfTypeArguments = TypeRelated + 884;
1399
	int RedundantSpecificationOfTypeArguments = TypeRelated + 884;
1400
	/** @since 3.8 */
1401
	int PotentiallyUnclosedCloseable = Internal + 885;
1402
	/** @since 3.8 */
1403
	int PotentiallyUnclosedCloseableAtExit = Internal + 886;
1404
	/** @since 3.8 */
1405
	int UnclosedCloseable = Internal + 887;
1406
	/** @since 3.8 */
1407
	int UnclosedCloseableAtExit = Internal + 888;
1408
	/** @since 3.8 */
1409
	int ExplicitlyClosedAutoCloseable = Internal + 889;
1395
	/**
1410
	/**
1396
	 * External problems -- These are problems defined by other plugins
1411
	 * External problems -- These are problems defined by other plugins
1397
	 */
1412
	 */
(-)compiler/org/eclipse/jdt/internal/compiler/ast/AllocationExpression.java (+3 lines)
Lines 10-15 Link Here
10
 *     Stephan Herrmann - Contributions for 
10
 *     Stephan Herrmann - Contributions for 
11
 *     						bug 236385 - [compiler] Warn for potential programming problem if an object is created but not used
11
 *     						bug 236385 - [compiler] Warn for potential programming problem if an object is created but not used
12
 *     						bug 319201 - [null] no warning when unboxing SingleNameReference causes NPE
12
 *     						bug 319201 - [null] no warning when unboxing SingleNameReference causes NPE
13
 *     						bug 349326 - [1.7] new warning for missing try-with-resources
13
 *******************************************************************************/
14
 *******************************************************************************/
14
package org.eclipse.jdt.internal.compiler.ast;
15
package org.eclipse.jdt.internal.compiler.ast;
15
16
Lines 42-47 Link Here
42
	// process arguments
43
	// process arguments
43
	if (this.arguments != null) {
44
	if (this.arguments != null) {
44
		for (int i = 0, count = this.arguments.length; i < count; i++) {
45
		for (int i = 0, count = this.arguments.length; i < count; i++) {
46
			// if argument is an AutoCloseable insert info that it *may* be closed (by the target method, i.e.)
47
			flowInfo = FakedTrackingVariable.markPotentialClosing(this.arguments[i], flowInfo);
45
			flowInfo =
48
			flowInfo =
46
				this.arguments[i]
49
				this.arguments[i]
47
					.analyseCode(currentScope, flowContext, flowInfo)
50
					.analyseCode(currentScope, flowContext, flowInfo)
(-)compiler/org/eclipse/jdt/internal/compiler/ast/Assignment.java (+29 lines)
Lines 12-17 Link Here
12
 * 							bug 319201 - [null] no warning when unboxing SingleNameReference causes NPE
12
 * 							bug 319201 - [null] no warning when unboxing SingleNameReference causes NPE
13
 * 							bug 292478 - Report potentially null across variable assignment
13
 * 							bug 292478 - Report potentially null across variable assignment
14
 *     						bug 335093 - [compiler][null] minimal hook for future null annotation support
14
 *     						bug 335093 - [compiler][null] minimal hook for future null annotation support
15
 *     						bug 349326 - [1.7] new warning for missing try-with-resources
15
 *******************************************************************************/
16
 *******************************************************************************/
16
package org.eclipse.jdt.internal.compiler.ast;
17
package org.eclipse.jdt.internal.compiler.ast;
17
18
Lines 47-52 Link Here
47
	flowInfo = ((Reference) this.lhs)
48
	flowInfo = ((Reference) this.lhs)
48
		.analyseAssignment(currentScope, flowContext, flowInfo, this, false)
49
		.analyseAssignment(currentScope, flowContext, flowInfo, this, false)
49
		.unconditionalInits();
50
		.unconditionalInits();
51
	if (local != null) {
52
		LocalVariableBinding trackerBinding = null;
53
		if (local.closeTracker != null) {
54
			// Assigning to a variable already holding an AutoCloseable, has it been closed before?
55
			trackerBinding = local.closeTracker.binding;
56
			if (!flowInfo.isDefinitelyNull(local)) { // only if previous value may be non-null
57
				if (flowInfo.isDefinitelyNull(trackerBinding)) 
58
					currentScope.problemReporter().unclosedCloseable(local.closeTracker, this);
59
				else if (flowInfo.isPotentiallyNull(trackerBinding)) 
60
					currentScope.problemReporter().potentiallyUnclosedCloseable(local.closeTracker, this);
61
			}
62
		}
63
		if (FakedTrackingVariable.isAutoCloseable(this.expression.resolvedType)) {
64
			if (local.closeTracker != null && local.closeTracker.isInsideTryWithResources) { 
65
				// re-assigning resource of try-with-resources is a different error
66
			} else {
67
				// new value is AutoCloseable, start tracking, possibly re-using existing tracker var:
68
				if (trackerBinding == null) {
69
					local.closeTracker = new FakedTrackingVariable(local, this);
70
					trackerBinding = local.closeTracker.binding;
71
				}
72
				flowInfo.markAsDefinitelyNull(trackerBinding);
73
// TODO(stephan): this might be useful, but I could not find a test case for it: 
74
//				if (flowContext.initsOnFinally != null)
75
//					flowContext.initsOnFinally.markAsDefinitelyNonNull(trackerBinding);
76
			}
77
		}
78
	}
50
	int nullStatus = this.expression.nullStatus(flowInfo);
79
	int nullStatus = this.expression.nullStatus(flowInfo);
51
	if (local != null && (local.type.tagBits & TagBits.IsBaseType) == 0) {
80
	if (local != null && (local.type.tagBits & TagBits.IsBaseType) == 0) {
52
		if (nullStatus == FlowInfo.NULL) {
81
		if (nullStatus == FlowInfo.NULL) {
(-)compiler/org/eclipse/jdt/internal/compiler/ast/Block.java (-1 / +4 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 349326 - [1.7] new warning for missing try-with-resources
10
 *******************************************************************************/
11
 *******************************************************************************/
11
package org.eclipse.jdt.internal.compiler.ast;
12
package org.eclipse.jdt.internal.compiler.ast;
12
13
Lines 36-41 Link Here
36
			flowInfo = stat.analyseCode(this.scope, flowContext, flowInfo);
37
			flowInfo = stat.analyseCode(this.scope, flowContext, flowInfo);
37
		}
38
		}
38
	}
39
	}
40
	if (this.explicitDeclarations > 0) // if block has its own scope analyze tracking vars now:
41
		this.scope.checkUnclosedCloseables(flowInfo, flowContext, null);
39
	return flowInfo;
42
	return flowInfo;
40
}
43
}
41
/**
44
/**
(-)compiler/org/eclipse/jdt/internal/compiler/ast/FakedTrackingVariable.java (+115 lines)
Added Link Here
1
/*******************************************************************************
2
 * Copyright (c) 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.internal.compiler.ast;
12
13
import org.eclipse.jdt.internal.compiler.codegen.CodeStream;
14
import org.eclipse.jdt.internal.compiler.flow.FlowInfo;
15
import org.eclipse.jdt.internal.compiler.impl.Constant;
16
import org.eclipse.jdt.internal.compiler.lookup.BlockScope;
17
import org.eclipse.jdt.internal.compiler.lookup.LocalVariableBinding;
18
import org.eclipse.jdt.internal.compiler.lookup.MethodScope;
19
import org.eclipse.jdt.internal.compiler.lookup.ReferenceBinding;
20
import org.eclipse.jdt.internal.compiler.lookup.TypeBinding;
21
import org.eclipse.jdt.internal.compiler.lookup.TypeConstants;
22
import org.eclipse.jdt.internal.compiler.lookup.TypeIds;
23
24
/**
25
 * A faked local variable declaration used for keeping track of data flows of a
26
 * special variable. Certain events will be recorded by changing the null info
27
 * for this variable.
28
 * 
29
 * See bug 349326 - [1.7] new warning for missing try-with-resources
30
 */
31
public class FakedTrackingVariable extends LocalDeclaration {
32
33
	/** If resource is already managed by try-with-resources don't complain. */
34
	public boolean isInsideTryWithResources;
35
36
	/** 
37
	 * If close() is invoked from a nested method (inside a local type) 
38
	 * report remaining problems only as potential.
39
	 */
40
	public boolean closedInNestedMethod; 
41
42
	/** If a problem has already been reported don't complain again. */
43
	public boolean hasReportedProblem;
44
45
	MethodScope methodScope; // designates the method declaring this variable
46
	
47
	public LocalVariableBinding originalBinding; // the real local being tracked
48
49
	public FakedTrackingVariable(LocalVariableBinding original, Statement location) {
50
		super(original.name, location.sourceStart, location.sourceEnd);
51
		this.type = new SingleTypeReference(
52
				TypeConstants.OBJECT,
53
				((long)this.sourceStart <<32)+this.sourceEnd);
54
		this.methodScope = original.declaringScope.methodScope();
55
		this.originalBinding = original;
56
		resolve(original.declaringScope);
57
	}
58
	
59
	public void generateCode(BlockScope currentScope, CodeStream codeStream)
60
	{ /* NOP - this variable is completely dummy, ie. for analysis only. */ }
61
62
	public void resolve (BlockScope scope) {
63
		// only need the binding, which is used as reference in FlowInfo methods.
64
		this.binding = new LocalVariableBinding(
65
				this.name,
66
				scope.getJavaLangObject(),  // dummy, just needs to be a reference type
67
				0,
68
				false);
69
		this.binding.setConstant(Constant.NotAConstant);
70
		this.binding.useFlag = LocalVariableBinding.USED;
71
		// use a free slot without assigning it:
72
		this.binding.id = scope.registerTrackingVariable(this);
73
	}
74
75
	/**
76
	 * If expression resolves to a local variable binding of type AutoCloseable,
77
	 * answer the variable that tracks closing of that local, creating it if needed.
78
	 * @param expression
79
	 * @return a new {@link FakedTrackingVariable} or null.
80
	 */
81
	public static FakedTrackingVariable getCloseTrackingVariable(Expression expression) {
82
		if (expression instanceof SingleNameReference) {
83
			SingleNameReference name = (SingleNameReference) expression;
84
			if (name.binding instanceof LocalVariableBinding) {
85
				LocalVariableBinding local = (LocalVariableBinding)name.binding;
86
				if (local.closeTracker != null)
87
					return local.closeTracker;
88
				if (local.isParameter() || !isAutoCloseable(expression.resolvedType))
89
					return null;
90
				// tracking var doesn't yet exist. This happens in finally block
91
				// which is analyzed before the corresponding try block
92
				Statement location = local.declaration;
93
				return local.closeTracker = new FakedTrackingVariable(local, location);
94
			}
95
		}
96
		return null;
97
	}
98
99
	public static FlowInfo markPotentialClosing(Expression expression, FlowInfo flowInfo) {
100
		FakedTrackingVariable trackVar = getCloseTrackingVariable(expression);
101
		if (trackVar != null) {
102
			// insert info that the tracked resource *may* be closed (by the target method, i.e.)
103
			FlowInfo infoResourceIsClosed = flowInfo.copy();
104
			infoResourceIsClosed.markAsDefinitelyNonNull(trackVar.binding);
105
			return FlowInfo.conditional(flowInfo, infoResourceIsClosed);
106
		}
107
		return flowInfo;
108
	}
109
110
	/** Answer wither the given type binding is a subtype of java.lang.AutoCloseable. */
111
	public static boolean isAutoCloseable(TypeBinding typeBinding) {
112
		return typeBinding instanceof ReferenceBinding
113
			&& ((ReferenceBinding)typeBinding).hasTypeBit(TypeIds.BitAutoCloseable);
114
	}
115
}
(-)compiler/org/eclipse/jdt/internal/compiler/ast/IfStatement.java (-1 / +5 lines)
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 349326 - [1.7] new warning for missing try-with-resources
11
 *******************************************************************************/
13
 *******************************************************************************/
12
package org.eclipse.jdt.internal.compiler.ast;
14
package org.eclipse.jdt.internal.compiler.ast;
13
15
Lines 124-129 Link Here
124
		}
126
		}
125
		elseFlowInfo = this.elseStatement.analyseCode(currentScope, flowContext, elseFlowInfo);
127
		elseFlowInfo = this.elseStatement.analyseCode(currentScope, flowContext, elseFlowInfo);
126
	}
128
	}
129
	// process AutoCloseable resources closed in only one branch:
130
	currentScope.correlateTrackingVarsIfElse(thenFlowInfo, elseFlowInfo);
127
	// merge THEN & ELSE initializations
131
	// merge THEN & ELSE initializations
128
	FlowInfo mergedInfo = FlowInfo.mergedOptimizedBranchesIfElse(
132
	FlowInfo mergedInfo = FlowInfo.mergedOptimizedBranchesIfElse(
129
		thenFlowInfo,
133
		thenFlowInfo,
(-)compiler/org/eclipse/jdt/internal/compiler/ast/LocalDeclaration.java (+8 lines)
Lines 11-16 Link Here
11
 *     						bug 319201 - [null] no warning when unboxing SingleNameReference causes NPE
11
 *     						bug 319201 - [null] no warning when unboxing SingleNameReference causes NPE
12
 *     						bug 292478 - Report potentially null across variable assignment
12
 *     						bug 292478 - Report potentially null across variable assignment
13
 *     						bug 335093 - [compiler][null] minimal hook for future null annotation support
13
 *     						bug 335093 - [compiler][null] minimal hook for future null annotation support
14
 *     						bug 349326 - [1.7] new warning for missing try-with-resources
14
 *******************************************************************************/
15
 *******************************************************************************/
15
package org.eclipse.jdt.internal.compiler.ast;
16
package org.eclipse.jdt.internal.compiler.ast;
16
17
Lines 76-81 Link Here
76
		this.initialization
77
		this.initialization
77
			.analyseCode(currentScope, flowContext, flowInfo)
78
			.analyseCode(currentScope, flowContext, flowInfo)
78
			.unconditionalInits();
79
			.unconditionalInits();
80
	if (FakedTrackingVariable.isAutoCloseable(this.initialization.resolvedType)) {
81
		this.binding.closeTracker = new FakedTrackingVariable(this.binding, this);
82
		flowInfo.markAsDefinitelyNull(this.binding.closeTracker.binding);
83
// TODO(stephan): this might be useful, but I could not find a test case for it: 
84
//		if (flowContext.initsOnFinally != null)
85
//			flowContext.initsOnFinally.markAsDefinitelyNonNull(this.binding.closeTracker.binding);
86
	}
79
	int nullStatus = this.initialization.nullStatus(flowInfo);
87
	int nullStatus = this.initialization.nullStatus(flowInfo);
80
	if (!flowInfo.isDefinitelyAssigned(this.binding)){// for local variable debug attributes
88
	if (!flowInfo.isDefinitelyAssigned(this.binding)){// for local variable debug attributes
81
		this.bits |= FirstAssignmentToLocal;
89
		this.bits |= FirstAssignmentToLocal;
(-)compiler/org/eclipse/jdt/internal/compiler/ast/MessageSend.java (-1 / +21 lines)
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 349326 - [1.7] new warning for missing try-with-resources
12
 *******************************************************************************/
14
 *******************************************************************************/
13
package org.eclipse.jdt.internal.compiler.ast;
15
package org.eclipse.jdt.internal.compiler.ast;
14
16
Lines 38-43 Link Here
38
import org.eclipse.jdt.internal.compiler.lookup.SourceTypeBinding;
40
import org.eclipse.jdt.internal.compiler.lookup.SourceTypeBinding;
39
import org.eclipse.jdt.internal.compiler.lookup.TagBits;
41
import org.eclipse.jdt.internal.compiler.lookup.TagBits;
40
import org.eclipse.jdt.internal.compiler.lookup.TypeBinding;
42
import org.eclipse.jdt.internal.compiler.lookup.TypeBinding;
43
import org.eclipse.jdt.internal.compiler.lookup.TypeConstants;
41
import org.eclipse.jdt.internal.compiler.lookup.TypeIds;
44
import org.eclipse.jdt.internal.compiler.lookup.TypeIds;
42
import org.eclipse.jdt.internal.compiler.problem.ProblemSeverities;
45
import org.eclipse.jdt.internal.compiler.problem.ProblemSeverities;
43
46
Lines 60-65 Link Here
60
public FlowInfo analyseCode(BlockScope currentScope, FlowContext flowContext, FlowInfo flowInfo) {
63
public FlowInfo analyseCode(BlockScope currentScope, FlowContext flowContext, FlowInfo flowInfo) {
61
	boolean nonStatic = !this.binding.isStatic();
64
	boolean nonStatic = !this.binding.isStatic();
62
	flowInfo = this.receiver.analyseCode(currentScope, flowContext, flowInfo, nonStatic).unconditionalInits();
65
	flowInfo = this.receiver.analyseCode(currentScope, flowContext, flowInfo, nonStatic).unconditionalInits();
66
	// recording the closing of AutoCloseable resources:
67
	if (CharOperation.equals(TypeConstants.CLOSE, this.selector)) 
68
	{
69
		FakedTrackingVariable trackingVariable = FakedTrackingVariable.getCloseTrackingVariable(this.receiver);
70
		if (trackingVariable != null) { // null happens if receiver is not a local variable or not an AutoCloseable
71
			if (trackingVariable.methodScope == currentScope.methodScope()) {
72
				flowInfo.markAsDefinitelyNonNull(trackingVariable.binding);
73
// TODO(stephan): this might be useful, but I could not find a test case for it: 
74
//				if (flowContext.initsOnFinally != null)
75
//					flowContext.initsOnFinally.markAsDefinitelyNonNull(trackingVariable.binding);
76
			} else {
77
				trackingVariable.closedInNestedMethod = true;
78
			}
79
		}
80
	}
63
	if (nonStatic) {
81
	if (nonStatic) {
64
		this.receiver.checkNPE(currentScope, flowContext, flowInfo);
82
		this.receiver.checkNPE(currentScope, flowContext, flowInfo);
65
		// https://bugs.eclipse.org/bugs/show_bug.cgi?id=318682
83
		// https://bugs.eclipse.org/bugs/show_bug.cgi?id=318682
Lines 80-85 Link Here
80
			if ((this.arguments[i].implicitConversion & TypeIds.UNBOXING) != 0) {
98
			if ((this.arguments[i].implicitConversion & TypeIds.UNBOXING) != 0) {
81
				this.arguments[i].checkNPE(currentScope, flowContext, flowInfo);
99
				this.arguments[i].checkNPE(currentScope, flowContext, flowInfo);
82
			}
100
			}
101
			// if argument is an AutoCloseable insert info that it *may* be closed (by the target method, i.e.)
102
			flowInfo = FakedTrackingVariable.markPotentialClosing(this.arguments[i], flowInfo);
83
			flowInfo = this.arguments[i].analyseCode(currentScope, flowContext, flowInfo).unconditionalInits();
103
			flowInfo = this.arguments[i].analyseCode(currentScope, flowContext, flowInfo).unconditionalInits();
84
		}
104
		}
85
	}
105
	}
(-)compiler/org/eclipse/jdt/internal/compiler/ast/MethodDeclaration.java (+2 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 349326 - [1.7] new warning for missing try-with-resources
10
 *******************************************************************************/
11
 *******************************************************************************/
11
package org.eclipse.jdt.internal.compiler.ast;
12
package org.eclipse.jdt.internal.compiler.ast;
12
13
Lines 134-139 Link Here
134
				}
135
				}
135
					
136
					
136
			}
137
			}
138
			this.scope.checkUnclosedCloseables(flowInfo, methodContext, null/*don't report against a specific location*/);
137
		} catch (AbortMethod e) {
139
		} catch (AbortMethod e) {
138
			this.ignoreFurtherInvestigation = true;
140
			this.ignoreFurtherInvestigation = true;
139
		}
141
		}
(-)compiler/org/eclipse/jdt/internal/compiler/ast/QualifiedAllocationExpression.java (-1 / +5 lines)
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 349326 - [1.7] new warning for missing try-with-resources
11
 *******************************************************************************/
13
 *******************************************************************************/
12
package org.eclipse.jdt.internal.compiler.ast;
14
package org.eclipse.jdt.internal.compiler.ast;
13
15
Lines 72-77 Link Here
72
		// process arguments
74
		// process arguments
73
		if (this.arguments != null) {
75
		if (this.arguments != null) {
74
			for (int i = 0, count = this.arguments.length; i < count; i++) {
76
			for (int i = 0, count = this.arguments.length; i < count; i++) {
77
				// if argument is an AutoCloseable insert info that it *may* be closed (by the target method, i.e.)
78
				flowInfo = FakedTrackingVariable.markPotentialClosing(this.arguments[i], flowInfo);
75
				flowInfo = this.arguments[i].analyseCode(currentScope, flowContext, flowInfo);
79
				flowInfo = this.arguments[i].analyseCode(currentScope, flowContext, flowInfo);
76
				if ((this.arguments[i].implicitConversion & TypeIds.UNBOXING) != 0) {
80
				if ((this.arguments[i].implicitConversion & TypeIds.UNBOXING) != 0) {
77
					this.arguments[i].checkNPE(currentScope, flowContext, flowInfo);
81
					this.arguments[i].checkNPE(currentScope, flowContext, flowInfo);
(-)compiler/org/eclipse/jdt/internal/compiler/ast/ReturnStatement.java (-1 / +11 lines)
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 349326 - [1.7] new warning for missing try-with-resources
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
		FakedTrackingVariable trackingVariable = FakedTrackingVariable.getCloseTrackingVariable(this.expression);
46
		if (trackingVariable != null) {
47
			// don't report issues concerning this local, since by returning
48
			// the method passes the responsibility to the caller:
49
			flowInfo.markAsDefinitelyNonNull(trackingVariable.binding);
50
			trackingVariable.hasReportedProblem = true;
51
		}
43
	}
52
	}
44
	this.initStateIndex =
53
	this.initStateIndex =
45
		currentScope.methodScope().recordInitializationStates(flowInfo);
54
		currentScope.methodScope().recordInitializationStates(flowInfo);
Lines 104-109 Link Here
104
			this.expression.bits |= ASTNode.IsReturnedValue;
113
			this.expression.bits |= ASTNode.IsReturnedValue;
105
		}
114
		}
106
	}
115
	}
116
	currentScope.checkUnclosedCloseables(flowInfo, null/*ignore exception exits from flowContext*/, this);
107
	return FlowInfo.DEAD_END;
117
	return FlowInfo.DEAD_END;
108
}
118
}
109
119
(-)compiler/org/eclipse/jdt/internal/compiler/ast/TryStatement.java (-5 / +27 lines)
Lines 7-16 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 332637 - Dead Code detection removing code that isn't dead
10
 *     Stephan Herrmann - Contributions for
11
 *     							bug 332637 - Dead Code detection removing code that isn't dead
12
 *     							bug 349326 - [1.7] new warning for missing try-with-resources
11
 *******************************************************************************/
13
 *******************************************************************************/
12
package org.eclipse.jdt.internal.compiler.ast;
14
package org.eclipse.jdt.internal.compiler.ast;
13
15
16
import java.util.ArrayList;
17
import java.util.List;
18
14
import org.eclipse.jdt.core.compiler.CharOperation;
19
import org.eclipse.jdt.core.compiler.CharOperation;
15
import org.eclipse.jdt.internal.compiler.ASTVisitor;
20
import org.eclipse.jdt.internal.compiler.ASTVisitor;
16
import org.eclipse.jdt.internal.compiler.classfmt.ClassFileConstants;
21
import org.eclipse.jdt.internal.compiler.classfmt.ClassFileConstants;
Lines 116-123 Link Here
116
121
117
		for (int i = 0, max = this.resources.length; i < max; i++) {
122
		for (int i = 0, max = this.resources.length; i < max; i++) {
118
			flowInfo = this.resources[i].analyseCode(currentScope, handlingContext, flowInfo.copy());
123
			flowInfo = this.resources[i].analyseCode(currentScope, handlingContext, flowInfo.copy());
119
			this.resources[i].binding.useFlag = LocalVariableBinding.USED; // Is implicitly used anyways.
124
			LocalVariableBinding resourceBinding = this.resources[i].binding;
120
			TypeBinding type = this.resources[i].binding.type;
125
			resourceBinding.useFlag = LocalVariableBinding.USED; // Is implicitly used anyways.
126
			if (resourceBinding.closeTracker != null) {
127
				resourceBinding.closeTracker.isInsideTryWithResources = true;
128
				flowInfo.markAsDefinitelyNonNull(resourceBinding.closeTracker.binding); // all is well
129
			} 
130
			TypeBinding type = resourceBinding.type;
121
			if (type != null && type.isValidBinding()) {
131
			if (type != null && type.isValidBinding()) {
122
				ReferenceBinding binding = (ReferenceBinding) type;
132
				ReferenceBinding binding = (ReferenceBinding) type;
123
				MethodBinding closeMethod = binding.getExactMethod(ConstantPool.Close, new TypeBinding [0], this.scope.compilationUnitScope()); // scope needs to be tighter
133
				MethodBinding closeMethod = binding.getExactMethod(ConstantPool.Close, new TypeBinding [0], this.scope.compilationUnitScope()); // scope needs to be tighter
Lines 241-248 Link Here
241
251
242
		for (int i = 0, max = this.resources.length; i < max; i++) {
252
		for (int i = 0, max = this.resources.length; i < max; i++) {
243
			flowInfo = this.resources[i].analyseCode(currentScope, handlingContext, flowInfo.copy());
253
			flowInfo = this.resources[i].analyseCode(currentScope, handlingContext, flowInfo.copy());
244
			this.resources[i].binding.useFlag = LocalVariableBinding.USED; // Is implicitly used anyways.
254
			LocalVariableBinding resourceBinding = this.resources[i].binding;
245
			TypeBinding type = this.resources[i].binding.type;
255
			resourceBinding.useFlag = LocalVariableBinding.USED; // Is implicitly used anyways.
256
			if (resourceBinding.closeTracker != null) {
257
				resourceBinding.closeTracker.isInsideTryWithResources = true;
258
				flowInfo.markAsDefinitelyNonNull(resourceBinding.closeTracker.binding); // all is well
259
			} 
260
			TypeBinding type = resourceBinding.type;
246
			if (type != null && type.isValidBinding()) {
261
			if (type != null && type.isValidBinding()) {
247
				ReferenceBinding binding = (ReferenceBinding) type;
262
				ReferenceBinding binding = (ReferenceBinding) type;
248
				MethodBinding closeMethod = binding.getExactMethod(ConstantPool.Close, new TypeBinding [0], this.scope.compilationUnitScope()); // scope needs to be tighter
263
				MethodBinding closeMethod = binding.getExactMethod(ConstantPool.Close, new TypeBinding [0], this.scope.compilationUnitScope()); // scope needs to be tighter
Lines 263-268 Link Here
263
				this.bits |= ASTNode.IsTryBlockExiting;
278
				this.bits |= ASTNode.IsTryBlockExiting;
264
		}
279
		}
265
280
281
		// superimpose status for tracking variables:
282
		//   don't complain on initsOnException if finally has a better state.
283
		List trackVars = new ArrayList();
284
		currentScope.getTrackVars(trackVars, subInfo);
285
		if (trackVars.size() > 0)
286
			flowContext.improveNullInfoForExceptionExits(trackVars, subInfo);
287
266
		// check unreachable catch blocks
288
		// check unreachable catch blocks
267
		handlingContext.complainIfUnusedExceptionHandlers(this.scope, this);
289
		handlingContext.complainIfUnusedExceptionHandlers(this.scope, this);
268
290
(-)compiler/org/eclipse/jdt/internal/compiler/flow/ExceptionHandlingFlowContext.java (-3 / +41 lines)
Lines 7-28 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 349326 - [1.7] new warning for missing try-with-resources
10
 *******************************************************************************/
11
 *******************************************************************************/
11
package org.eclipse.jdt.internal.compiler.flow;
12
package org.eclipse.jdt.internal.compiler.flow;
12
13
13
import java.util.ArrayList;
14
import java.util.ArrayList;
15
import java.util.List;
14
16
15
import org.eclipse.jdt.internal.compiler.ast.AbstractMethodDeclaration;
16
import org.eclipse.jdt.internal.compiler.ast.ASTNode;
17
import org.eclipse.jdt.internal.compiler.ast.ASTNode;
18
import org.eclipse.jdt.internal.compiler.ast.AbstractMethodDeclaration;
17
import org.eclipse.jdt.internal.compiler.ast.Argument;
19
import org.eclipse.jdt.internal.compiler.ast.Argument;
18
import org.eclipse.jdt.internal.compiler.ast.UnionTypeReference;
20
import org.eclipse.jdt.internal.compiler.ast.FakedTrackingVariable;
19
import org.eclipse.jdt.internal.compiler.ast.SubRoutineStatement;
21
import org.eclipse.jdt.internal.compiler.ast.SubRoutineStatement;
20
import org.eclipse.jdt.internal.compiler.ast.TryStatement;
22
import org.eclipse.jdt.internal.compiler.ast.TryStatement;
21
import org.eclipse.jdt.internal.compiler.ast.TypeReference;
23
import org.eclipse.jdt.internal.compiler.ast.TypeReference;
24
import org.eclipse.jdt.internal.compiler.ast.UnionTypeReference;
22
import org.eclipse.jdt.internal.compiler.codegen.ObjectCache;
25
import org.eclipse.jdt.internal.compiler.codegen.ObjectCache;
23
import org.eclipse.jdt.internal.compiler.lookup.BlockScope;
26
import org.eclipse.jdt.internal.compiler.lookup.BlockScope;
24
import org.eclipse.jdt.internal.compiler.lookup.CatchParameterBinding;
27
import org.eclipse.jdt.internal.compiler.lookup.CatchParameterBinding;
25
import org.eclipse.jdt.internal.compiler.lookup.ExtraCompilerModifiers;
28
import org.eclipse.jdt.internal.compiler.lookup.ExtraCompilerModifiers;
29
import org.eclipse.jdt.internal.compiler.lookup.LocalVariableBinding;
26
import org.eclipse.jdt.internal.compiler.lookup.MethodScope;
30
import org.eclipse.jdt.internal.compiler.lookup.MethodScope;
27
import org.eclipse.jdt.internal.compiler.lookup.ReferenceBinding;
31
import org.eclipse.jdt.internal.compiler.lookup.ReferenceBinding;
28
import org.eclipse.jdt.internal.compiler.lookup.Scope;
32
import org.eclipse.jdt.internal.compiler.lookup.Scope;
Lines 180-186 Link Here
180
	return node;
184
	return node;
181
}
185
}
182
186
183
187
public int getNullStatusAfter(LocalVariableBinding local, FlowInfo flowInfo) {
188
	// collect info from normal flow and exceptional flows:
189
	int status = flowInfo.nullStatus(local);
190
	if (this.initsOnExceptions != null)
191
		for (int i = 0; i < this.initsOnExceptions.length; i++)
192
			status |= (this.initsOnExceptions[i].nullStatus(local) & (FlowInfo.NULL|FlowInfo.POTENTIALLY_NULL));
193
	return status;
194
}
184
195
185
public String individualToString() {
196
public String individualToString() {
186
	StringBuffer buffer = new StringBuffer("Exception flow context"); //$NON-NLS-1$
197
	StringBuffer buffer = new StringBuffer("Exception flow context"); //$NON-NLS-1$
Lines 298-301 Link Here
298
	}
309
	}
299
	return null;
310
	return null;
300
}
311
}
312
/**
313
 * {@inheritDoc}
314
 */
315
public void improveNullInfoForExceptionExits(List moreTrackVars, FlowInfo otherInfo) {
316
	if (this.initsOnExceptions == null) return;
317
	for (int j = 0; j < this.initsOnExceptions.length; j++) {
318
		UnconditionalFlowInfo copy = null;
319
		for (int i = 0; i < moreTrackVars.size(); i++) {
320
			LocalVariableBinding trackVar = ((FakedTrackingVariable) moreTrackVars.get(i)).binding;
321
			int status = otherInfo.nullStatus(trackVar);
322
			if ((status & FlowInfo.NULL) == 0) {
323
				if ((status & FlowInfo.NON_NULL) != 0) {
324
					this.initsOnExceptions[j].markAsDefinitelyNonNull(trackVar);
325
				} else if ((status & FlowInfo.POTENTIALLY_NON_NULL) != 0) {
326
					if (this.initsOnExceptions[j].isDefinitelyNull(trackVar)) {
327
						// cannot directly set to pot.nn, need to construct and merge infos for this task:
328
						if (copy == null)
329
							copy = this.initsOnExceptions[j].unconditionalCopy();
330
						copy.markAsDefinitelyNonNull(trackVar);
331
					}
332
				}
333
			}
334
		}
335
		if (copy != null)
336
			this.initsOnExceptions[j] = this.initsOnExceptions[j].mergedWith(copy);
337
	}
338
}
301
}
339
}
(-)compiler/org/eclipse/jdt/internal/compiler/flow/FlowContext.java (-1 / +49 lines)
Lines 7-19 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 349326 - [1.7] new warning for missing try-with-resources
10
 *******************************************************************************/
11
 *******************************************************************************/
11
package org.eclipse.jdt.internal.compiler.flow;
12
package org.eclipse.jdt.internal.compiler.flow;
12
13
13
import java.util.ArrayList;
14
import java.util.ArrayList;
15
import java.util.List;
16
14
import org.eclipse.jdt.core.compiler.CharOperation;
17
import org.eclipse.jdt.core.compiler.CharOperation;
15
import org.eclipse.jdt.internal.compiler.ast.AbstractMethodDeclaration;
16
import org.eclipse.jdt.internal.compiler.ast.ASTNode;
18
import org.eclipse.jdt.internal.compiler.ast.ASTNode;
19
import org.eclipse.jdt.internal.compiler.ast.AbstractMethodDeclaration;
17
import org.eclipse.jdt.internal.compiler.ast.Expression;
20
import org.eclipse.jdt.internal.compiler.ast.Expression;
18
import org.eclipse.jdt.internal.compiler.ast.LabeledStatement;
21
import org.eclipse.jdt.internal.compiler.ast.LabeledStatement;
19
import org.eclipse.jdt.internal.compiler.ast.Reference;
22
import org.eclipse.jdt.internal.compiler.ast.Reference;
Lines 391-396 Link Here
391
	return null;
394
	return null;
392
}
395
}
393
396
397
/**
398
 * Answer the combined null status that local will have after this flow context.
399
 * Subclasses will respect break and exception exits.
400
 */
401
public int getNullStatusAfter(LocalVariableBinding local, FlowInfo flowInfo) {
402
	return flowInfo.nullStatus(local);
403
}
404
394
/*
405
/*
395
 * lookup through break labels
406
 * lookup through break labels
396
 */
407
 */
Lines 732-735 Link Here
732
	buffer.append(individualToString()).append('\n');
743
	buffer.append(individualToString()).append('\n');
733
	return buffer.toString();
744
	return buffer.toString();
734
}
745
}
746
/** 
747
 * For all tracking variables in the given list improve the null info in initsOnException (if existent)
748
 * with information from the given otherInfo.
749
 */
750
public void improveNullInfoForExceptionExits(List moreTrackVars, FlowInfo otherInfo) { 
751
	// nothing here, overridden in ExceptionHandlingFlowContext
752
}
753
754
/**
755
 * Get the null status that local will have after the current point as indicated by flowInfo and flowContext
756
 * @param local
757
 * @param flowInfo
758
 * @param flowContext may be null
759
 * @return a bitset from the constants FlowInfo.{NULL,POTENTIALLY_NULL,POTENTIALLY_NON_NULL,NON_NULL}.
760
 */
761
public static int getNullStatusAfter(LocalVariableBinding local, FlowInfo flowInfo, FlowContext flowContext) {
762
	int status = (flowContext != null) 
763
					? flowContext.getNullStatusAfter(local, flowInfo)
764
					: flowInfo.nullStatus(local);
765
	// at this point some combinations are not useful so flatten to a single bit:
766
	return mergeNullStatus(status);
767
}
768
769
/* Merge the bits NULL, NON_NULL, POTENTIALLY_NULL, POTENTIALLY_NON_NULL to a one-bit answer. */
770
private static int mergeNullStatus(int status) {
771
	if ((status & FlowInfo.NULL) != 0) {
772
		if ((status & (FlowInfo.NON_NULL | FlowInfo.POTENTIALLY_NON_NULL)) != 0)
773
			return FlowInfo.POTENTIALLY_NULL; 	// null + doubt = pot null
774
		return FlowInfo.NULL;
775
	} else if ((status & FlowInfo.NON_NULL) != 0) {
776
		if ((status & FlowInfo.POTENTIALLY_NULL) != 0)
777
			return FlowInfo.POTENTIALLY_NULL;	// non-null + doubt = pot null
778
		return FlowInfo.NON_NULL;
779
	} else if ((status & FlowInfo.POTENTIALLY_NULL) != 0)
780
		return FlowInfo.POTENTIALLY_NULL;
781
	return status;
782
}
735
}
783
}
(-)compiler/org/eclipse/jdt/internal/compiler/flow/SwitchFlowContext.java (+10 lines)
Lines 7-17 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 349326 - [1.7] new warning for missing try-with-resources
10
 *******************************************************************************/
11
 *******************************************************************************/
11
package org.eclipse.jdt.internal.compiler.flow;
12
package org.eclipse.jdt.internal.compiler.flow;
12
13
13
import org.eclipse.jdt.internal.compiler.ast.ASTNode;
14
import org.eclipse.jdt.internal.compiler.ast.ASTNode;
14
import org.eclipse.jdt.internal.compiler.codegen.BranchLabel;
15
import org.eclipse.jdt.internal.compiler.codegen.BranchLabel;
16
import org.eclipse.jdt.internal.compiler.lookup.LocalVariableBinding;
15
17
16
/**
18
/**
17
 * Reflects the context of code analysis, keeping track of enclosing
19
 * Reflects the context of code analysis, keeping track of enclosing
Lines 31-36 Link Here
31
	return this.breakLabel;
33
	return this.breakLabel;
32
}
34
}
33
35
36
public int getNullStatusAfter(LocalVariableBinding local, FlowInfo flowInfo) {
37
	// collect info from normal flow and breaks flows:
38
	int status = flowInfo.nullStatus(local);
39
	if (this.initsOnBreak != null)
40
		status |= this.initsOnBreak.nullStatus(local);
41
	return status;
42
}
43
34
public String individualToString() {
44
public String individualToString() {
35
	StringBuffer buffer = new StringBuffer("Switch flow context"); //$NON-NLS-1$
45
	StringBuffer buffer = new StringBuffer("Switch flow context"); //$NON-NLS-1$
36
	buffer.append("[initsOnBreak -").append(this.initsOnBreak.toString()).append(']'); //$NON-NLS-1$
46
	buffer.append("[initsOnBreak -").append(this.initsOnBreak.toString()).append(']'); //$NON-NLS-1$
(-)compiler/org/eclipse/jdt/internal/compiler/flow/UnconditionalFlowInfo.java (-6 / +7 lines)
Lines 13-18 Link Here
13
 *     						bug 292478 - Report potentially null across variable assignment
13
 *     						bug 292478 - Report potentially null across variable assignment
14
 *     						bug 332637 - Dead Code detection removing code that isn't dead
14
 *     						bug 332637 - Dead Code detection removing code that isn't dead
15
 *     						bug 341499 - [compiler][null] allocate extra bits in all methods of UnconditionalFlowInfo
15
 *     						bug 341499 - [compiler][null] allocate extra bits in all methods of UnconditionalFlowInfo
16
 *     						bug 349326 - [1.7] new warning for missing try-with-resources
16
 *******************************************************************************/
17
 *******************************************************************************/
17
package org.eclipse.jdt.internal.compiler.flow;
18
package org.eclipse.jdt.internal.compiler.flow;
18
19
Lines 770-776 Link Here
770
	}
771
	}
771
	int vectorIndex;
772
	int vectorIndex;
772
	if ((vectorIndex = (position / BitCacheSize) - 1)
773
	if ((vectorIndex = (position / BitCacheSize) - 1)
773
			>= this.extra[0].length) {
774
			>= this.extra[2].length) {
774
		return false; // if not enough room in vector, then not initialized
775
		return false; // if not enough room in vector, then not initialized
775
	}
776
	}
776
	return ((this.extra[2][vectorIndex] & this.extra[4][vectorIndex]
777
	return ((this.extra[2][vectorIndex] & this.extra[4][vectorIndex]
Lines 797-803 Link Here
797
	}
798
	}
798
	int vectorIndex;
799
	int vectorIndex;
799
	if ((vectorIndex = (position / BitCacheSize) - 1) >=
800
	if ((vectorIndex = (position / BitCacheSize) - 1) >=
800
			this.extra[0].length) {
801
			this.extra[2].length) {
801
		return false; // if not enough room in vector, then not initialized
802
		return false; // if not enough room in vector, then not initialized
802
	}
803
	}
803
	return ((this.extra[2][vectorIndex] & this.extra[3][vectorIndex]
804
	return ((this.extra[2][vectorIndex] & this.extra[3][vectorIndex]
Lines 822-828 Link Here
822
	}
823
	}
823
	int vectorIndex;
824
	int vectorIndex;
824
	if ((vectorIndex = (position / BitCacheSize) - 1) >=
825
	if ((vectorIndex = (position / BitCacheSize) - 1) >=
825
			this.extra[0].length) {
826
			this.extra[2].length) {
826
		return false; // if not enough room in vector, then not initialized
827
		return false; // if not enough room in vector, then not initialized
827
	}
828
	}
828
	return ((this.extra[2][vectorIndex] & this.extra[5][vectorIndex]
829
	return ((this.extra[2][vectorIndex] & this.extra[5][vectorIndex]
Lines 882-888 Link Here
882
	}
883
	}
883
	int vectorIndex;
884
	int vectorIndex;
884
	if ((vectorIndex = (position / BitCacheSize) - 1) >=
885
	if ((vectorIndex = (position / BitCacheSize) - 1) >=
885
			this.extra[0].length) {
886
			this.extra[2].length) {
886
		return false; // if not enough room in vector, then not initialized
887
		return false; // if not enough room in vector, then not initialized
887
	}
888
	}
888
	return ((this.extra[4][vectorIndex]
889
	return ((this.extra[4][vectorIndex]
Lines 908-914 Link Here
908
	}
909
	}
909
	int vectorIndex;
910
	int vectorIndex;
910
	if ((vectorIndex = (position / BitCacheSize) - 1) >=
911
	if ((vectorIndex = (position / BitCacheSize) - 1) >=
911
			this.extra[0].length) {
912
			this.extra[2].length) {
912
		return false; // if not enough room in vector, then not initialized
913
		return false; // if not enough room in vector, then not initialized
913
	}
914
	}
914
	return ((this.extra[3][vectorIndex]
915
	return ((this.extra[3][vectorIndex]
Lines 934-940 Link Here
934
	}
935
	}
935
	int vectorIndex;
936
	int vectorIndex;
936
	if ((vectorIndex = (position / BitCacheSize) - 1) >=
937
	if ((vectorIndex = (position / BitCacheSize) - 1) >=
937
			this.extra[0].length) {
938
			this.extra[2].length) {
938
		return false; // if not enough room in vector, then not initialized
939
		return false; // if not enough room in vector, then not initialized
939
	}
940
	}
940
	return (this.extra[5][vectorIndex]
941
	return (this.extra[5][vectorIndex]
(-)compiler/org/eclipse/jdt/internal/compiler/impl/CompilerOptions.java (-4 / +37 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 349326 - [1.7] new warning for missing try-with-resources
13
 *******************************************************************************/
15
 *******************************************************************************/
14
package org.eclipse.jdt.internal.compiler.impl;
16
package org.eclipse.jdt.internal.compiler.impl;
15
17
Lines 137-142 Link Here
137
	public static final String OPTION_ReportMethodCanBeStatic = "org.eclipse.jdt.core.compiler.problem.reportMethodCanBeStatic";  //$NON-NLS-1$
139
	public static final String OPTION_ReportMethodCanBeStatic = "org.eclipse.jdt.core.compiler.problem.reportMethodCanBeStatic";  //$NON-NLS-1$
138
	public static final String OPTION_ReportMethodCanBePotentiallyStatic = "org.eclipse.jdt.core.compiler.problem.reportMethodCanBePotentiallyStatic";  //$NON-NLS-1$
140
	public static final String OPTION_ReportMethodCanBePotentiallyStatic = "org.eclipse.jdt.core.compiler.problem.reportMethodCanBePotentiallyStatic";  //$NON-NLS-1$
139
	public static final String OPTION_ReportRedundantSpecificationOfTypeArguments =  "org.eclipse.jdt.core.compiler.problem.redundantSpecificationOfTypeArguments"; //$NON-NLS-1$
141
	public static final String OPTION_ReportRedundantSpecificationOfTypeArguments =  "org.eclipse.jdt.core.compiler.problem.redundantSpecificationOfTypeArguments"; //$NON-NLS-1$
142
	public static final String OPTION_ReportUnclosedCloseable = "org.eclipse.jdt.core.compiler.problem.unclosedCloseable"; //$NON-NLS-1$
143
	public static final String OPTION_ReportPotentiallyUnclosedCloseable = "org.eclipse.jdt.core.compiler.problem.potentiallyUnclosedCloseable"; //$NON-NLS-1$
144
	public static final String OPTION_ReportExplicitlyClosedAutoCloseable = "org.eclipse.jdt.core.compiler.problem.explicitlyClosedAutoCloseable"; //$NON-NLS-1$
140
	/**
145
	/**
141
	 * Possible values for configurable options
146
	 * Possible values for configurable options
142
	 */
147
	 */
Lines 240-245 Link Here
240
	public static final int MethodCanBeStatic = IrritantSet.GROUP2 | ASTNode.Bit5;
245
	public static final int MethodCanBeStatic = IrritantSet.GROUP2 | ASTNode.Bit5;
241
	public static final int MethodCanBePotentiallyStatic = IrritantSet.GROUP2 | ASTNode.Bit6;
246
	public static final int MethodCanBePotentiallyStatic = IrritantSet.GROUP2 | ASTNode.Bit6;
242
	public static final int RedundantSpecificationOfTypeArguments = IrritantSet.GROUP2 | ASTNode.Bit7;
247
	public static final int RedundantSpecificationOfTypeArguments = IrritantSet.GROUP2 | ASTNode.Bit7;
248
	public static final int UnclosedCloseable = IrritantSet.GROUP2 | ASTNode.Bit8;
249
	public static final int PotentiallyUnclosedCloseable = IrritantSet.GROUP2 | ASTNode.Bit9;
250
	public static final int ExplicitlyClosedAutoCloseable = IrritantSet.GROUP2 | ASTNode.Bit10;
243
251
244
	// Severity level for handlers
252
	// Severity level for handlers
245
	/** 
253
	/** 
Lines 376-383 Link Here
376
		"javadoc", //$NON-NLS-1$
384
		"javadoc", //$NON-NLS-1$
377
		"nls", //$NON-NLS-1$
385
		"nls", //$NON-NLS-1$
378
		"null", //$NON-NLS-1$
386
		"null", //$NON-NLS-1$
379
		"restriction", //$NON-NLS-1$
380
		"rawtypes", //$NON-NLS-1$
387
		"rawtypes", //$NON-NLS-1$
388
		"resource", //$NON-NLS-1$
389
		"restriction", //$NON-NLS-1$		
381
		"serial", //$NON-NLS-1$
390
		"serial", //$NON-NLS-1$
382
		"static-access", //$NON-NLS-1$
391
		"static-access", //$NON-NLS-1$
383
		"static-method", //$NON-NLS-1$
392
		"static-method", //$NON-NLS-1$
Lines 551-556 Link Here
551
				return OPTION_ReportMethodCanBePotentiallyStatic;
560
				return OPTION_ReportMethodCanBePotentiallyStatic;
552
			case RedundantSpecificationOfTypeArguments :
561
			case RedundantSpecificationOfTypeArguments :
553
				return OPTION_ReportRedundantSpecificationOfTypeArguments;
562
				return OPTION_ReportRedundantSpecificationOfTypeArguments;
563
			case UnclosedCloseable :
564
				return OPTION_ReportUnclosedCloseable;
565
			case PotentiallyUnclosedCloseable :
566
				return OPTION_ReportPotentiallyUnclosedCloseable;
567
			case ExplicitlyClosedAutoCloseable :
568
				return OPTION_ReportExplicitlyClosedAutoCloseable;
554
		}
569
		}
555
		return null;
570
		return null;
556
	}
571
	}
Lines 714-719 Link Here
714
			OPTION_ReportUnusedTypeArgumentsForMethodInvocation,
729
			OPTION_ReportUnusedTypeArgumentsForMethodInvocation,
715
			OPTION_ReportUnusedWarningToken,
730
			OPTION_ReportUnusedWarningToken,
716
			OPTION_ReportVarargsArgumentNeedCast,
731
			OPTION_ReportVarargsArgumentNeedCast,
732
			OPTION_ReportUnclosedCloseable,
733
			OPTION_ReportPotentiallyUnclosedCloseable,
734
			OPTION_ReportExplicitlyClosedAutoCloseable,
717
		};
735
		};
718
		return result;
736
		return result;
719
	}
737
	}
Lines 784-793 Link Here
784
			case MethodCanBeStatic :
802
			case MethodCanBeStatic :
785
			case MethodCanBePotentiallyStatic :
803
			case MethodCanBePotentiallyStatic :
786
				return "static-method"; //$NON-NLS-1$
804
				return "static-method"; //$NON-NLS-1$
805
			case PotentiallyUnclosedCloseable:
806
			case UnclosedCloseable:
807
			case ExplicitlyClosedAutoCloseable:
808
				return "resource"; //$NON-NLS-1$
787
			case InvalidJavadoc :
809
			case InvalidJavadoc :
788
			case MissingJavadocComments :
810
			case MissingJavadocComments :
789
			case MissingJavadocTags:
811
			case MissingJavadocTags:
790
				return "javadoc"; //$NON-NLS-1$				
812
				return "javadoc"; //$NON-NLS-1$
791
		}
813
		}
792
		return null;
814
		return null;
793
	}
815
	}
Lines 841-846 Link Here
841
			case 'r' :
863
			case 'r' :
842
				if ("rawtypes".equals(warningToken)) //$NON-NLS-1$
864
				if ("rawtypes".equals(warningToken)) //$NON-NLS-1$
843
					return IrritantSet.RAW;
865
					return IrritantSet.RAW;
866
				if ("resource".equals(warningToken)) //$NON-NLS-1$
867
					return IrritantSet.RESOURCE;
844
				if ("restriction".equals(warningToken)) //$NON-NLS-1$
868
				if ("restriction".equals(warningToken)) //$NON-NLS-1$
845
					return IrritantSet.RESTRICTION;
869
					return IrritantSet.RESTRICTION;
846
				break;
870
				break;
Lines 980-985 Link Here
980
		optionsMap.put(OPTION_ReportMethodCanBeStatic, getSeverityString(MethodCanBeStatic));
1004
		optionsMap.put(OPTION_ReportMethodCanBeStatic, getSeverityString(MethodCanBeStatic));
981
		optionsMap.put(OPTION_ReportMethodCanBePotentiallyStatic, getSeverityString(MethodCanBePotentiallyStatic));
1005
		optionsMap.put(OPTION_ReportMethodCanBePotentiallyStatic, getSeverityString(MethodCanBePotentiallyStatic));
982
		optionsMap.put(OPTION_ReportRedundantSpecificationOfTypeArguments, getSeverityString(RedundantSpecificationOfTypeArguments));
1006
		optionsMap.put(OPTION_ReportRedundantSpecificationOfTypeArguments, getSeverityString(RedundantSpecificationOfTypeArguments));
1007
		optionsMap.put(OPTION_ReportUnclosedCloseable, getSeverityString(UnclosedCloseable));
1008
		optionsMap.put(OPTION_ReportPotentiallyUnclosedCloseable, getSeverityString(PotentiallyUnclosedCloseable));
1009
		optionsMap.put(OPTION_ReportExplicitlyClosedAutoCloseable, getSeverityString(ExplicitlyClosedAutoCloseable));
983
		return optionsMap;
1010
		return optionsMap;
984
	}
1011
	}
985
1012
Lines 1410-1415 Link Here
1410
		if ((optionValue = optionsMap.get(OPTION_ReportMethodCanBeStatic)) != null) updateSeverity(MethodCanBeStatic, optionValue);
1437
		if ((optionValue = optionsMap.get(OPTION_ReportMethodCanBeStatic)) != null) updateSeverity(MethodCanBeStatic, optionValue);
1411
		if ((optionValue = optionsMap.get(OPTION_ReportMethodCanBePotentiallyStatic)) != null) updateSeverity(MethodCanBePotentiallyStatic, optionValue);
1438
		if ((optionValue = optionsMap.get(OPTION_ReportMethodCanBePotentiallyStatic)) != null) updateSeverity(MethodCanBePotentiallyStatic, optionValue);
1412
		if ((optionValue = optionsMap.get(OPTION_ReportRedundantSpecificationOfTypeArguments)) != null) updateSeverity(RedundantSpecificationOfTypeArguments, optionValue);
1439
		if ((optionValue = optionsMap.get(OPTION_ReportRedundantSpecificationOfTypeArguments)) != null) updateSeverity(RedundantSpecificationOfTypeArguments, optionValue);
1440
		if ((optionValue = optionsMap.get(OPTION_ReportUnclosedCloseable)) != null) updateSeverity(UnclosedCloseable, optionValue);
1441
		if ((optionValue = optionsMap.get(OPTION_ReportPotentiallyUnclosedCloseable)) != null) updateSeverity(PotentiallyUnclosedCloseable, optionValue);
1442
		if ((optionValue = optionsMap.get(OPTION_ReportExplicitlyClosedAutoCloseable)) != null) updateSeverity(ExplicitlyClosedAutoCloseable, optionValue);
1413
1443
1414
		// Javadoc options
1444
		// Javadoc options
1415
		if ((optionValue = optionsMap.get(OPTION_DocCommentSupport)) != null) {
1445
		if ((optionValue = optionsMap.get(OPTION_DocCommentSupport)) != null) {
Lines 1625-1630 Link Here
1625
		buf.append("\n\t- method can be static: ").append(getSeverityString(MethodCanBeStatic)); //$NON-NLS-1$
1655
		buf.append("\n\t- method can be static: ").append(getSeverityString(MethodCanBeStatic)); //$NON-NLS-1$
1626
		buf.append("\n\t- method can be potentially static: ").append(getSeverityString(MethodCanBePotentiallyStatic)); //$NON-NLS-1$
1656
		buf.append("\n\t- method can be potentially static: ").append(getSeverityString(MethodCanBePotentiallyStatic)); //$NON-NLS-1$
1627
		buf.append("\n\t- redundant specification of type arguments: ").append(getSeverityString(RedundantSpecificationOfTypeArguments)); //$NON-NLS-1$
1657
		buf.append("\n\t- redundant specification of type arguments: ").append(getSeverityString(RedundantSpecificationOfTypeArguments)); //$NON-NLS-1$
1658
		buf.append("\n\t- resource is not closed: ").append(getSeverityString(UnclosedCloseable)); //$NON-NLS-1$
1659
		buf.append("\n\t- resource may not be closed: ").append(getSeverityString(PotentiallyUnclosedCloseable)); //$NON-NLS-1$
1660
		buf.append("\n\t- resource should be handled by try-with-resources: ").append(getSeverityString(ExplicitlyClosedAutoCloseable)); //$NON-NLS-1$
1628
		return buf.toString();
1661
		return buf.toString();
1629
	}
1662
	}
1630
	
1663
	
(-)compiler/org/eclipse/jdt/internal/compiler/impl/IrritantSet.java (-1 / +7 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 349326 - [1.7] new warning for missing try-with-resources
10
 *******************************************************************************/
11
 *******************************************************************************/
11
12
12
package org.eclipse.jdt.internal.compiler.impl;
13
package org.eclipse.jdt.internal.compiler.impl;
Lines 57-62 Link Here
57
	public static final IrritantSet UNUSED = new IrritantSet(CompilerOptions.UnusedLocalVariable);
58
	public static final IrritantSet UNUSED = new IrritantSet(CompilerOptions.UnusedLocalVariable);
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);
61
	public static final IrritantSet RESOURCE = new IrritantSet(CompilerOptions.UnclosedCloseable);
60
62
61
	public static final IrritantSet JAVADOC = new IrritantSet(CompilerOptions.InvalidJavadoc);
63
	public static final IrritantSet JAVADOC = new IrritantSet(CompilerOptions.InvalidJavadoc);
62
	public static final IrritantSet COMPILER_DEFAULT_ERRORS = new IrritantSet(0); // no optional error by default	
64
	public static final IrritantSet COMPILER_DEFAULT_ERRORS = new IrritantSet(0); // no optional error by default	
Lines 99-105 Link Here
99
			// group-2 warnings enabled by default
101
			// group-2 warnings enabled by default
100
			.set(
102
			.set(
101
				CompilerOptions.DeadCode
103
				CompilerOptions.DeadCode
102
				|CompilerOptions.Tasks);
104
				|CompilerOptions.Tasks
105
				|CompilerOptions.UnclosedCloseable);
103
			
106
			
104
		ALL.setAll();
107
		ALL.setAll();
105
		HIDING
108
		HIDING
Lines 124-129 Link Here
124
			.set(CompilerOptions.RedundantSpecificationOfTypeArguments);
127
			.set(CompilerOptions.RedundantSpecificationOfTypeArguments);
125
		STATIC_METHOD
128
		STATIC_METHOD
126
		    .set(CompilerOptions.MethodCanBePotentiallyStatic);
129
		    .set(CompilerOptions.MethodCanBePotentiallyStatic);
130
		RESOURCE
131
			.set(CompilerOptions.PotentiallyUnclosedCloseable)
132
			.set(CompilerOptions.ExplicitlyClosedAutoCloseable);
127
		String suppressRawWhenUnchecked = System.getProperty("suppressRawWhenUnchecked"); //$NON-NLS-1$
133
		String suppressRawWhenUnchecked = System.getProperty("suppressRawWhenUnchecked"); //$NON-NLS-1$
128
		if (suppressRawWhenUnchecked != null && "true".equalsIgnoreCase(suppressRawWhenUnchecked)) { //$NON-NLS-1$
134
		if (suppressRawWhenUnchecked != null && "true".equalsIgnoreCase(suppressRawWhenUnchecked)) { //$NON-NLS-1$
129
			UNCHECKED.set(CompilerOptions.RawTypeReference);
135
			UNCHECKED.set(CompilerOptions.RawTypeReference);
(-)compiler/org/eclipse/jdt/internal/compiler/lookup/BinaryTypeBinding.java (-2 / +21 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 349326 - [1.7] new warning for missing try-with-resources
10
 *******************************************************************************/
11
 *******************************************************************************/
11
package org.eclipse.jdt.internal.compiler.lookup;
12
package org.eclipse.jdt.internal.compiler.lookup;
12
13
Lines 971-976 Link Here
971
	variable.resolve();
972
	variable.resolve();
972
	return variable;
973
	return variable;
973
}
974
}
975
public boolean hasTypeBit(int bit) {
976
	// ensure hierarchy is resolved, which will propagate bits down to us
977
	superclass();
978
	superInterfaces();
979
	return (this.typeBits & bit) != 0;
980
}
974
private void initializeTypeVariable(TypeVariableBinding variable, TypeVariableBinding[] existingVariables, SignatureWrapper wrapper, char[][][] missingTypeNames) {
981
private void initializeTypeVariable(TypeVariableBinding variable, TypeVariableBinding[] existingVariables, SignatureWrapper wrapper, char[][][] missingTypeNames) {
975
	// ParameterSignature = Identifier ':' TypeSignature
982
	// ParameterSignature = Identifier ':' TypeSignature
976
	//   or Identifier ':' TypeSignature(optional) InterfaceBound(s)
983
	//   or Identifier ':' TypeSignature(optional) InterfaceBound(s)
Lines 1139-1146 Link Here
1139
	// finish resolving the type
1146
	// finish resolving the type
1140
	this.superclass = (ReferenceBinding) resolveType(this.superclass, this.environment, true /* raw conversion */);
1147
	this.superclass = (ReferenceBinding) resolveType(this.superclass, this.environment, true /* raw conversion */);
1141
	this.tagBits &= ~TagBits.HasUnresolvedSuperclass;
1148
	this.tagBits &= ~TagBits.HasUnresolvedSuperclass;
1142
	if (this.superclass.problemId() == ProblemReasons.NotFound)
1149
	if (this.superclass.problemId() == ProblemReasons.NotFound) {
1143
		this.tagBits |= TagBits.HierarchyHasProblems; // propagate type inconsistency
1150
		this.tagBits |= TagBits.HierarchyHasProblems; // propagate type inconsistency
1151
	} else {
1152
		// make super-type resolving recursive for propagating typeBits downwards
1153
		this.superclass.superclass();
1154
		this.superclass.superInterfaces();
1155
	}
1156
	this.typeBits |= this.superclass.typeBits;
1144
	return this.superclass;
1157
	return this.superclass;
1145
}
1158
}
1146
// NOTE: superInterfaces of binary types are resolved when needed
1159
// NOTE: superInterfaces of binary types are resolved when needed
Lines 1150-1157 Link Here
1150
1163
1151
	for (int i = this.superInterfaces.length; --i >= 0;) {
1164
	for (int i = this.superInterfaces.length; --i >= 0;) {
1152
		this.superInterfaces[i] = (ReferenceBinding) resolveType(this.superInterfaces[i], this.environment, true /* raw conversion */);
1165
		this.superInterfaces[i] = (ReferenceBinding) resolveType(this.superInterfaces[i], this.environment, true /* raw conversion */);
1153
		if (this.superInterfaces[i].problemId() == ProblemReasons.NotFound)
1166
		if (this.superInterfaces[i].problemId() == ProblemReasons.NotFound) {
1154
			this.tagBits |= TagBits.HierarchyHasProblems; // propagate type inconsistency
1167
			this.tagBits |= TagBits.HierarchyHasProblems; // propagate type inconsistency
1168
		} else {
1169
			// make super-type resolving recursive for propagating typeBits downwards
1170
			this.superInterfaces[i].superclass();
1171
			this.superInterfaces[i].superInterfaces();
1172
		}
1173
		this.typeBits |= this.superInterfaces[i].typeBits;
1155
	}
1174
	}
1156
	this.tagBits &= ~TagBits.HasUnresolvedSuperinterfaces;
1175
	this.tagBits &= ~TagBits.HasUnresolvedSuperinterfaces;
1157
	return this.superInterfaces;
1176
	return this.superInterfaces;
(-)compiler/org/eclipse/jdt/internal/compiler/lookup/BlockScope.java (+101 lines)
Lines 7-19 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 349326 - [1.7] new warning for missing try-with-resources
10
 *******************************************************************************/
11
 *******************************************************************************/
11
package org.eclipse.jdt.internal.compiler.lookup;
12
package org.eclipse.jdt.internal.compiler.lookup;
12
13
14
import java.util.ArrayList;
15
import java.util.List;
16
13
import org.eclipse.jdt.core.compiler.CharOperation;
17
import org.eclipse.jdt.core.compiler.CharOperation;
14
import org.eclipse.jdt.internal.compiler.ast.*;
18
import org.eclipse.jdt.internal.compiler.ast.*;
15
import org.eclipse.jdt.internal.compiler.classfmt.ClassFileConstants;
19
import org.eclipse.jdt.internal.compiler.classfmt.ClassFileConstants;
16
import org.eclipse.jdt.internal.compiler.codegen.CodeStream;
20
import org.eclipse.jdt.internal.compiler.codegen.CodeStream;
21
import org.eclipse.jdt.internal.compiler.flow.FlowContext;
22
import org.eclipse.jdt.internal.compiler.flow.FlowInfo;
17
import org.eclipse.jdt.internal.compiler.impl.Constant;
23
import org.eclipse.jdt.internal.compiler.impl.Constant;
18
import org.eclipse.jdt.internal.compiler.problem.ProblemReporter;
24
import org.eclipse.jdt.internal.compiler.problem.ProblemReporter;
19
25
Lines 957-960 Link Here
957
		}
963
		}
958
	}
964
	}
959
}
965
}
966
967
private List trackingVariables; // can be null if no resources are tracked
968
/**
969
 * Register a tracking variable and compute its id.
970
 */
971
public int registerTrackingVariable(FakedTrackingVariable fakedTrackingVariable) {
972
	if (this.trackingVariables == null)
973
		this.trackingVariables = new ArrayList();
974
	this.trackingVariables.add(fakedTrackingVariable);
975
	MethodScope outerMethodScope = outerMostMethodScope();
976
	return outerMethodScope.analysisIndex + (++outerMethodScope.trackVarCount);
977
	
978
}
979
/**
980
 * At the end of a block check the closing-status of all tracked closeables that are declared in this block. 
981
 */
982
public void checkUnclosedCloseables(FlowInfo flowInfo, FlowContext flowContext, ASTNode location) {
983
	if (this.trackingVariables == null) return;
984
	for (int i=0; i<this.trackingVariables.size(); i++) {
985
		FakedTrackingVariable trackingVar = (FakedTrackingVariable) this.trackingVariables.get(i);
986
		if (trackingVar.hasReportedProblem)
987
			continue;
988
		if (trackingVar.originalBinding != null && flowInfo.isDefinitelyNull(trackingVar.originalBinding))
989
			continue; // resource is null at this flow, don't complain
990
		int status = FlowContext.getNullStatusAfter(trackingVar.binding, flowInfo, flowContext);
991
		if (status == FlowInfo.NULL) {
992
			if (trackingVar.closedInNestedMethod)
993
				problemReporter().potentiallyUnclosedCloseable(trackingVar, location);
994
			else
995
				problemReporter().unclosedCloseable(trackingVar, location);
996
		} else if (status == FlowInfo.POTENTIALLY_NULL) {
997
			problemReporter().potentiallyUnclosedCloseable(trackingVar, location);
998
		} else if (status == FlowInfo.NON_NULL) {
999
			if (environment().globalOptions.complianceLevel >= ClassFileConstants.JDK1_7 
1000
					&& !trackingVar.isInsideTryWithResources)
1001
				problemReporter().explicitlyClosedAutoCloseable(trackingVar);
1002
		}
1003
	}
1004
}
1005
/**
1006
 * Find all tracking variables in scope that have relevant null status.
1007
 * @param moreTrackVars list for collecting all found tracking variables
1008
 * @param flowInfo use to check if tracking variable has interesting status
1009
 */
1010
public void getTrackVars(List moreTrackVars, FlowInfo flowInfo) {
1011
	if (this.trackingVariables != null) {
1012
		for (int i=0; i<this.trackingVariables.size(); i++) {
1013
			FakedTrackingVariable trackingVar = (FakedTrackingVariable) this.trackingVariables.get(i);
1014
			if (flowInfo.nullStatus(trackingVar.binding) == FlowInfo.UNKNOWN)
1015
				continue;
1016
			moreTrackVars.add(trackingVar);
1017
		}
1018
	}
1019
	if (this.parent instanceof BlockScope)
1020
		((BlockScope) this.parent).getTrackVars(moreTrackVars, flowInfo);
1021
}
1022
1023
/** 
1024
 * If one branch of an if-else closes any AutoCloseable resource, and if the same
1025
 * resource is known to be null on the other branch mark it as closed, too,
1026
 * so that merging both branches indicates that the resource is always closed.
1027
 * Example:
1028
 *	FileReader fr1 = null;
1029
 *	try {\n" +
1030
 *      fr1 = new FileReader(someFile);" + 
1031
 *		fr1.read(buf);\n" + 
1032
 *	} finally {\n" + 
1033
 *		if (fr1 != null)\n" +
1034
 *           try {\n" +
1035
 *               fr1.close();\n" +
1036
 *           } catch (IOException e) {
1037
 *              // do nothing 
1038
 *           }
1039
 *      // after this if statement fr1 is definitely not leaked 
1040
 *	}
1041
 */
1042
public void correlateTrackingVarsIfElse(FlowInfo thenFlowInfo, FlowInfo elseFlowInfo) {
1043
	if (this.trackingVariables != null) {
1044
		for (int i=0; i<this.trackingVariables.size(); i++) {
1045
			FakedTrackingVariable trackingVar = (FakedTrackingVariable) this.trackingVariables.get(i);
1046
			if (   thenFlowInfo.isDefinitelyNonNull(trackingVar.binding)			// closed in then branch
1047
				&& elseFlowInfo.isDefinitelyNull(trackingVar.originalBinding))		// null in else branch
1048
			{
1049
				elseFlowInfo.markAsDefinitelyNonNull(trackingVar.binding);			// -> always closed
1050
			}
1051
			else if (   elseFlowInfo.isDefinitelyNonNull(trackingVar.binding)		// closed in else branch
1052
					 && thenFlowInfo.isDefinitelyNull(trackingVar.originalBinding))	// null in then branch
1053
			{
1054
				thenFlowInfo.markAsDefinitelyNonNull(trackingVar.binding);			// -> always closed
1055
			}
1056
		}
1057
	}
1058
	if (this.parent instanceof BlockScope)
1059
		((BlockScope) this.parent).correlateTrackingVarsIfElse(thenFlowInfo, elseFlowInfo);
1060
}
960
}
1061
}
(-)compiler/org/eclipse/jdt/internal/compiler/lookup/ClassScope.java (+3 lines)
Lines 11-16 Link Here
11
 *     						Bug 328281 - visibility leaks not detected when analyzing unused field in private class
11
 *     						Bug 328281 - visibility leaks not detected when analyzing unused field in private class
12
 *     						Bug 300576 - NPE Computing type hierarchy when compliance doesn't match libraries
12
 *     						Bug 300576 - NPE Computing type hierarchy when compliance doesn't match libraries
13
 *     						Bug 354536 - compiling package-info.java still depends on the order of compilation units
13
 *     						Bug 354536 - compiling package-info.java still depends on the order of compilation units
14
 *     						Bug 349326 - [1.7] new warning for missing try-with-resources
14
 *******************************************************************************/
15
 *******************************************************************************/
15
package org.eclipse.jdt.internal.compiler.lookup;
16
package org.eclipse.jdt.internal.compiler.lookup;
16
17
Lines 908-913 Link Here
908
			} else {
909
			} else {
909
				// only want to reach here when no errors are reported
910
				// only want to reach here when no errors are reported
910
				sourceType.superclass = superclass;
911
				sourceType.superclass = superclass;
912
				sourceType.typeBits |= superclass.typeBits;
911
				return true;
913
				return true;
912
			}
914
			}
913
		}
915
		}
Lines 1023-1028 Link Here
1023
				noProblems &= superInterfaceRef.resolvedType.isValidBinding();
1025
				noProblems &= superInterfaceRef.resolvedType.isValidBinding();
1024
			}
1026
			}
1025
			// only want to reach here when no errors are reported
1027
			// only want to reach here when no errors are reported
1028
			sourceType.typeBits |= superInterface.typeBits;
1026
			interfaceBindings[count++] = superInterface;
1029
			interfaceBindings[count++] = superInterface;
1027
		}
1030
		}
1028
		// hold onto all correctly resolved superinterfaces
1031
		// hold onto all correctly resolved superinterfaces
(-)compiler/org/eclipse/jdt/internal/compiler/lookup/LocalVariableBinding.java (-1 / +6 lines)
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 <stephan@cs.tu-berlin.de> - Contribution for bug 185682 - Increment/decrement operators mark local variables as read
10
 *     Stephan Herrmann <stephan@cs.tu-berlin.de> - Contributions for
11
 *     							bug 185682 - Increment/decrement operators mark local variables as read
12
 *     							bug 349326 - [1.7] new warning for missing try-with-resources
11
 *******************************************************************************/
13
 *******************************************************************************/
12
package org.eclipse.jdt.internal.compiler.lookup;
14
package org.eclipse.jdt.internal.compiler.lookup;
13
15
Lines 15-20 Link Here
15
import org.eclipse.jdt.internal.compiler.ast.ASTNode;
17
import org.eclipse.jdt.internal.compiler.ast.ASTNode;
16
import org.eclipse.jdt.internal.compiler.ast.AbstractMethodDeclaration;
18
import org.eclipse.jdt.internal.compiler.ast.AbstractMethodDeclaration;
17
import org.eclipse.jdt.internal.compiler.ast.Annotation;
19
import org.eclipse.jdt.internal.compiler.ast.Annotation;
20
import org.eclipse.jdt.internal.compiler.ast.FakedTrackingVariable;
18
import org.eclipse.jdt.internal.compiler.ast.LocalDeclaration;
21
import org.eclipse.jdt.internal.compiler.ast.LocalDeclaration;
19
import org.eclipse.jdt.internal.compiler.ast.TypeDeclaration;
22
import org.eclipse.jdt.internal.compiler.ast.TypeDeclaration;
20
import org.eclipse.jdt.internal.compiler.impl.Constant;
23
import org.eclipse.jdt.internal.compiler.impl.Constant;
Lines 35-40 Link Here
35
	public int[] initializationPCs;
38
	public int[] initializationPCs;
36
	public int initializationCount = 0;
39
	public int initializationCount = 0;
37
40
41
	public FakedTrackingVariable closeTracker; // track closing of instances of type AutoCloseable, maybe null
42
38
	// for synthetic local variables
43
	// for synthetic local variables
39
	// if declaration slot is not positionned, the variable will not be listed in attribute
44
	// if declaration slot is not positionned, the variable will not be listed in attribute
40
	// note that the name of a variable should be chosen so as not to conflict with user ones (usually starting with a space char is all needed)
45
	// note that the name of a variable should be chosen so as not to conflict with user ones (usually starting with a space char is all needed)
(-)compiler/org/eclipse/jdt/internal/compiler/lookup/MethodScope.java (+4 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 349326 - [1.7] new warning for missing try-with-resources
10
 *******************************************************************************/
11
 *******************************************************************************/
11
package org.eclipse.jdt.internal.compiler.lookup;
12
package org.eclipse.jdt.internal.compiler.lookup;
12
13
Lines 49-54 Link Here
49
	// inner-emulation
50
	// inner-emulation
50
	public SyntheticArgumentBinding[] extraSyntheticArguments;
51
	public SyntheticArgumentBinding[] extraSyntheticArguments;
51
52
53
	// count number of tracking variables, see FakedTrackingVariable
54
	int trackVarCount;
55
52
public MethodScope(ClassScope parent, ReferenceContext context, boolean isStatic) {
56
public MethodScope(ClassScope parent, ReferenceContext context, boolean isStatic) {
53
	super(METHOD_SCOPE, parent);
57
	super(METHOD_SCOPE, parent);
54
	this.locals = new LocalVariableBinding[5];
58
	this.locals = new LocalVariableBinding[5];
(-)compiler/org/eclipse/jdt/internal/compiler/lookup/ParameterizedTypeBinding.java (+8 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 349326 - [1.7] new warning for missing try-with-resources
10
 *******************************************************************************/
11
 *******************************************************************************/
11
package org.eclipse.jdt.internal.compiler.lookup;
12
package org.eclipse.jdt.internal.compiler.lookup;
12
13
Lines 629-634 Link Here
629
	    return this.type.hasMemberTypes();
630
	    return this.type.hasMemberTypes();
630
	}
631
	}
631
632
633
	public boolean hasTypeBit(int bit) {
634
		TypeBinding erasure = erasure();
635
		if (erasure instanceof ReferenceBinding)
636
			return ((ReferenceBinding) erasure).hasTypeBit(bit);
637
		return false;
638
	}
639
632
	/**
640
	/**
633
	 * @see org.eclipse.jdt.internal.compiler.lookup.ReferenceBinding#implementsMethod(MethodBinding)
641
	 * @see org.eclipse.jdt.internal.compiler.lookup.ReferenceBinding#implementsMethod(MethodBinding)
634
	 */
642
	 */
(-)compiler/org/eclipse/jdt/internal/compiler/lookup/ProblemReferenceBinding.java (+7 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 349326 - [1.7] new warning for missing try-with-resources
10
 *******************************************************************************/
11
 *******************************************************************************/
11
package org.eclipse.jdt.internal.compiler.lookup;
12
package org.eclipse.jdt.internal.compiler.lookup;
12
13
Lines 40-45 Link Here
40
	return this.closestMatch;
41
	return this.closestMatch;
41
}
42
}
42
43
44
public boolean hasTypeBit(int bit) {
45
	if (this.closestMatch != null)
46
		return this.closestMatch.hasTypeBit(bit);
47
	return false;
48
}
49
43
/* API
50
/* API
44
* Answer the problem id associated with the receiver.
51
* Answer the problem id associated with the receiver.
45
* NoError if the receiver is a valid binding.
52
* NoError if the receiver is a valid binding.
(-)compiler/org/eclipse/jdt/internal/compiler/lookup/ReferenceBinding.java (-2 / +11 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 349326 - [1.7] new warning for missing try-with-resources
10
 *******************************************************************************/
11
 *******************************************************************************/
11
package org.eclipse.jdt.internal.compiler.lookup;
12
package org.eclipse.jdt.internal.compiler.lookup;
12
13
Lines 41-47 Link Here
41
42
42
	private SimpleLookupTable compatibleCache;
43
	private SimpleLookupTable compatibleCache;
43
44
44
	public static final ReferenceBinding LUB_GENERIC = new ReferenceBinding() { /* used for lub computation */};
45
	int typeBits; // additional bits characterizing this type
46
47
	public static final ReferenceBinding LUB_GENERIC = new ReferenceBinding() { /* used for lub computation */
48
		public boolean hasTypeBit(int bit) { return false; }
49
	};
45
50
46
	private static final Comparator FIELD_COMPARATOR = new Comparator() {
51
	private static final Comparator FIELD_COMPARATOR = new Comparator() {
47
		public int compare(Object o1, Object o2) {
52
		public int compare(Object o1, Object o2) {
Lines 424-431 Link Here
424
				case 'A' :
429
				case 'A' :
425
					switch(typeName.length) {
430
					switch(typeName.length) {
426
						case 13 :
431
						case 13 :
427
							if (CharOperation.equals(typeName, TypeConstants.JAVA_LANG_AUTOCLOSEABLE[2]))
432
							if (CharOperation.equals(typeName, TypeConstants.JAVA_LANG_AUTOCLOSEABLE[2])) {
428
								this.id = TypeIds.T_JavaLangAutoCloseable;
433
								this.id = TypeIds.T_JavaLangAutoCloseable;
434
								this.typeBits |= TypeIds.BitAutoCloseable; 
435
							}
429
							return;
436
							return;
430
						case 14:
437
						case 14:
431
							if (CharOperation.equals(typeName, TypeConstants.JAVA_LANG_ASSERTIONERROR[2]))
438
							if (CharOperation.equals(typeName, TypeConstants.JAVA_LANG_ASSERTIONERROR[2]))
Lines 923-928 Link Here
923
public final boolean hasRestrictedAccess() {
930
public final boolean hasRestrictedAccess() {
924
	return (this.modifiers & ExtraCompilerModifiers.AccRestrictedAccess) != 0;
931
	return (this.modifiers & ExtraCompilerModifiers.AccRestrictedAccess) != 0;
925
}
932
}
933
/** Answer an additional bit characterizing this type, like {@link TypeIds#BitAutoCloseable}. */
934
abstract public boolean hasTypeBit(int bit);
926
935
927
/** Answer true if the receiver implements anInterface or is identical to anInterface.
936
/** Answer true if the receiver implements anInterface or is identical to anInterface.
928
* If searchHierarchy is true, then also search the receiver's superclasses.
937
* If searchHierarchy is true, then also search the receiver's superclasses.
(-)compiler/org/eclipse/jdt/internal/compiler/lookup/SourceTypeBinding.java (-1 / +8 lines)
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 <stephan@cs.tu-berlin.de> - Contribution for bug 328281 - visibility leaks not detected when analyzing unused field in private class
10
 *     Stephan Herrmann <stephan@cs.tu-berlin.de> - Contributions for
11
 *     							bug 328281 - visibility leaks not detected when analyzing unused field in private class
12
 *     							bug 349326 - [1.7] new warning for missing try-with-resources
11
 *******************************************************************************/
13
 *******************************************************************************/
12
package org.eclipse.jdt.internal.compiler.lookup;
14
package org.eclipse.jdt.internal.compiler.lookup;
13
15
Lines 1063-1068 Link Here
1063
	return accessors[1];
1065
	return accessors[1];
1064
}
1066
}
1065
1067
1068
public boolean hasTypeBit(int bit) {
1069
	// source types initialize type bits during connectSuperclass/interfaces()
1070
	return (this.typeBits & bit) != 0;
1071
}
1072
1066
/**
1073
/**
1067
 * @see org.eclipse.jdt.internal.compiler.lookup.Binding#initializeDeprecatedAnnotationTagBits()
1074
 * @see org.eclipse.jdt.internal.compiler.lookup.Binding#initializeDeprecatedAnnotationTagBits()
1068
 */
1075
 */
(-)compiler/org/eclipse/jdt/internal/compiler/lookup/TypeConstants.java (+2 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 349326 - [1.7] new warning for missing try-with-resources
10
 *******************************************************************************/
11
 *******************************************************************************/
11
package org.eclipse.jdt.internal.compiler.lookup;
12
package org.eclipse.jdt.internal.compiler.lookup;
12
13
Lines 150-155 Link Here
150
			"MethodHandle$PolymorphicSignature".toCharArray() //$NON-NLS-1$
151
			"MethodHandle$PolymorphicSignature".toCharArray() //$NON-NLS-1$
151
	};
152
	};
152
	char[][] JAVA_LANG_AUTOCLOSEABLE =  {JAVA, LANG, "AutoCloseable".toCharArray()}; //$NON-NLS-1$
153
	char[][] JAVA_LANG_AUTOCLOSEABLE =  {JAVA, LANG, "AutoCloseable".toCharArray()}; //$NON-NLS-1$
154
	char[] CLOSE = "close".toCharArray(); //$NON-NLS-1$
153
155
154
	// Constraints for generic type argument inference
156
	// Constraints for generic type argument inference
155
	int CONSTRAINT_EQUAL = 0;		// Actual = Formal
157
	int CONSTRAINT_EQUAL = 0;		// Actual = Formal
(-)compiler/org/eclipse/jdt/internal/compiler/lookup/TypeIds.java (+7 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 349326 - [1.7] new warning for missing try-with-resources
10
 *******************************************************************************/
11
 *******************************************************************************/
11
package org.eclipse.jdt.internal.compiler.lookup;
12
package org.eclipse.jdt.internal.compiler.lookup;
12
13
Lines 177-180 Link Here
177
	final int Object2boolean = T_JavaLangObject + (T_boolean << 4);
178
	final int Object2boolean = T_JavaLangObject + (T_boolean << 4);
178
	final int BOXING = 0x200;
179
	final int BOXING = 0x200;
179
	final int UNBOXING = 0x400;
180
	final int UNBOXING = 0x400;
181
182
	/** 
183
	 * Marks all sub-types of java.lang.AutoCloseable.
184
	 * @see ReferenceBinding#hasTypeBit(int)
185
	 */
186
	final int BitAutoCloseable = 1;
180
}
187
}
(-)compiler/org/eclipse/jdt/internal/compiler/lookup/TypeVariableBinding.java (-2 / +18 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 <stephan@cs.tu-berlin.de> - Contribution for bug 282152 - [1.5][compiler] Generics code rejected by Eclipse but accepted by javac
10
 *     Stephan Herrmann <stephan@cs.tu-berlin.de> - Contributions for
11
 *     							bug 282152 - [1.5][compiler] Generics code rejected by Eclipse but accepted by javac
12
 *     							bug 349326 - [1.7] new warning for missing try-with-resources
11
 *******************************************************************************/
13
 *******************************************************************************/
12
package org.eclipse.jdt.internal.compiler.lookup;
14
package org.eclipse.jdt.internal.compiler.lookup;
13
15
Lines 42-47 Link Here
42
		this.modifiers = ClassFileConstants.AccPublic | ExtraCompilerModifiers.AccGenericSignature; // treat type var as public
44
		this.modifiers = ClassFileConstants.AccPublic | ExtraCompilerModifiers.AccGenericSignature; // treat type var as public
43
		this.tagBits |= TagBits.HasTypeVariable;
45
		this.tagBits |= TagBits.HasTypeVariable;
44
		this.environment = environment;
46
		this.environment = environment;
47
		this.typeBits = -1;
45
	}
48
	}
46
49
47
	/**
50
	/**
Lines 307-312 Link Here
307
		return true;
310
		return true;
308
	}
311
	}
309
312
313
	public boolean hasTypeBit(int bit) {
314
		if (this.typeBits == -1) {
315
			// initialize from bounds
316
			this.typeBits = 0;
317
			if (this.superclass != null)
318
				this.typeBits |= this.superclass.typeBits;
319
			if (this.superInterfaces != null)
320
				for (int i = 0, l = this.superInterfaces.length; i < l; i++)
321
					this.typeBits |= this.superInterfaces[i].typeBits;
322
		}
323
		return (this.typeBits & bit) != 0;
324
	}
325
310
	/**
326
	/**
311
	 * Returns true if the type variable is directly bound to a given type
327
	 * Returns true if the type variable is directly bound to a given type
312
	 */
328
	 */
(-)compiler/org/eclipse/jdt/internal/compiler/lookup/UnresolvedReferenceBinding.java (-1 / +6 lines)
Lines 1-5 Link Here
1
/*******************************************************************************
1
/*******************************************************************************
2
 * Copyright (c) 2000, 2008 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 349326 - [1.7] new warning for missing try-with-resources
10
 *******************************************************************************/
11
 *******************************************************************************/
11
package org.eclipse.jdt.internal.compiler.lookup;
12
package org.eclipse.jdt.internal.compiler.lookup;
12
13
Lines 41-46 Link Here
41
public String debugName() {
42
public String debugName() {
42
	return toString();
43
	return toString();
43
}
44
}
45
public boolean hasTypeBit(int bit) {
46
	// shouldn't happen since we are not called before analyseCode(), but play safe:
47
	return false;
48
}
44
ReferenceBinding resolve(LookupEnvironment environment, boolean convertGenericToRawType) {
49
ReferenceBinding resolve(LookupEnvironment environment, boolean convertGenericToRawType) {
45
    ReferenceBinding targetType = this.resolvedType;
50
    ReferenceBinding targetType = this.resolvedType;
46
	if (targetType == null) {
51
	if (targetType == null) {
(-)compiler/org/eclipse/jdt/internal/compiler/lookup/WildcardBinding.java (-1 / +16 lines)
Lines 1-5 Link Here
1
/*******************************************************************************
1
/*******************************************************************************
2
 * Copyright (c) 2005, 2009 IBM Corporation and others.
2
 * Copyright (c) 2005, 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 349326 - [1.7] new warning for missing try-with-resources
10
 *******************************************************************************/
11
 *******************************************************************************/
11
package org.eclipse.jdt.internal.compiler.lookup;
12
package org.eclipse.jdt.internal.compiler.lookup;
12
13
Lines 54-59 Link Here
54
		if (bound instanceof UnresolvedReferenceBinding)
55
		if (bound instanceof UnresolvedReferenceBinding)
55
			((UnresolvedReferenceBinding) bound).addWrapper(this, environment);
56
			((UnresolvedReferenceBinding) bound).addWrapper(this, environment);
56
		this.tagBits |=  TagBits.HasUnresolvedTypeVariables; // cleared in resolve()
57
		this.tagBits |=  TagBits.HasUnresolvedTypeVariables; // cleared in resolve()
58
		this.typeBits = -1;
57
	}
59
	}
58
60
59
	public int kind() {
61
	public int kind() {
Lines 420-425 Link Here
420
		return this.genericType.hashCode();
422
		return this.genericType.hashCode();
421
	}
423
	}
422
424
425
	public boolean hasTypeBit(int bit) {
426
		if (this.typeBits == -1) {
427
			// initialize from upper bounds
428
			this.typeBits = 0;
429
			if (this.superclass != null)
430
				this.typeBits |= this.superclass.typeBits;
431
			if (this.superInterfaces != null)
432
				for (int i = 0, l = this.superInterfaces.length; i < l; i++)
433
					this.typeBits |= this.superInterfaces[i].typeBits;
434
		}
435
		return (this.typeBits & bit) != 0;
436
	}
437
423
	void initialize(ReferenceBinding someGenericType, TypeBinding someBound, TypeBinding[] someOtherBounds) {
438
	void initialize(ReferenceBinding someGenericType, TypeBinding someBound, TypeBinding[] someOtherBounds) {
424
		this.genericType = someGenericType;
439
		this.genericType = someGenericType;
425
		this.bound = someBound;
440
		this.bound = someBound;
(-)compiler/org/eclipse/jdt/internal/compiler/problem/ProblemReporter.java (+61 lines)
Lines 11-16 Link Here
11
 *     Stephan Herrmann  - Contributions for 
11
 *     Stephan Herrmann  - Contributions for 
12
 *     						bug 236385 - 
12
 *     						bug 236385 - 
13
 *     						bug 338303 - Warning about Redundant assignment conflicts with definite assignment
13
 *     						bug 338303 - Warning about Redundant assignment conflicts with definite assignment
14
 *     						bug 349326 - [1.7] new warning for missing try-with-resources
14
 *******************************************************************************/
15
 *******************************************************************************/
15
package org.eclipse.jdt.internal.compiler.problem;
16
package org.eclipse.jdt.internal.compiler.problem;
16
17
Lines 51-56 Link Here
51
import org.eclipse.jdt.internal.compiler.ast.EqualExpression;
52
import org.eclipse.jdt.internal.compiler.ast.EqualExpression;
52
import org.eclipse.jdt.internal.compiler.ast.ExplicitConstructorCall;
53
import org.eclipse.jdt.internal.compiler.ast.ExplicitConstructorCall;
53
import org.eclipse.jdt.internal.compiler.ast.Expression;
54
import org.eclipse.jdt.internal.compiler.ast.Expression;
55
import org.eclipse.jdt.internal.compiler.ast.FakedTrackingVariable;
54
import org.eclipse.jdt.internal.compiler.ast.FieldDeclaration;
56
import org.eclipse.jdt.internal.compiler.ast.FieldDeclaration;
55
import org.eclipse.jdt.internal.compiler.ast.FieldReference;
57
import org.eclipse.jdt.internal.compiler.ast.FieldReference;
56
import org.eclipse.jdt.internal.compiler.ast.ImportReference;
58
import org.eclipse.jdt.internal.compiler.ast.ImportReference;
Lines 426-431 Link Here
426
			
428
			
427
		case IProblem.MethodCanBePotentiallyStatic:
429
		case IProblem.MethodCanBePotentiallyStatic:
428
			return CompilerOptions.MethodCanBePotentiallyStatic;
430
			return CompilerOptions.MethodCanBePotentiallyStatic;
431
432
		case IProblem.UnclosedCloseable:
433
		case IProblem.UnclosedCloseableAtExit:
434
			return CompilerOptions.UnclosedCloseable;
435
		case IProblem.PotentiallyUnclosedCloseable:
436
		case IProblem.PotentiallyUnclosedCloseableAtExit:
437
			return CompilerOptions.PotentiallyUnclosedCloseable;
438
		case IProblem.ExplicitlyClosedAutoCloseable:
439
			return CompilerOptions.ExplicitlyClosedAutoCloseable;
429
				
440
				
430
		case IProblem.RedundantSpecificationOfTypeArguments:
441
		case IProblem.RedundantSpecificationOfTypeArguments:
431
			return CompilerOptions.RedundantSpecificationOfTypeArguments;
442
			return CompilerOptions.RedundantSpecificationOfTypeArguments;
Lines 461-466 Link Here
461
			case CompilerOptions.ParameterAssignment :
472
			case CompilerOptions.ParameterAssignment :
462
			case CompilerOptions.MethodCanBeStatic :
473
			case CompilerOptions.MethodCanBeStatic :
463
			case CompilerOptions.MethodCanBePotentiallyStatic :
474
			case CompilerOptions.MethodCanBePotentiallyStatic :
475
			case CompilerOptions.ExplicitlyClosedAutoCloseable :
464
				return CategorizedProblem.CAT_CODE_STYLE;
476
				return CategorizedProblem.CAT_CODE_STYLE;
465
477
466
			case CompilerOptions.MaskedCatchBlock :
478
			case CompilerOptions.MaskedCatchBlock :
Lines 482-487 Link Here
482
			case CompilerOptions.ShouldImplementHashcode :
494
			case CompilerOptions.ShouldImplementHashcode :
483
			case CompilerOptions.DeadCode :
495
			case CompilerOptions.DeadCode :
484
			case CompilerOptions.UnusedObjectAllocation :
496
			case CompilerOptions.UnusedObjectAllocation :
497
			case CompilerOptions.UnclosedCloseable :
498
			case CompilerOptions.PotentiallyUnclosedCloseable :
485
				return CategorizedProblem.CAT_POTENTIAL_PROGRAMMING_PROBLEM;
499
				return CategorizedProblem.CAT_POTENTIAL_PROGRAMMING_PROBLEM;
486
			
500
			
487
			case CompilerOptions.OverriddenPackageDefaultMethod :
501
			case CompilerOptions.OverriddenPackageDefaultMethod :
Lines 7906-7909 Link Here
7906
			location.sourceEnd);
7920
			location.sourceEnd);
7907
    }
7921
    }
7908
}
7922
}
7923
public void potentiallyUnclosedCloseable(FakedTrackingVariable trackVar, ASTNode location) {
7924
	String[] args = { String.valueOf(trackVar.name) };
7925
	if (location == null) {
7926
		this.handle(
7927
			IProblem.PotentiallyUnclosedCloseable,
7928
			args,
7929
			args,
7930
			trackVar.sourceStart,
7931
			trackVar.sourceEnd);
7932
	} else {
7933
		this.handle(
7934
			IProblem.PotentiallyUnclosedCloseableAtExit,
7935
			args,
7936
			args,
7937
			location.sourceStart,
7938
			location.sourceEnd);
7939
	}
7940
	trackVar.hasReportedProblem = true;
7941
}
7942
public void unclosedCloseable(FakedTrackingVariable trackVar, ASTNode location) {
7943
	String[] args = { String.valueOf(trackVar.name) };
7944
	if (location == null) {
7945
		this.handle(
7946
			IProblem.UnclosedCloseable,
7947
			args,
7948
			args,
7949
			trackVar.sourceStart,
7950
			trackVar.sourceEnd);
7951
	} else {
7952
		this.handle(
7953
			IProblem.UnclosedCloseableAtExit,
7954
			args,
7955
			args,
7956
			location.sourceStart,
7957
			location.sourceEnd);
7958
	}
7959
	trackVar.hasReportedProblem = true;
7960
}
7961
public void explicitlyClosedAutoCloseable(FakedTrackingVariable trackVar) {
7962
	String[] args = { String.valueOf(trackVar.name) };
7963
	this.handle(
7964
		IProblem.ExplicitlyClosedAutoCloseable,
7965
		args,
7966
		args,
7967
		trackVar.sourceStart,
7968
		trackVar.sourceEnd);	
7969
}
7909
}
7970
}
(-)compiler/org/eclipse/jdt/internal/compiler/problem/messages.properties (-1 / +8 lines)
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 349326 - [1.7] new warning for missing try-with-resources
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 643-648 Link Here
643
882 = Unhandled exception type {0} thrown by automatic close() invocation on {1}
645
882 = Unhandled exception type {0} thrown by automatic close() invocation on {1}
644
883 = '<>' operator is not allowed for source level below 1.7
646
883 = '<>' operator is not allowed for source level below 1.7
645
884 = Redundant specification of type arguments <{0}>
647
884 = Redundant specification of type arguments <{0}>
648
885 = Potentially leaking resource '{0}': is not closed on all paths
649
886 = Potentially leaking resource '{0}': may not be closed at this location
650
887 = Leaking resource '{0}': is never closed
651
888 = Leaking resource '{0}': is not closed at this location
652
889 = Resource '{0}' should be managed by try-with-resource
646
653
647
### ELABORATIONS
654
### ELABORATIONS
648
## Access restrictions
655
## Access restrictions
(-)model/org/eclipse/jdt/core/JavaCore.java (+50 lines)
Lines 83-88 Link Here
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 COMPILER_PB_UNUSED_OBJECT_ALLOCATION
85
 *     Stephan Herrmann  - added COMPILER_PB_SUPPRESS_OPTIONAL_ERRORS
85
 *     Stephan Herrmann  - added COMPILER_PB_SUPPRESS_OPTIONAL_ERRORS
86
 *     Stephan Herrmann  - added the following constants:
87
 *     								COMPILER_PB_UNCLOSED_CLOSEABLE,
88
 *     								COMPILER_PB_POTENTIALLY_UNCLOSED_CLOSEABLE
89
 *     								COMPILER_PB_EXPLICITLY_CLOSED_AUTOCLOSEABLE
86
 *******************************************************************************/
90
 *******************************************************************************/
87
91
88
package org.eclipse.jdt.core;
92
package org.eclipse.jdt.core;
Lines 1357-1362 Link Here
1357
	 */
1361
	 */
1358
	public static final String COMPILER_PB_POTENTIALLY_MISSING_STATIC_ON_METHOD = PLUGIN_ID + ".compiler.problem.reportMethodCanBePotentiallyStatic"; //$NON-NLS-1$
1362
	public static final String COMPILER_PB_POTENTIALLY_MISSING_STATIC_ON_METHOD = PLUGIN_ID + ".compiler.problem.reportMethodCanBePotentiallyStatic"; //$NON-NLS-1$
1359
	/**
1363
	/**
1364
	 * Compiler option ID: Reporting a resource that is not closed properly.
1365
	 * <p>When enabled, that compiler will issue an error or a warning if
1366
	 *    a local variable holds a value of type AutoCloseable and if
1367
	 *    flow analysis shows that the method <code>close()</code> is not invoked locally on that value.
1368
	 * <dl>
1369
	 * <dt>Option id:</dt><dd><code>"org.eclipse.jdt.core.compiler.problem.reportUnclosedCloseable"</code></dd>
1370
	 * <dt>Possible values:</dt><dd><code>{ "error", "warning", "ignore" }</code></dd>
1371
	 * <dt>Default:</dt><dd><code>"warning"</code></dd>
1372
	 * </dl>
1373
	 * @since 3.8
1374
	 * @category CompilerOptionID
1375
	 */
1376
	public static final String COMPILER_PB_UNCLOSED_CLOSEABLE = PLUGIN_ID + ".compiler.problem.unclosedCloseable"; //$NON-NLS-1$
1377
	/**
1378
	 * Compiler option ID: Reporting a resource that may not be closed properly.
1379
	 * <p>When enabled, that compiler will issue an error or a warning if
1380
	 *    a local variable holds a value of type AutoCloseable and if
1381
	 *    flow analysis shows that the method <code>close()</code> is 
1382
	 *    not invoked locally on that value for all execution paths.
1383
	 * <dl>
1384
	 * <dt>Option id:</dt><dd><code>"org.eclipse.jdt.core.compiler.problem.reportPotentiallyUnclosedCloseable"</code></dd>
1385
	 * <dt>Possible values:</dt><dd><code>{ "error", "warning", "ignore" }</code></dd>
1386
	 * <dt>Default:</dt><dd><code>"ignore"</code></dd>
1387
	 * </dl>
1388
	 * @since 3.8
1389
	 * @category CompilerOptionID
1390
	 */
1391
	public static final String COMPILER_PB_POTENTIALLY_UNCLOSED_CLOSEABLE = PLUGIN_ID + ".compiler.problem.potentiallyUnclosedCloseable"; //$NON-NLS-1$
1392
	/**
1393
	 * Compiler option ID: Reporting a resource that is not managed by try-with-resources.
1394
	 * <p>When enabled, that compiler will issue an error or a warning if a local variable 
1395
	 * 	  holds a value of type AutoCloseable, and if the method <code>close()</code> is
1396
	 * 	  explicitly invoked on that resource, but the resource is not managed by a
1397
	 * 	  try-with-resources block.
1398
	 * <p>Note that this option is not intended to be surfaced in the UI, as it is intended
1399
	 *    only for internal use for computing quick assists / cleanups. 
1400
	 * <dl>
1401
	 * <dt>Option id:</dt><dd><code>"org.eclipse.jdt.core.compiler.problem.reportPotentiallyUnclosedCloseable"</code></dd>
1402
	 * <dt>Possible values:</dt><dd><code>{ "error", "warning", "ignore" }</code></dd>
1403
	 * <dt>Default:</dt><dd><code>"ignore"</code></dd>
1404
	 * </dl>
1405
	 * @since 3.8
1406
	 * @category CompilerOptionID
1407
	 */
1408
	public static final String COMPILER_PB_EXPLICITLY_CLOSED_AUTOCLOSEABLE = PLUGIN_ID + ".compiler.problem.explicitlyClosedAutoCloseable"; //$NON-NLS-1$
1409
	/**
1360
	 * Compiler option ID: Setting Source Compatibility Mode.
1410
	 * Compiler option ID: Setting Source Compatibility Mode.
1361
	 * <p>Specify whether which source level compatibility is used. From 1.4 on, <code>'assert'</code> is a keyword
1411
	 * <p>Specify whether which source level compatibility is used. From 1.4 on, <code>'assert'</code> is a keyword
1362
	 *    reserved for assertion support. Also note, than when toggling to 1.4 mode, the target VM
1412
	 *    reserved for assertion support. Also note, than when toggling to 1.4 mode, the target VM
(-)src/org/eclipse/jdt/core/tests/compiler/regression/BatchCompilerTest.java (-3 / +8 lines)
Lines 8-16 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 <stephan@cs.tu-berlin.de> - 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
 *     Stephan Herrmann <stephan@cs.tu-berlin.de> - Contribution for bug 185682 - Increment/decrement operators mark local variables as read
13
 *     							bug 295551 - Add option to automatically promote all warnings to errors
14
 *     							bug 185682 - Increment/decrement operators mark local variables as read
15
 *     							bug 349326 - [1.7] new warning for missing try-with-resources
14
 *******************************************************************************/
16
 *******************************************************************************/
15
package org.eclipse.jdt.core.tests.compiler.regression;
17
package org.eclipse.jdt.core.tests.compiler.regression;
16
18
Lines 1816-1821 Link Here
1816
			"		<option key=\"org.eclipse.jdt.core.compiler.problem.discouragedReference\" value=\"warning\"/>\n" + 
1818
			"		<option key=\"org.eclipse.jdt.core.compiler.problem.discouragedReference\" value=\"warning\"/>\n" + 
1817
			"		<option key=\"org.eclipse.jdt.core.compiler.problem.emptyStatement\" value=\"ignore\"/>\n" + 
1819
			"		<option key=\"org.eclipse.jdt.core.compiler.problem.emptyStatement\" value=\"ignore\"/>\n" + 
1818
			"		<option key=\"org.eclipse.jdt.core.compiler.problem.enumIdentifier\" value=\"warning\"/>\n" + 
1820
			"		<option key=\"org.eclipse.jdt.core.compiler.problem.enumIdentifier\" value=\"warning\"/>\n" + 
1821
			"		<option key=\"org.eclipse.jdt.core.compiler.problem.explicitlyClosedAutoCloseable\" value=\"ignore\"/>\n" + 
1819
			"		<option key=\"org.eclipse.jdt.core.compiler.problem.fallthroughCase\" value=\"ignore\"/>\n" + 
1822
			"		<option key=\"org.eclipse.jdt.core.compiler.problem.fallthroughCase\" value=\"ignore\"/>\n" + 
1820
			"		<option key=\"org.eclipse.jdt.core.compiler.problem.fatalOptionalError\" value=\"disabled\"/>\n" + 
1823
			"		<option key=\"org.eclipse.jdt.core.compiler.problem.fatalOptionalError\" value=\"disabled\"/>\n" + 
1821
			"		<option key=\"org.eclipse.jdt.core.compiler.problem.fieldHiding\" value=\"ignore\"/>\n" + 
1824
			"		<option key=\"org.eclipse.jdt.core.compiler.problem.fieldHiding\" value=\"ignore\"/>\n" + 
Lines 1857-1862 Link Here
1857
			"		<option key=\"org.eclipse.jdt.core.compiler.problem.parameterAssignment\" value=\"ignore\"/>\n" + 
1860
			"		<option key=\"org.eclipse.jdt.core.compiler.problem.parameterAssignment\" value=\"ignore\"/>\n" + 
1858
			"		<option key=\"org.eclipse.jdt.core.compiler.problem.possibleAccidentalBooleanAssignment\" value=\"ignore\"/>\n" + 
1861
			"		<option key=\"org.eclipse.jdt.core.compiler.problem.possibleAccidentalBooleanAssignment\" value=\"ignore\"/>\n" + 
1859
			"		<option key=\"org.eclipse.jdt.core.compiler.problem.potentialNullReference\" value=\"ignore\"/>\n" + 
1862
			"		<option key=\"org.eclipse.jdt.core.compiler.problem.potentialNullReference\" value=\"ignore\"/>\n" + 
1863
			"		<option key=\"org.eclipse.jdt.core.compiler.problem.potentiallyUnclosedCloseable\" value=\"ignore\"/>\n" +
1860
			"		<option key=\"org.eclipse.jdt.core.compiler.problem.rawTypeReference\" value=\"warning\"/>\n" +
1864
			"		<option key=\"org.eclipse.jdt.core.compiler.problem.rawTypeReference\" value=\"warning\"/>\n" +
1861
			"		<option key=\"org.eclipse.jdt.core.compiler.problem.redundantNullCheck\" value=\"ignore\"/>\n" + 
1865
			"		<option key=\"org.eclipse.jdt.core.compiler.problem.redundantNullCheck\" value=\"ignore\"/>\n" + 
1862
			"		<option key=\"org.eclipse.jdt.core.compiler.problem.redundantSpecificationOfTypeArguments\" value=\"ignore\"/>\n" + 
1866
			"		<option key=\"org.eclipse.jdt.core.compiler.problem.redundantSpecificationOfTypeArguments\" value=\"ignore\"/>\n" + 
Lines 1872-1877 Link Here
1872
			"		<option key=\"org.eclipse.jdt.core.compiler.problem.typeParameterHiding\" value=\"warning\"/>\n" + 
1876
			"		<option key=\"org.eclipse.jdt.core.compiler.problem.typeParameterHiding\" value=\"warning\"/>\n" + 
1873
			"		<option key=\"org.eclipse.jdt.core.compiler.problem.unavoidableGenericTypeProblems\" value=\"enabled\"/>\n" +
1877
			"		<option key=\"org.eclipse.jdt.core.compiler.problem.unavoidableGenericTypeProblems\" value=\"enabled\"/>\n" +
1874
			"		<option key=\"org.eclipse.jdt.core.compiler.problem.uncheckedTypeOperation\" value=\"warning\"/>\n" + 
1878
			"		<option key=\"org.eclipse.jdt.core.compiler.problem.uncheckedTypeOperation\" value=\"warning\"/>\n" + 
1879
			"		<option key=\"org.eclipse.jdt.core.compiler.problem.unclosedCloseable\" value=\"warning\"/>\n" + 
1875
			"		<option key=\"org.eclipse.jdt.core.compiler.problem.undocumentedEmptyBlock\" value=\"ignore\"/>\n" + 
1880
			"		<option key=\"org.eclipse.jdt.core.compiler.problem.undocumentedEmptyBlock\" value=\"ignore\"/>\n" + 
1876
			"		<option key=\"org.eclipse.jdt.core.compiler.problem.unhandledWarningToken\" value=\"warning\"/>\n" + 
1881
			"		<option key=\"org.eclipse.jdt.core.compiler.problem.unhandledWarningToken\" value=\"warning\"/>\n" + 
1877
			"		<option key=\"org.eclipse.jdt.core.compiler.problem.unnecessaryElse\" value=\"ignore\"/>\n" + 
1882
			"		<option key=\"org.eclipse.jdt.core.compiler.problem.unnecessaryElse\" value=\"ignore\"/>\n" + 
(-)src/org/eclipse/jdt/core/tests/compiler/regression/CompilerInvocationTests.java (-1 / +13 lines)
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 349326 - [1.7] new warning for missing try-with-resources
12
 *******************************************************************************/
14
 *******************************************************************************/
13
package org.eclipse.jdt.core.tests.compiler.regression;
15
package org.eclipse.jdt.core.tests.compiler.regression;
14
16
Lines 440-445 Link Here
440
		expectedProblemAttributes.put("ExceptionTypeInternalNameProvided", DEPRECATED);
442
		expectedProblemAttributes.put("ExceptionTypeInternalNameProvided", DEPRECATED);
441
		expectedProblemAttributes.put("ExceptionTypeNotFound", DEPRECATED);
443
		expectedProblemAttributes.put("ExceptionTypeNotFound", DEPRECATED);
442
		expectedProblemAttributes.put("ExceptionTypeNotVisible", DEPRECATED);
444
		expectedProblemAttributes.put("ExceptionTypeNotVisible", DEPRECATED);
445
		expectedProblemAttributes.put("ExplicitlyClosedAutoCloseable", new ProblemAttributes(CategorizedProblem.CAT_CODE_STYLE));
443
		expectedProblemAttributes.put("ExpressionShouldBeAVariable", new ProblemAttributes(CategorizedProblem.CAT_SYNTAX));
446
		expectedProblemAttributes.put("ExpressionShouldBeAVariable", new ProblemAttributes(CategorizedProblem.CAT_SYNTAX));
444
		expectedProblemAttributes.put("ExternalProblemFixable", new ProblemAttributes(CategorizedProblem.CAT_INTERNAL));
447
		expectedProblemAttributes.put("ExternalProblemFixable", new ProblemAttributes(CategorizedProblem.CAT_INTERNAL));
445
		expectedProblemAttributes.put("ExternalProblemNotFixable", new ProblemAttributes(CategorizedProblem.CAT_INTERNAL));
448
		expectedProblemAttributes.put("ExternalProblemNotFixable", new ProblemAttributes(CategorizedProblem.CAT_INTERNAL));
Lines 764-769 Link Here
764
		expectedProblemAttributes.put("PolymorphicMethodNotBelow17", new ProblemAttributes(CategorizedProblem.CAT_MEMBER));
767
		expectedProblemAttributes.put("PolymorphicMethodNotBelow17", new ProblemAttributes(CategorizedProblem.CAT_MEMBER));
765
		expectedProblemAttributes.put("PossibleAccidentalBooleanAssignment", new ProblemAttributes(CategorizedProblem.CAT_POTENTIAL_PROGRAMMING_PROBLEM));
768
		expectedProblemAttributes.put("PossibleAccidentalBooleanAssignment", new ProblemAttributes(CategorizedProblem.CAT_POTENTIAL_PROGRAMMING_PROBLEM));
766
		expectedProblemAttributes.put("PotentialHeapPollutionFromVararg", new ProblemAttributes(CategorizedProblem.CAT_UNCHECKED_RAW));
769
		expectedProblemAttributes.put("PotentialHeapPollutionFromVararg", new ProblemAttributes(CategorizedProblem.CAT_UNCHECKED_RAW));
770
		expectedProblemAttributes.put("PotentiallyUnclosedCloseable", new ProblemAttributes(CategorizedProblem.CAT_POTENTIAL_PROGRAMMING_PROBLEM));
771
		expectedProblemAttributes.put("PotentiallyUnclosedCloseableAtExit", new ProblemAttributes(CategorizedProblem.CAT_POTENTIAL_PROGRAMMING_PROBLEM));
767
		expectedProblemAttributes.put("PotentialNullLocalVariableReference", new ProblemAttributes(CategorizedProblem.CAT_POTENTIAL_PROGRAMMING_PROBLEM));
772
		expectedProblemAttributes.put("PotentialNullLocalVariableReference", new ProblemAttributes(CategorizedProblem.CAT_POTENTIAL_PROGRAMMING_PROBLEM));
768
		expectedProblemAttributes.put("PublicClassMustMatchFileName", new ProblemAttributes(CategorizedProblem.CAT_TYPE));
773
		expectedProblemAttributes.put("PublicClassMustMatchFileName", new ProblemAttributes(CategorizedProblem.CAT_TYPE));
769
		expectedProblemAttributes.put("RawMemberTypeCannotBeParameterized", new ProblemAttributes(CategorizedProblem.CAT_TYPE));
774
		expectedProblemAttributes.put("RawMemberTypeCannotBeParameterized", new ProblemAttributes(CategorizedProblem.CAT_TYPE));
Lines 827-832 Link Here
827
		expectedProblemAttributes.put("TypeMissingDeprecatedAnnotation", new ProblemAttributes(CategorizedProblem.CAT_CODE_STYLE));
832
		expectedProblemAttributes.put("TypeMissingDeprecatedAnnotation", new ProblemAttributes(CategorizedProblem.CAT_CODE_STYLE));
828
		expectedProblemAttributes.put("TypeParameterHidingType", new ProblemAttributes(CategorizedProblem.CAT_NAME_SHADOWING_CONFLICT));
833
		expectedProblemAttributes.put("TypeParameterHidingType", new ProblemAttributes(CategorizedProblem.CAT_NAME_SHADOWING_CONFLICT));
829
		expectedProblemAttributes.put("UnboxingConversion", new ProblemAttributes(CategorizedProblem.CAT_CODE_STYLE));
834
		expectedProblemAttributes.put("UnboxingConversion", new ProblemAttributes(CategorizedProblem.CAT_CODE_STYLE));
835
		expectedProblemAttributes.put("UnclosedCloseable", new ProblemAttributes(CategorizedProblem.CAT_POTENTIAL_PROGRAMMING_PROBLEM));
836
		expectedProblemAttributes.put("UnclosedCloseableAtExit", new ProblemAttributes(CategorizedProblem.CAT_POTENTIAL_PROGRAMMING_PROBLEM));
830
		expectedProblemAttributes.put("UndefinedAnnotationMember", new ProblemAttributes(CategorizedProblem.CAT_MEMBER));
837
		expectedProblemAttributes.put("UndefinedAnnotationMember", new ProblemAttributes(CategorizedProblem.CAT_MEMBER));
831
		expectedProblemAttributes.put("UndefinedConstructor", new ProblemAttributes(CategorizedProblem.CAT_MEMBER));
838
		expectedProblemAttributes.put("UndefinedConstructor", new ProblemAttributes(CategorizedProblem.CAT_MEMBER));
832
		expectedProblemAttributes.put("UndefinedConstructorInDefaultConstructor", new ProblemAttributes(CategorizedProblem.CAT_MEMBER));
839
		expectedProblemAttributes.put("UndefinedConstructorInDefaultConstructor", new ProblemAttributes(CategorizedProblem.CAT_MEMBER));
Lines 1107-1112 Link Here
1107
		expectedProblemAttributes.put("ExceptionTypeInternalNameProvided", SKIP);
1114
		expectedProblemAttributes.put("ExceptionTypeInternalNameProvided", SKIP);
1108
		expectedProblemAttributes.put("ExceptionTypeNotFound", SKIP);
1115
		expectedProblemAttributes.put("ExceptionTypeNotFound", SKIP);
1109
		expectedProblemAttributes.put("ExceptionTypeNotVisible", SKIP);
1116
		expectedProblemAttributes.put("ExceptionTypeNotVisible", SKIP);
1117
		expectedProblemAttributes.put("ExplicitlyClosedAutoCloseable", new ProblemAttributes(JavaCore.COMPILER_PB_EXPLICITLY_CLOSED_AUTOCLOSEABLE));
1110
		expectedProblemAttributes.put("ExpressionShouldBeAVariable", SKIP);
1118
		expectedProblemAttributes.put("ExpressionShouldBeAVariable", SKIP);
1111
		expectedProblemAttributes.put("ExternalProblemFixable", SKIP);
1119
		expectedProblemAttributes.put("ExternalProblemFixable", SKIP);
1112
		expectedProblemAttributes.put("ExternalProblemNotFixable", SKIP);
1120
		expectedProblemAttributes.put("ExternalProblemNotFixable", SKIP);
Lines 1431-1436 Link Here
1431
		expectedProblemAttributes.put("PolymorphicMethodNotBelow17", SKIP);
1439
		expectedProblemAttributes.put("PolymorphicMethodNotBelow17", SKIP);
1432
		expectedProblemAttributes.put("PossibleAccidentalBooleanAssignment", new ProblemAttributes(JavaCore.COMPILER_PB_POSSIBLE_ACCIDENTAL_BOOLEAN_ASSIGNMENT));
1440
		expectedProblemAttributes.put("PossibleAccidentalBooleanAssignment", new ProblemAttributes(JavaCore.COMPILER_PB_POSSIBLE_ACCIDENTAL_BOOLEAN_ASSIGNMENT));
1433
		expectedProblemAttributes.put("PotentialHeapPollutionFromVararg", new ProblemAttributes(JavaCore.COMPILER_PB_UNCHECKED_TYPE_OPERATION));
1441
		expectedProblemAttributes.put("PotentialHeapPollutionFromVararg", new ProblemAttributes(JavaCore.COMPILER_PB_UNCHECKED_TYPE_OPERATION));
1442
		expectedProblemAttributes.put("PotentiallyUnclosedCloseable", new ProblemAttributes(JavaCore.COMPILER_PB_POTENTIALLY_UNCLOSED_CLOSEABLE));
1443
		expectedProblemAttributes.put("PotentiallyUnclosedCloseableAtExit", new ProblemAttributes(JavaCore.COMPILER_PB_POTENTIALLY_UNCLOSED_CLOSEABLE));
1434
		expectedProblemAttributes.put("PotentialNullLocalVariableReference", new ProblemAttributes(JavaCore.COMPILER_PB_POTENTIAL_NULL_REFERENCE));
1444
		expectedProblemAttributes.put("PotentialNullLocalVariableReference", new ProblemAttributes(JavaCore.COMPILER_PB_POTENTIAL_NULL_REFERENCE));
1435
		expectedProblemAttributes.put("PublicClassMustMatchFileName", SKIP);
1445
		expectedProblemAttributes.put("PublicClassMustMatchFileName", SKIP);
1436
		expectedProblemAttributes.put("RawMemberTypeCannotBeParameterized", SKIP);
1446
		expectedProblemAttributes.put("RawMemberTypeCannotBeParameterized", SKIP);
Lines 1494-1499 Link Here
1494
		expectedProblemAttributes.put("TypeMissingDeprecatedAnnotation", new ProblemAttributes(JavaCore.COMPILER_PB_MISSING_DEPRECATED_ANNOTATION));
1504
		expectedProblemAttributes.put("TypeMissingDeprecatedAnnotation", new ProblemAttributes(JavaCore.COMPILER_PB_MISSING_DEPRECATED_ANNOTATION));
1495
		expectedProblemAttributes.put("TypeParameterHidingType", new ProblemAttributes(JavaCore.COMPILER_PB_TYPE_PARAMETER_HIDING));
1505
		expectedProblemAttributes.put("TypeParameterHidingType", new ProblemAttributes(JavaCore.COMPILER_PB_TYPE_PARAMETER_HIDING));
1496
		expectedProblemAttributes.put("UnboxingConversion", new ProblemAttributes(JavaCore.COMPILER_PB_AUTOBOXING));
1506
		expectedProblemAttributes.put("UnboxingConversion", new ProblemAttributes(JavaCore.COMPILER_PB_AUTOBOXING));
1507
		expectedProblemAttributes.put("UnclosedCloseable", new ProblemAttributes(JavaCore.COMPILER_PB_UNCLOSED_CLOSEABLE));
1508
		expectedProblemAttributes.put("UnclosedCloseableAtExit", new ProblemAttributes(JavaCore.COMPILER_PB_UNCLOSED_CLOSEABLE));
1497
		expectedProblemAttributes.put("UndefinedAnnotationMember", SKIP);
1509
		expectedProblemAttributes.put("UndefinedAnnotationMember", SKIP);
1498
		expectedProblemAttributes.put("UndefinedConstructor", SKIP);
1510
		expectedProblemAttributes.put("UndefinedConstructor", SKIP);
1499
		expectedProblemAttributes.put("UndefinedConstructorInDefaultConstructor", SKIP);
1511
		expectedProblemAttributes.put("UndefinedConstructorInDefaultConstructor", SKIP);
(-)src/org/eclipse/jdt/core/tests/compiler/regression/TryWithResourcesStatementTest.java (-5 / +834 lines)
Lines 7-24 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 349326 - [1.7] new warning for missing try-with-resources
10
 *******************************************************************************/
11
 *******************************************************************************/
11
package org.eclipse.jdt.core.tests.compiler.regression;
12
package org.eclipse.jdt.core.tests.compiler.regression;
12
13
13
import java.util.Map;
14
import java.util.Map;
14
15
16
import org.eclipse.jdt.core.JavaCore;
15
import org.eclipse.jdt.internal.compiler.impl.CompilerOptions;
17
import org.eclipse.jdt.internal.compiler.impl.CompilerOptions;
16
18
17
import junit.framework.Test;
19
import junit.framework.Test;
18
public class TryWithResourcesStatementTest extends AbstractRegressionTest {
20
public class TryWithResourcesStatementTest extends AbstractRegressionTest {
19
21
20
static {
22
static {
21
//	TESTS_NAMES = new String[] { "test053" };
23
//	TESTS_NAMES = new String[] { "test055" };
22
//	TESTS_NUMBERS = new int[] { 50 };
24
//	TESTS_NUMBERS = new int[] { 50 };
23
//	TESTS_RANGE = new int[] { 11, -1 };
25
//	TESTS_RANGE = new int[] { 11, -1 };
24
}
26
}
Lines 485-496 Link Here
485
		"	               ^^\n" + 
487
		"	               ^^\n" + 
486
		"Dead code\n" + 
488
		"Dead code\n" + 
487
		"----------\n" + 
489
		"----------\n" + 
488
		"3. ERROR in X.java (at line 5)\n" + 
490
		"3. WARNING in X.java (at line 5)\n" + 
491
		"	Y why = new Y();\n" + 
492
		"	  ^^^\n" + 
493
		"Leaking resource 'why': is never closed\n" + 
494
		"----------\n" + 
495
		"4. ERROR in X.java (at line 5)\n" + 
489
		"	Y why = new Y();\n" + 
496
		"	Y why = new Y();\n" + 
490
		"	        ^^^^^^^\n" + 
497
		"	        ^^^^^^^\n" + 
491
		"Unhandled exception type WeirdException\n" + 
498
		"Unhandled exception type WeirdException\n" + 
492
		"----------\n" + 
499
		"----------\n" + 
493
		"4. WARNING in X.java (at line 22)\n" + 
500
		"5. WARNING in X.java (at line 22)\n" + 
494
		"	class WeirdException extends Throwable {}\n" + 
501
		"	class WeirdException extends Throwable {}\n" + 
495
		"	      ^^^^^^^^^^^^^^\n" + 
502
		"	      ^^^^^^^^^^^^^^\n" + 
496
		"The serializable class WeirdException does not declare a static final serialVersionUID field of type long\n" + 
503
		"The serializable class WeirdException does not declare a static final serialVersionUID field of type long\n" + 
Lines 558-569 Link Here
558
		"	               ^^\n" + 
565
		"	               ^^\n" + 
559
		"Dead code\n" + 
566
		"Dead code\n" + 
560
		"----------\n" + 
567
		"----------\n" + 
561
		"3. ERROR in X.java (at line 5)\n" + 
568
		"3. WARNING in X.java (at line 5)\n" + 
569
		"	Y why = new Y();\n" + 
570
		"	  ^^^\n" + 
571
		"Leaking resource 'why': is never closed\n" + 
572
		"----------\n" + 
573
		"4. ERROR in X.java (at line 5)\n" + 
562
		"	Y why = new Y();\n" + 
574
		"	Y why = new Y();\n" + 
563
		"	        ^^^^^^^\n" + 
575
		"	        ^^^^^^^\n" + 
564
		"Unhandled exception type WeirdException\n" + 
576
		"Unhandled exception type WeirdException\n" + 
565
		"----------\n" + 
577
		"----------\n" + 
566
		"4. WARNING in X.java (at line 20)\n" + 
578
		"5. WARNING in X.java (at line 20)\n" + 
567
		"	class WeirdException extends Throwable {}\n" + 
579
		"	class WeirdException extends Throwable {}\n" + 
568
		"	      ^^^^^^^^^^^^^^\n" + 
580
		"	      ^^^^^^^^^^^^^^\n" + 
569
		"The serializable class WeirdException does not declare a static final serialVersionUID field of type long\n" + 
581
		"The serializable class WeirdException does not declare a static final serialVersionUID field of type long\n" + 
Lines 3337-3342 Link Here
3337
		"Object.Integer cannot be resolved to a type\n" + 
3349
		"Object.Integer cannot be resolved to a type\n" + 
3338
		"----------\n");
3350
		"----------\n");
3339
}
3351
}
3352
// Bug 349326 - [1.7] new warning for missing try-with-resources
3353
// a method uses an AutoCloseable without ever closing it.
3354
public void test055() {
3355
	Map options = getCompilerOptions();
3356
	options.put(CompilerOptions.OPTION_ReportUnclosedCloseable, CompilerOptions.ERROR);
3357
	options.put(CompilerOptions.OPTION_ReportPotentiallyUnclosedCloseable, CompilerOptions.WARNING);
3358
	this.runNegativeTest(
3359
		new String[] {
3360
			"X.java",
3361
			"import java.io.File;\n" +
3362
			"import java.io.FileReader;\n" +
3363
			"import java.io.IOException;\n" +
3364
			"public class X {\n" +
3365
			"    void foo() throws IOException {\n" +
3366
			"        File file = new File(\"somefile\");\n" +
3367
			"        FileReader fileReader = new FileReader(file);\n" +
3368
// not invoking any methods on FileReader, try to avoid necessary call to superclass() in the compiler
3369
//			"        char[] in = new char[50];\n" +
3370
//			"        fileReader.read(in);\n" +
3371
			"    }\n" +
3372
			"    public static void main(String[] args) throws IOException {\n" +
3373
			"        new X().foo();\n" +
3374
			"    }\n" +
3375
			"}\n"
3376
		},
3377
		"----------\n" + 
3378
		"1. ERROR in X.java (at line 7)\n" + 
3379
		"	FileReader fileReader = new FileReader(file);\n" + 
3380
		"	           ^^^^^^^^^^\n" + 
3381
		"Leaking resource 'fileReader': is never closed\n" +
3382
		"----------\n",
3383
		null,
3384
		true,
3385
		options);
3386
}
3387
// Bug 349326 - [1.7] new warning for missing try-with-resources
3388
// a method uses an AutoCloseable and closes it but exception may occur earlier.
3389
public void test055a() {
3390
	Map options = getCompilerOptions();
3391
	options.put(CompilerOptions.OPTION_ReportUnclosedCloseable, CompilerOptions.ERROR);
3392
	options.put(CompilerOptions.OPTION_ReportPotentiallyUnclosedCloseable, CompilerOptions.ERROR);
3393
	this.runNegativeTest(
3394
		new String[] {
3395
			"X.java",
3396
			"import java.io.File;\n" +
3397
			"import java.io.FileReader;\n" +
3398
			"import java.io.IOException;\n" +
3399
			"public class X {\n" +
3400
			"    void foo() throws IOException {\n" +
3401
			"        File file = new File(\"somefile\");\n" +
3402
			"        FileReader fileReader = new FileReader(file);\n" +
3403
			"        char[] in = new char[50];\n" +
3404
			"        fileReader.read(in);\n" +
3405
			"		 fileReader.close();\n" +
3406
			"    }\n" +
3407
			"    public static void main(String[] args) {\n" +
3408
			"        try {\n" +
3409
			"            new X().foo();\n" +
3410
			"        } catch (IOException ioex) {\n" +
3411
			"            System.out.println(\"caught\");\n" +
3412
			"        }\n" +
3413
			"    }\n" +
3414
			"}\n"
3415
		},
3416
		"----------\n" + 
3417
		"1. ERROR in X.java (at line 7)\n" + 
3418
		"	FileReader fileReader = new FileReader(file);\n" + 
3419
		"	           ^^^^^^^^^^\n" + 
3420
		"Potentially leaking resource 'fileReader': is not closed on all paths\n" + 
3421
		"----------\n",
3422
		null,
3423
		true,
3424
		options);
3425
}
3426
// Bug 349326 - [1.7] new warning for missing try-with-resources
3427
// a method uses an AutoCloseable and closes it properly in a finally block
3428
public void test055b() {
3429
	Map options = getCompilerOptions();
3430
	options.put(CompilerOptions.OPTION_ReportUnclosedCloseable, CompilerOptions.ERROR);
3431
	options.put(CompilerOptions.OPTION_ReportPotentiallyUnclosedCloseable, CompilerOptions.ERROR);
3432
	this.runConformTest(
3433
		new String[] {
3434
			"X.java",
3435
			"import java.io.File;\n" +
3436
			"import java.io.FileReader;\n" +
3437
			"import java.io.IOException;\n" +
3438
			"public class X {\n" +
3439
			"    void foo() throws IOException {\n" +
3440
			"        File file = new File(\"somefile\");\n" +
3441
			"        FileReader fileReader = new FileReader(file);\n" +
3442
			"        try {\n" +
3443
			"            char[] in = new char[50];\n" +
3444
			"            fileReader.read(in);\n" +
3445
			"        } finally {\n" +
3446
			"		     fileReader.close();\n" +
3447
			"        }\n" +
3448
			"    }\n" +
3449
			"    public static void main(String[] args) {\n" +
3450
			"        try {\n" +
3451
			"            new X().foo();\n" +
3452
			"        } catch (IOException ioex) {\n" +
3453
			"            System.out.println(\"caught\");\n" +
3454
			"        }\n" +
3455
			"    }\n" +
3456
			"}\n"
3457
		},
3458
		"caught", /*output*/
3459
		null/*classLibs*/,
3460
		true/*shouldFlush*/,
3461
		null/*vmargs*/,
3462
		options,
3463
		null/*requestor*/);
3464
}
3465
// Bug 349326 - [1.7] new warning for missing try-with-resources
3466
// a method uses an AutoCloseable properly within try-with-resources.
3467
public void test055c() {
3468
	Map options = getCompilerOptions();
3469
	options.put(CompilerOptions.OPTION_ReportUnclosedCloseable, CompilerOptions.ERROR);
3470
	options.put(CompilerOptions.OPTION_ReportPotentiallyUnclosedCloseable, CompilerOptions.WARNING);
3471
	this.runConformTest(
3472
		new String[] {
3473
			"X.java",
3474
			"import java.io.File;\n" +
3475
			"import java.io.FileReader;\n" +
3476
			"import java.io.IOException;\n" +
3477
			"public class X {\n" +
3478
			"    void foo() throws IOException {\n" +
3479
			"        File file = new File(\"somefile\");\n" +
3480
			"        try (FileReader fileReader = new FileReader(file)) {\n" +
3481
			"            char[] in = new char[50];\n" +
3482
			"            fileReader.read(in);\n" +
3483
			"		 }\n" +
3484
			"    }\n" +
3485
			"    public static void main(String[] args) {\n" +
3486
			"        try {\n" +
3487
			"            new X().foo();\n" +
3488
			"        } catch (IOException ioex) {\n" +
3489
			"            System.out.println(\"caught\");\n" +
3490
			"        }\n" +
3491
			"    }\n" +
3492
			"}\n"
3493
		},
3494
		"caught", /*output*/
3495
		null/*classLibs*/,
3496
		true/*shouldFlush*/,
3497
		null/*vmargs*/,
3498
		options,
3499
		null/*requestor*/);
3500
}
3501
// Bug 349326 - [1.7] new warning for missing try-with-resources
3502
// a method uses two AutoCloseables (testing independent analysis)
3503
// - one closeable may be unclosed at a conditional return
3504
// - the other is only conditionally closed
3505
public void test055d() {
3506
	Map options = getCompilerOptions();
3507
	options.put(CompilerOptions.OPTION_ReportUnclosedCloseable, CompilerOptions.ERROR);
3508
	options.put(CompilerOptions.OPTION_ReportPotentiallyUnclosedCloseable, CompilerOptions.WARNING);
3509
	this.runNegativeTest(
3510
		new String[] {
3511
			"X.java",
3512
			"import java.io.File;\n" +
3513
			"import java.io.FileReader;\n" +
3514
			"import java.io.IOException;\n" +
3515
			"public class X {\n" +
3516
			"    void foo(boolean flag1, boolean flag2) throws IOException {\n" +
3517
			"        File file = new File(\"somefile\");\n" +
3518
			"        char[] in = new char[50];\n" +
3519
			"        FileReader fileReader1 = new FileReader(file);\n" +
3520
			"        fileReader1.read(in);\n" +
3521
			"        FileReader fileReader2 = new FileReader(file);\n" +
3522
			"        fileReader2.read(in);\n" +
3523
			"        if (flag1) {\n" +
3524
			"            fileReader2.close();\n" +
3525
			"            return;\n" +
3526
			"        } else if (flag2) {\n" +
3527
			"            fileReader2.close();\n" +
3528
			"        }\n" +
3529
			"        fileReader1.close();\n" +
3530
			"    }\n" +
3531
			"    public static void main(String[] args) throws IOException {\n" +
3532
			"        new X().foo(false, true);\n" +
3533
			"    }\n" +
3534
			"}\n"
3535
		},
3536
		"----------\n" + 
3537
		"1. WARNING in X.java (at line 10)\n" + 
3538
		"	FileReader fileReader2 = new FileReader(file);\n" + 
3539
		"	           ^^^^^^^^^^^\n" + 
3540
		"Potentially leaking resource 'fileReader2': is not closed on all paths\n" +
3541
		"----------\n" + 
3542
		"2. ERROR in X.java (at line 14)\n" + 
3543
		"	return;\n" + 
3544
		"	^^^^^^^\n" + 
3545
		"Leaking resource \'fileReader1\': is not closed at this location\n" + 
3546
		"----------\n",
3547
		null,
3548
		true,
3549
		options);
3550
}
3551
//Bug 349326 - [1.7] new warning for missing try-with-resources
3552
//a method uses two AutoCloseables (testing independent analysis)
3553
//- one closeable may be unclosed at a conditional return
3554
//- the other is only conditionally closed
3555
public void test055d_suppress() {
3556
	Map options = getCompilerOptions();
3557
	options.put(CompilerOptions.OPTION_ReportUnclosedCloseable, CompilerOptions.ERROR);
3558
	options.put(CompilerOptions.OPTION_ReportPotentiallyUnclosedCloseable, CompilerOptions.WARNING);
3559
	options.put(CompilerOptions.OPTION_SuppressOptionalErrors, CompilerOptions.ENABLED);
3560
	this.runNegativeTest(
3561
		new String[] {
3562
			"X.java",
3563
			"import java.io.File;\n" +
3564
			"import java.io.FileReader;\n" +
3565
			"import java.io.IOException;\n" +
3566
			"public class X {\n" +
3567
			"    void foo(boolean flag1, boolean flag2) throws IOException {\n" +
3568
			"        @SuppressWarnings(\"resource\") File file = new File(\"somefile\"); // unnecessary suppress\n" +
3569
			"        char[] in = new char[50];\n" +
3570
			"        FileReader fileReader1 = new FileReader(file);\n" +
3571
			"        fileReader1.read(in);\n" +
3572
			"        @SuppressWarnings(\"resource\") FileReader fileReader2 = new FileReader(file); // useful suppress\n" +
3573
			"        fileReader2.read(in);\n" +
3574
			"        if (flag1) {\n" +
3575
			"            fileReader2.close();\n" +
3576
			"            return; // not suppressed\n" +
3577
			"        } else if (flag2) {\n" +
3578
			"            fileReader2.close();\n" +
3579
			"        }\n" +
3580
			"        fileReader1.close();\n" +
3581
			"    }\n" +
3582
			"    @SuppressWarnings(\"resource\") // useful suppress\n" +
3583
			"    void bar() throws IOException {\n" +
3584
			"        File file = new File(\"somefile\");\n" +
3585
			"        FileReader fileReader = new FileReader(file);\n" +
3586
			"        char[] in = new char[50];\n" +
3587
			"        fileReader.read(in);\n" +
3588
			"    }\n" +
3589
			"    public static void main(String[] args) throws IOException {\n" +
3590
			"        new X().foo(false, true);\n" +
3591
			"    }\n" +
3592
			"}\n"
3593
		},
3594
		"----------\n" + 
3595
		"1. WARNING in X.java (at line 6)\n" + 
3596
		"	@SuppressWarnings(\"resource\") File file = new File(\"somefile\"); // unnecessary suppress\n" + 
3597
		"	                  ^^^^^^^^^^\n" + 
3598
		"Unnecessary @SuppressWarnings(\"resource\")\n" + 
3599
		"----------\n" + 
3600
		"2. ERROR in X.java (at line 14)\n" + 
3601
		"	return; // not suppressed\n" + 
3602
		"	^^^^^^^\n" + 
3603
		"Leaking resource \'fileReader1\': is not closed at this location\n" + 
3604
		"----------\n",
3605
		null,
3606
		true,
3607
		options);
3608
}
3609
// Bug 349326 - [1.7] new warning for missing try-with-resources
3610
// one method returns an AutoCleasble, a second method uses this object without ever closing it.
3611
public void test055e() {
3612
	Map options = getCompilerOptions();
3613
	options.put(CompilerOptions.OPTION_ReportUnclosedCloseable, CompilerOptions.ERROR);
3614
	options.put(CompilerOptions.OPTION_ReportPotentiallyUnclosedCloseable, CompilerOptions.WARNING);
3615
	this.runNegativeTest(
3616
		new String[] {
3617
			"X.java",
3618
			"import java.io.File;\n" +
3619
			"import java.io.FileReader;\n" +
3620
			"import java.io.IOException;\n" +
3621
			"public class X {\n" +
3622
			"    FileReader getReader(String filename) throws IOException {\n" +
3623
			"        File file = new File(\"somefile\");\n" +
3624
			"        FileReader fileReader = new FileReader(file);\n" +
3625
			"        return fileReader;\n" + 		// don't complain here, pass responsibility to caller
3626
			"    }\n" +
3627
			"    void foo() throws IOException {\n" +
3628
			"        FileReader reader = getReader(\"somefile\");\n" +
3629
			"        char[] in = new char[50];\n" +
3630
			"        reader.read(in);\n" +
3631
			"    }\n" +
3632
			"    public static void main(String[] args) throws IOException {\n" +
3633
			"        new X().foo();\n" +
3634
			"    }\n" +
3635
			"}\n"
3636
		},
3637
		"----------\n" + 
3638
		"1. ERROR in X.java (at line 11)\n" + 
3639
		"	FileReader reader = getReader(\"somefile\");\n" + 
3640
		"	           ^^^^^^\n" + 
3641
		"Leaking resource 'reader': is never closed\n" + 
3642
		"----------\n",
3643
		null,
3644
		true,
3645
		options);
3646
}
3647
// Bug 349326 - [1.7] new warning for missing try-with-resources
3648
// a method explicitly closes its AutoCloseable rather than using t-w-r
3649
public void test055f() {
3650
	Map options = getCompilerOptions();
3651
	options.put(CompilerOptions.OPTION_ReportUnclosedCloseable, CompilerOptions.ERROR);
3652
	options.put(CompilerOptions.OPTION_ReportPotentiallyUnclosedCloseable, CompilerOptions.WARNING);
3653
	options.put(CompilerOptions.OPTION_ReportExplicitlyClosedAutoCloseable, CompilerOptions.ERROR);
3654
	this.runNegativeTest(
3655
		new String[] {
3656
			"X.java",
3657
			"import java.io.File;\n" +
3658
			"import java.io.FileReader;\n" +
3659
			"import java.io.IOException;\n" +
3660
			"public class X {\n" +
3661
			"    void foo() throws IOException {\n" +
3662
			"        File file = new File(\"somefile\");\n" +
3663
			"        FileReader fileReader = null;\n" +
3664
			"        try {\n" +
3665
			"            fileReader = new FileReader(file);\n" +
3666
			"            char[] in = new char[50];\n" +
3667
			"            fileReader.read(in);\n" +
3668
			"        } finally {\n" +
3669
			"            fileReader.close();\n" +
3670
			"        }\n" +
3671
			"    }\n" +
3672
			"    public static void main(String[] args) throws IOException {\n" +
3673
			"        new X().foo();\n" +
3674
			"    }\n" +
3675
			"}\n"
3676
		},
3677
		"----------\n" + 
3678
		"1. ERROR in X.java (at line 7)\n" + 
3679
		"	FileReader fileReader = null;\n" + 
3680
		"	           ^^^^^^^^^^\n" + 
3681
		"Resource \'fileReader\' should be managed by try-with-resource\n" + 
3682
		"----------\n",
3683
		null,
3684
		true,
3685
		options);
3686
}
3687
// Bug 349326 - [1.7] new warning for missing try-with-resources
3688
// an AutoCloseable local is re-assigned
3689
public void test055g() {
3690
	Map options = getCompilerOptions();
3691
	options.put(JavaCore.COMPILER_PB_UNCLOSED_CLOSEABLE, CompilerOptions.ERROR);
3692
	options.put(JavaCore.COMPILER_PB_POTENTIALLY_UNCLOSED_CLOSEABLE, CompilerOptions.WARNING);
3693
	options.put(JavaCore.COMPILER_PB_EXPLICITLY_CLOSED_AUTOCLOSEABLE, CompilerOptions.IGNORE);
3694
	this.runNegativeTest(
3695
		new String[] {
3696
			"X.java",
3697
			"import java.io.File;\n" +
3698
			"import java.io.FileReader;\n" +
3699
			"import java.io.IOException;\n" +
3700
			"public class X {\n" +
3701
			"    void foo() throws IOException {\n" +
3702
			"        File file = new File(\"somefile\");\n" +
3703
			"        FileReader fileReader = new FileReader(file);\n" +
3704
			"        char[] in = new char[50];\n" +
3705
			"        fileReader.read(in);\n" +
3706
			"        fileReader = new FileReader(file);\n" +
3707
			"        fileReader.read(in);\n" +
3708
			"        fileReader.close();\n" +
3709
			"    }\n" +
3710
			"    public static void main(String[] args) throws IOException {\n" +
3711
			"        new X().foo();\n" +
3712
			"    }\n" +
3713
			"}\n"
3714
		},
3715
		"----------\n" + 
3716
		"1. ERROR in X.java (at line 10)\n" + 
3717
		"	fileReader = new FileReader(file);\n" + 
3718
		"	^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^\n" + 
3719
		"Leaking resource \'fileReader\': is not closed at this location\n" + 
3720
		"----------\n",
3721
		null,
3722
		true,
3723
		options);
3724
}
3725
// Bug 349326 - [1.7] new warning for missing try-with-resources
3726
// two AutoCloseables at different nesting levels (anonymous local type)
3727
public void test055h() {
3728
	Map options = getCompilerOptions();
3729
	options.put(JavaCore.COMPILER_PB_UNCLOSED_CLOSEABLE, CompilerOptions.ERROR);
3730
	options.put(JavaCore.COMPILER_PB_POTENTIALLY_UNCLOSED_CLOSEABLE, CompilerOptions.WARNING);
3731
	options.put(JavaCore.COMPILER_PB_EXPLICITLY_CLOSED_AUTOCLOSEABLE, CompilerOptions.IGNORE);
3732
	this.runNegativeTest(
3733
		new String[] {
3734
			"X.java",
3735
			"import java.io.File;\n" +
3736
			"import java.io.FileReader;\n" +
3737
			"import java.io.IOException;\n" +
3738
			"public class X {\n" +
3739
			"    void foo() throws IOException {\n" +
3740
			"        final File file = new File(\"somefile\");\n" +
3741
			"        final FileReader fileReader = new FileReader(file);\n" +
3742
			"        char[] in = new char[50];\n" +
3743
			"        fileReader.read(in);\n" +
3744
			"        new Runnable() {\n public void run() {\n" +
3745
			"            try {\n" +
3746
			"                fileReader.close();\n" +
3747
			"                FileReader localReader = new FileReader(file);\n" +
3748
			"            } catch (IOException ex) { /* nop */ }\n" +
3749
			"        }}.run();\n" +
3750
			"    }\n" +
3751
			"    public static void main(String[] args) throws IOException {\n" +
3752
			"        new X().foo();\n" +
3753
			"    }\n" +
3754
			"}\n"
3755
		},
3756
		"----------\n" + 
3757
		"1. WARNING in X.java (at line 7)\n" + 
3758
		"	final FileReader fileReader = new FileReader(file);\n" + 
3759
		"	                 ^^^^^^^^^^\n" + 
3760
		"Potentially leaking resource 'fileReader': is not closed on all paths\n" + 
3761
		"----------\n" + 
3762
		"2. ERROR in X.java (at line 14)\n" + 
3763
		"	FileReader localReader = new FileReader(file);\n" + 
3764
		"	           ^^^^^^^^^^^\n" + 
3765
		"Leaking resource 'localReader': is never closed\n" + 
3766
		"----------\n",
3767
		null,
3768
		true,
3769
		options);
3770
}
3771
// Bug 349326 - [1.7] new warning for missing try-with-resources
3772
// three AutoCloseables in different blocks of the same method
3773
public void test055i() {
3774
	Map options = getCompilerOptions();
3775
	options.put(JavaCore.COMPILER_PB_UNCLOSED_CLOSEABLE, CompilerOptions.ERROR);
3776
	options.put(JavaCore.COMPILER_PB_POTENTIALLY_UNCLOSED_CLOSEABLE, CompilerOptions.WARNING);
3777
	options.put(JavaCore.COMPILER_PB_EXPLICITLY_CLOSED_AUTOCLOSEABLE, CompilerOptions.IGNORE);
3778
	this.runNegativeTest(
3779
		new String[] {
3780
			"X.java",
3781
			"import java.io.File;\n" +
3782
			"import java.io.FileReader;\n" +
3783
			"import java.io.IOException;\n" +
3784
			"public class X {\n" +
3785
			"    void foo(boolean f1, boolean f2) throws IOException {\n" +
3786
			"        File file = new File(\"somefile\");\n" +
3787
			"        if (f1) {\n" +
3788
			"            FileReader fileReader = new FileReader(file); // err: not closed\n" +
3789
			"            char[] in = new char[50];\n" +
3790
			"            fileReader.read(in);\n" +
3791
			"            while (true) {\n" +
3792
			"                 FileReader loopReader = new FileReader(file); // don't warn, properly closed\n" +
3793
			"                 loopReader.close();" +
3794
			"                 break;\n" +
3795
			"            }\n" +
3796
			"        } else {\n" +
3797
			"            FileReader fileReader = new FileReader(file); // warn: not closed on all paths\n" +
3798
			"            if (f2)\n" +
3799
			"                fileReader.close();\n" +
3800
			"        }\n" +
3801
			"    }\n" +
3802
			"    public static void main(String[] args) throws IOException {\n" +
3803
			"        new X().foo(true, true);\n" +
3804
			"    }\n" +
3805
			"}\n"
3806
		},
3807
		"----------\n" + 
3808
		"1. ERROR in X.java (at line 8)\n" + 
3809
		"	FileReader fileReader = new FileReader(file); // err: not closed\n" + 
3810
		"	           ^^^^^^^^^^\n" + 
3811
		"Leaking resource 'fileReader': is never closed\n" + 
3812
		"----------\n" + 
3813
		"2. WARNING in X.java (at line 16)\n" + 
3814
		"	FileReader fileReader = new FileReader(file); // warn: not closed on all paths\n" + 
3815
		"	           ^^^^^^^^^^\n" + 
3816
		"Potentially leaking resource 'fileReader': is not closed on all paths\n" + 
3817
		"----------\n",
3818
		null,
3819
		true,
3820
		options);
3821
}
3822
// Bug 349326 - [1.7] new warning for missing try-with-resources
3823
// a method uses an AutoCloseable without closing it locally but passing as arg to another method
3824
public void test055j() {
3825
	Map options = getCompilerOptions();
3826
	options.put(CompilerOptions.OPTION_ReportUnclosedCloseable, CompilerOptions.ERROR);
3827
	options.put(CompilerOptions.OPTION_ReportPotentiallyUnclosedCloseable, CompilerOptions.ERROR);
3828
	this.runNegativeTest(
3829
		new String[] {
3830
			"X.java",
3831
			"import java.io.File;\n" +
3832
			"import java.io.FileReader;\n" +
3833
			"import java.io.IOException;\n" +
3834
			"public class X {\n" +
3835
			"    void foo() throws IOException {\n" +
3836
			"        File file = new File(\"somefile\");\n" +
3837
			"        FileReader fileReader = new FileReader(file);\n" +
3838
			"        read(fileReader);\n" +
3839
			"    }\n" +
3840
			"    void read(FileReader reader) { }\n" +
3841
			"    public static void main(String[] args) throws IOException {\n" +
3842
			"        new X().foo();\n" +
3843
			"    }\n" +
3844
			"}\n"
3845
		},
3846
		"----------\n" + 
3847
		"1. ERROR in X.java (at line 7)\n" + 
3848
		"	FileReader fileReader = new FileReader(file);\n" + 
3849
		"	           ^^^^^^^^^^\n" + 
3850
		"Potentially leaking resource 'fileReader': is not closed on all paths\n" + 
3851
		"----------\n",
3852
		null,
3853
		true,
3854
		options);
3855
}
3856
// Bug 349326 - [1.7] new warning for missing try-with-resources
3857
// many locals, some are AutoCloseable.
3858
// Unfortunately analysis cannot respect how exception exits may affect ra3 and rb3,
3859
// doing so would create false positives.
3860
public void test055k() {
3861
	Map options = getCompilerOptions();
3862
	options.put(CompilerOptions.OPTION_ReportUnclosedCloseable, CompilerOptions.ERROR);
3863
	options.put(CompilerOptions.OPTION_ReportPotentiallyUnclosedCloseable, CompilerOptions.WARNING);
3864
	options.put(CompilerOptions.OPTION_ReportExplicitlyClosedAutoCloseable, CompilerOptions.ERROR);
3865
	this.runNegativeTest(
3866
		new String[] {
3867
			"X.java",
3868
			"import java.io.File;\n" +
3869
			"import java.io.FileReader;\n" +
3870
			"import java.io.IOException;\n" +
3871
			"public class X {\n" +
3872
			"    void foo() throws IOException {\n" +
3873
			"        int i01, i02, i03, i04, i05, i06, i07, i08, i09,\n" +
3874
			"            i11, i12, i13, i14, i15, i16, i17, i18, i19,\n" +
3875
			"            i21, i22, i23, i24, i25, i26, i27, i28, i29,\n" +
3876
			"            i31, i32, i33, i34, i35, i36, i37, i38, i39,\n" +
3877
			"            i41, i42, i43, i44, i45, i46, i47, i48, i49;\n" +
3878
			"        File file = new File(\"somefile\");\n" +
3879
			"        FileReader ra1 = null, ra2 = null;\n" +
3880
			"        try {\n" +
3881
			"            ra1 = new FileReader(file);\n" +
3882
			"            ra2 = new FileReader(file);\n" +
3883
			"            FileReader ra3 = new FileReader(file);\n" +
3884
			"            char[] in = new char[50];\n" +
3885
			"            ra1.read(in);\n" +
3886
			"            ra2.read(in);\n" +
3887
			"            ra3.close();\n" +
3888
			"        } finally {\n" +
3889
			"            ra1.close();\n" +
3890
			"        }\n" +
3891
			"        int i51, i52, i53, i54, i55, i56, i57, i58, i59, i60;\n" + // beyond this point locals are analyzed using extraBits
3892
			"        FileReader rb1 = null, rb2 = null;\n" +
3893
			"        try {\n" +
3894
			"            rb1 = new FileReader(file);\n" +
3895
			"            rb2 = new FileReader(file);\n" +
3896
			"            FileReader rb3 = new FileReader(file);\n" +
3897
			"            char[] in = new char[50];\n" +
3898
			"            rb1.read(in);\n" +
3899
			"            rb2.read(in);\n" +
3900
			"            rb3.close();\n" +
3901
			"        } finally {\n" +
3902
			"            rb1.close();\n" +
3903
			"        }\n" +
3904
			"    }\n" +
3905
			"    public static void main(String[] args) throws IOException {\n" +
3906
			"        new X().foo();\n" +
3907
			"    }\n" +
3908
			"}\n"
3909
		},
3910
		"----------\n" + 
3911
		"1. ERROR in X.java (at line 12)\n" + 
3912
		"	FileReader ra1 = null, ra2 = null;\n" + 
3913
		"	           ^^^\n" + 
3914
		"Resource \'ra1\' should be managed by try-with-resource\n" + 
3915
		"----------\n" + 
3916
		"2. ERROR in X.java (at line 15)\n" + 
3917
		"	ra2 = new FileReader(file);\n" + 
3918
		"	^^^^^^^^^^^^^^^^^^^^^^^^^^\n" + 
3919
		"Leaking resource 'ra2': is never closed\n" + 
3920
		"----------\n" + 
3921
		"3. ERROR in X.java (at line 16)\n" + 
3922
		"	FileReader ra3 = new FileReader(file);\n" + 
3923
		"	           ^^^\n" + 
3924
		"Resource \'ra3\' should be managed by try-with-resource\n" +
3925
		"----------\n" + 
3926
		"4. ERROR in X.java (at line 25)\n" + 
3927
		"	FileReader rb1 = null, rb2 = null;\n" + 
3928
		"	           ^^^\n" + 
3929
		"Resource \'rb1\' should be managed by try-with-resource\n" + 
3930
		"----------\n" + 
3931
		"5. ERROR in X.java (at line 28)\n" + 
3932
		"	rb2 = new FileReader(file);\n" + 
3933
		"	^^^^^^^^^^^^^^^^^^^^^^^^^^\n" + 
3934
		"Leaking resource 'rb2': is never closed\n" + 
3935
		"----------\n" + 
3936
		"6. ERROR in X.java (at line 29)\n" + 
3937
		"	FileReader rb3 = new FileReader(file);\n" + 
3938
		"	           ^^^\n" + 
3939
		"Resource \'rb3\' should be managed by try-with-resource\n" + 
3940
		"----------\n",
3941
		null,
3942
		true,
3943
		options);
3944
}
3945
// Bug 349326 - [1.7] new warning for missing try-with-resources
3946
// various non-problems
3947
public void test055l() {
3948
	Map options = getCompilerOptions();
3949
	options.put(CompilerOptions.OPTION_ReportUnclosedCloseable, CompilerOptions.ERROR);
3950
	options.put(CompilerOptions.OPTION_ReportPotentiallyUnclosedCloseable, CompilerOptions.ERROR);
3951
	options.put(CompilerOptions.OPTION_ReportExplicitlyClosedAutoCloseable, CompilerOptions.ERROR);
3952
	this.runNegativeTest(
3953
		new String[] {
3954
			"X.java",
3955
			"import java.io.File;\n" +
3956
			"import java.io.FileReader;\n" +
3957
			"import java.io.IOException;\n" +
3958
			"public class X {\n" +
3959
			"    X(FileReader r0) {}\n" + // don't complain against argument
3960
			"    FileReader getReader() { return null; }\n" +
3961
			"    void foo(FileReader r1) throws IOException {\n" +
3962
			"        FileReader fileReader = getReader();\n" +
3963
			"        if (fileReader == null)\n" +
3964
			"            return;\n" + // don't complain, resource is actually null
3965
			"        FileReader r3 = getReader();\n" +
3966
			"        if (r3 == null)\n" +
3967
			"            r3 = new FileReader(new File(\"absent\"));\n" + // don't complain, previous resource is actually null
3968
			"        try {\n" +
3969
			"            char[] in = new char[50];\n" +
3970
			"            fileReader.read(in);\n" +
3971
			"            r1.read(in);\n" +
3972
			"        } finally {\n" +
3973
			"            fileReader.close();\n" +
3974
			"            r3.close();\n" +
3975
			"        }\n" +
3976
			"    }\n" +
3977
			"    public static void main(String[] args) throws IOException {\n" +
3978
			"        FileReader r2 = new FileReader(new File(\"inexist\")); // only potential problem: ctor X below might close r2\n" +
3979
			"        new X(r2).foo(new FileReader(new File(\"notthere\")));\n" +
3980
			"    }\n" +
3981
			"}\n"
3982
		},
3983
		"----------\n" + 
3984
		"1. ERROR in X.java (at line 8)\n" + 
3985
		"	FileReader fileReader = getReader();\n" + 
3986
		"	           ^^^^^^^^^^\n" + 
3987
		"Resource \'fileReader\' should be managed by try-with-resource\n" + 
3988
		"----------\n" + 
3989
		"2. ERROR in X.java (at line 11)\n" + 
3990
		"	FileReader r3 = getReader();\n" + 
3991
		"	           ^^\n" + 
3992
		"Resource \'r3\' should be managed by try-with-resource\n" + 
3993
		"----------\n" + 
3994
		"3. ERROR in X.java (at line 24)\n" + 
3995
		"	FileReader r2 = new FileReader(new File(\"inexist\")); // only potential problem: ctor X below might close r2\n" + 
3996
		"	           ^^\n" + 
3997
		"Potentially leaking resource 'r2': is not closed on all paths\n" + 
3998
		"----------\n",
3999
		null,
4000
		true,
4001
		options);
4002
}
4003
// Bug 349326 - [1.7] new warning for missing try-with-resources
4004
// nested try with early exit
4005
public void test055m() {
4006
	Map options = getCompilerOptions();
4007
	options.put(CompilerOptions.OPTION_ReportUnclosedCloseable, CompilerOptions.ERROR);
4008
	options.put(CompilerOptions.OPTION_ReportPotentiallyUnclosedCloseable, CompilerOptions.ERROR);
4009
	this.runConformTest(
4010
		new String[] {
4011
			"X.java",
4012
			"import java.io.File;\n" +
4013
			"import java.io.FileReader;\n" +
4014
			"import java.io.IOException;\n" +
4015
			"public class X {\n" +
4016
			"    void foo() {\n" +
4017
			"        File file = new File(\"somefile\");" +
4018
			"        try {\n" +
4019
			"            FileReader fileReader = new FileReader(file);\n" +
4020
			"            try {\n" +
4021
			"                char[] in = new char[50];\n" +
4022
			"                if (fileReader.read(in)==0)\n" +
4023
			"                    return;\n" +
4024
			"            } finally {\n" +
4025
			"		         fileReader.close();\n" +
4026
			"            }\n" +
4027
			"        } catch (IOException e) {\n" +
4028
			"            System.out.println(\"caught\");\n" +
4029
			"        }\n" +
4030
			"    }\n" +
4031
			"    public static void main(String[] args) {\n" +
4032
			"        new X().foo();\n" +
4033
			"    }\n" +
4034
			"}\n"
4035
		},
4036
		"caught", /*output*/
4037
		null/*classLibs*/,
4038
		true/*shouldFlush*/,
4039
		null/*vmargs*/,
4040
		options,
4041
		null/*requestor*/);
4042
}
4043
// Bug 349326 - [1.7] new warning for missing try-with-resources
4044
// nested try should not interfere with earlier analysis.
4045
public void test055n() {
4046
	Map options = getCompilerOptions();
4047
	options.put(CompilerOptions.OPTION_ReportUnclosedCloseable, CompilerOptions.ERROR);
4048
	options.put(CompilerOptions.OPTION_ReportPotentiallyUnclosedCloseable, CompilerOptions.ERROR);
4049
	this.runConformTest(
4050
		new String[] {
4051
			"X.java",
4052
			"import java.io.File;\n" +
4053
			"import java.io.FileReader;\n" +
4054
			"import java.io.IOException;\n" +
4055
			"import java.io.FileNotFoundException;\n" +
4056
			"public class X {\n" +
4057
			"    void foo(File someFile, char[] buf) throws IOException {\n" + 
4058
			"		FileReader fr1 = new FileReader(someFile);\n" + 
4059
			"		try {\n" + 
4060
			"			fr1.read(buf);\n" + 
4061
			"		} finally {\n" + 
4062
			"			fr1.close();\n" + 
4063
			"		}\n" + 
4064
			"		try {\n" + 
4065
			"			FileReader fr3 = new FileReader(someFile);\n" + 
4066
			"			try {\n" + 
4067
			"			} finally {\n" + 
4068
			"				fr3.close();\n" + 
4069
			"			}\n" + 
4070
			"		} catch (IOException e) {\n" + 
4071
			"		}\n" + 
4072
			"	 }\n" +
4073
			"    public static void main(String[] args) throws IOException {\n" +
4074
			"        try {\n" +
4075
			"            new X().foo(new File(\"missing\"), new char[100]);\n" +
4076
			"        } catch (FileNotFoundException e) {\n" +
4077
			"            System.out.println(\"caught\");\n" +
4078
			"        }\n" +
4079
			"    }\n" +
4080
			"}\n"
4081
		},
4082
		"caught", /*output*/
4083
		null/*classLibs*/,
4084
		true/*shouldFlush*/,
4085
		null/*vmargs*/,
4086
		options,
4087
		null/*requestor*/);
4088
}
4089
// Bug 349326 - [1.7] new warning for missing try-with-resources
4090
// if close is guarded by null check this should still be recognized as definitely closed
4091
public void test055o() {
4092
	Map options = getCompilerOptions();
4093
	options.put(CompilerOptions.OPTION_ReportUnclosedCloseable, CompilerOptions.ERROR);
4094
	options.put(CompilerOptions.OPTION_ReportPotentiallyUnclosedCloseable, CompilerOptions.ERROR);
4095
	this.runConformTest(
4096
		new String[] {
4097
			"X.java",
4098
			"import java.io.File;\n" +
4099
			"import java.io.FileReader;\n" +
4100
			"import java.io.IOException;\n" +
4101
			"import java.io.FileNotFoundException;\n" +
4102
			"public class X {\n" +
4103
			"    void foo(File someFile, char[] buf) throws IOException {\n" + 
4104
			"		FileReader fr1 = null;\n" + 
4105
			"		try {\n" +
4106
			"           fr1 = new FileReader(someFile);" + 
4107
			"			fr1.read(buf);\n" + 
4108
			"		} finally {\n" + 
4109
			"			if (fr1 != null)\n" +
4110
			"               try {\n" +
4111
			"                   fr1.close();\n" +
4112
			"               } catch (IOException e) { /*do nothing*/ }\n" + 
4113
			"		}\n" + 
4114
			"	 }\n" +
4115
			"    public static void main(String[] args) throws IOException {\n" +
4116
			"        try {\n" +
4117
			"            new X().foo(new File(\"missing\"), new char[100]);\n" +
4118
			"        } catch (FileNotFoundException e) {\n" +
4119
			"            System.out.println(\"caught\");\n" +
4120
			"        }\n" +
4121
			"    }\n" +
4122
			"}\n"
4123
		},
4124
		"caught", /*output*/
4125
		null/*classLibs*/,
4126
		true/*shouldFlush*/,
4127
		null/*vmargs*/,
4128
		options,
4129
		null/*requestor*/);
4130
}
4131
// Bug 349326 - [1.7] new warning for missing try-with-resources
4132
// a method uses an AutoCloseable without ever closing it, type from a type variable
4133
public void test055p() {
4134
	Map options = getCompilerOptions();
4135
	options.put(CompilerOptions.OPTION_ReportUnclosedCloseable, CompilerOptions.ERROR);
4136
	options.put(CompilerOptions.OPTION_ReportPotentiallyUnclosedCloseable, CompilerOptions.WARNING);
4137
	this.runNegativeTest(
4138
		new String[] {
4139
			"X.java",
4140
			"import java.io.File;\n" +
4141
			"import java.io.FileReader;\n" +
4142
			"import java.io.Reader;\n" +
4143
			"import java.io.IOException;\n" +
4144
			"public abstract class X <T extends Reader> {\n" +
4145
			"    void foo() throws IOException {\n" +
4146
			"        File file = new File(\"somefile\");\n" +
4147
			"        T fileReader = newReader(file);\n" +
4148
			"        char[] in = new char[50];\n" +
4149
			"        fileReader.read(in);\n" +
4150
			"    }\n" +
4151
			"    abstract T newReader(File file) throws IOException;\n" +
4152
			"    public static void main(String[] args) throws IOException {\n" +
4153
			"        new X<FileReader>() {\n" +
4154
			"            FileReader newReader(File f) throws IOException { return new FileReader(f); }\n" +
4155
			"        }.foo();\n" +
4156
			"    }\n" +
4157
			"}\n"
4158
		},
4159
		"----------\n" + 
4160
		"1. ERROR in X.java (at line 8)\n" + 
4161
		"	T fileReader = newReader(file);\n" + 
4162
		"	  ^^^^^^^^^^\n" + 
4163
		"Leaking resource 'fileReader': is never closed\n" +
4164
		"----------\n",
4165
		null,
4166
		true,
4167
		options);
4168
}
3340
public static Class testClass() {
4169
public static Class testClass() {
3341
	return TryWithResourcesStatementTest.class;
4170
	return TryWithResourcesStatementTest.class;
3342
}
4171
}

Return to bug 349326