Some Eclipse Foundation services are deprecated, or will be soon. Please ensure you've read this important communication.
View | Details | Raw Unified | Return to bug 359724 | Differences between
and this patch

Collapse All | Expand All

(-)a/.gitignore (-6 / +5 lines)
Lines 1-4 Link Here
1
bin/
1
/*/bin/
2
*~
2
*~
3
*.rej
3
*.rej
4
*.bak
4
*.bak
Lines 7-14 Link Here
7
heapdump.*
7
heapdump.*
8
core.*
8
core.*
9
Snap.*
9
Snap.*
10
target/
10
/*/bin-resources/
11
bin-resources/
11
/*/binext/
12
binext/
12
/*/binprocessors/
13
binprocessors/
13
/*/antbin/
14
antbin/
(-)a/org.eclipse.jdt.annotation/.classpath (+7 lines)
Added Link Here
1
<?xml version="1.0" encoding="UTF-8"?>
2
<classpath>
3
	<classpathentry kind="src" path="src"/>
4
	<classpathentry kind="con" path="org.eclipse.jdt.launching.JRE_CONTAINER/org.eclipse.jdt.internal.debug.ui.launcher.StandardVMType/J2SE-1.5"/>
5
	<classpathentry kind="con" path="org.eclipse.pde.core.requiredPlugins"/>
6
	<classpathentry kind="output" path="bin"/>
7
</classpath>
(-)a/org.eclipse.jdt.annotation/.project (+34 lines)
Added Link Here
1
<?xml version="1.0" encoding="UTF-8"?>
2
<projectDescription>
3
	<name>org.eclipse.jdt.annotation</name>
4
	<comment></comment>
5
	<projects>
6
	</projects>
7
	<buildSpec>
8
		<buildCommand>
9
			<name>org.eclipse.jdt.core.javabuilder</name>
10
			<arguments>
11
			</arguments>
12
		</buildCommand>
13
		<buildCommand>
14
			<name>org.eclipse.pde.ManifestBuilder</name>
15
			<arguments>
16
			</arguments>
17
		</buildCommand>
18
		<buildCommand>
19
			<name>org.eclipse.pde.SchemaBuilder</name>
20
			<arguments>
21
			</arguments>
22
		</buildCommand>
23
		<buildCommand>
24
			<name>org.eclipse.pde.api.tools.apiAnalysisBuilder</name>
25
			<arguments>
26
			</arguments>
27
		</buildCommand>
28
	</buildSpec>
29
	<natures>
30
		<nature>org.eclipse.jdt.core.javanature</nature>
31
		<nature>org.eclipse.pde.PluginNature</nature>
32
		<nature>org.eclipse.pde.api.tools.apiAnalysisNature</nature>
33
	</natures>
34
</projectDescription>
(-)a/org.eclipse.jdt.annotation/.settings/org.eclipse.core.runtime.prefs (+2 lines)
Added Link Here
1
eclipse.preferences.version=1
2
line.separator=\n
(-)a/org.eclipse.jdt.annotation/.settings/org.eclipse.jdt.core.prefs (+364 lines)
Added Link Here
1
eclipse.preferences.version=1
2
org.eclipse.jdt.core.builder.cleanOutputFolder=clean
3
org.eclipse.jdt.core.builder.duplicateResourceTask=warning
4
org.eclipse.jdt.core.builder.invalidClasspath=abort
5
org.eclipse.jdt.core.builder.recreateModifiedClassFileInOutputFolder=ignore
6
org.eclipse.jdt.core.builder.resourceCopyExclusionFilter=*.launch,.svn/
7
org.eclipse.jdt.core.circularClasspath=error
8
org.eclipse.jdt.core.classpath.exclusionPatterns=enabled
9
org.eclipse.jdt.core.classpath.multipleOutputLocations=enabled
10
org.eclipse.jdt.core.compiler.codegen.inlineJsrBytecode=enabled
11
org.eclipse.jdt.core.compiler.codegen.targetPlatform=1.5
12
org.eclipse.jdt.core.compiler.codegen.unusedLocal=preserve
13
org.eclipse.jdt.core.compiler.compliance=1.5
14
org.eclipse.jdt.core.compiler.debug.lineNumber=generate
15
org.eclipse.jdt.core.compiler.debug.localVariable=generate
16
org.eclipse.jdt.core.compiler.debug.sourceFile=generate
17
org.eclipse.jdt.core.compiler.doc.comment.support=enabled
18
org.eclipse.jdt.core.compiler.maxProblemPerUnit=100
19
org.eclipse.jdt.core.compiler.problem.annotationSuperInterface=warning
20
org.eclipse.jdt.core.compiler.problem.assertIdentifier=error
21
org.eclipse.jdt.core.compiler.problem.autoboxing=warning
22
org.eclipse.jdt.core.compiler.problem.comparingIdentical=warning
23
org.eclipse.jdt.core.compiler.problem.deadCode=warning
24
org.eclipse.jdt.core.compiler.problem.deprecation=warning
25
org.eclipse.jdt.core.compiler.problem.deprecationInDeprecatedCode=disabled
26
org.eclipse.jdt.core.compiler.problem.deprecationWhenOverridingDeprecatedMethod=disabled
27
org.eclipse.jdt.core.compiler.problem.discouragedReference=warning
28
org.eclipse.jdt.core.compiler.problem.emptyStatement=warning
29
org.eclipse.jdt.core.compiler.problem.enumIdentifier=error
30
org.eclipse.jdt.core.compiler.problem.explicitlyClosedAutoCloseable=warning
31
org.eclipse.jdt.core.compiler.problem.fallthroughCase=warning
32
org.eclipse.jdt.core.compiler.problem.fatalOptionalError=enabled
33
org.eclipse.jdt.core.compiler.problem.fieldHiding=warning
34
org.eclipse.jdt.core.compiler.problem.finalParameterBound=warning
35
org.eclipse.jdt.core.compiler.problem.finallyBlockNotCompletingNormally=warning
36
org.eclipse.jdt.core.compiler.problem.forbiddenReference=error
37
org.eclipse.jdt.core.compiler.problem.hiddenCatchBlock=warning
38
org.eclipse.jdt.core.compiler.problem.includeNullInfoFromAsserts=disabled
39
org.eclipse.jdt.core.compiler.problem.incompatibleNonInheritedInterfaceMethod=warning
40
org.eclipse.jdt.core.compiler.problem.incompleteEnumSwitch=warning
41
org.eclipse.jdt.core.compiler.problem.indirectStaticAccess=warning
42
org.eclipse.jdt.core.compiler.problem.invalidJavadoc=warning
43
org.eclipse.jdt.core.compiler.problem.invalidJavadocTags=enabled
44
org.eclipse.jdt.core.compiler.problem.invalidJavadocTagsDeprecatedRef=enabled
45
org.eclipse.jdt.core.compiler.problem.invalidJavadocTagsNotVisibleRef=enabled
46
org.eclipse.jdt.core.compiler.problem.invalidJavadocTagsVisibility=private
47
org.eclipse.jdt.core.compiler.problem.localVariableHiding=warning
48
org.eclipse.jdt.core.compiler.problem.methodWithConstructorName=warning
49
org.eclipse.jdt.core.compiler.problem.missingDeprecatedAnnotation=ignore
50
org.eclipse.jdt.core.compiler.problem.missingHashCodeMethod=warning
51
org.eclipse.jdt.core.compiler.problem.missingJavadocComments=ignore
52
org.eclipse.jdt.core.compiler.problem.missingJavadocCommentsOverriding=enabled
53
org.eclipse.jdt.core.compiler.problem.missingJavadocCommentsVisibility=public
54
org.eclipse.jdt.core.compiler.problem.missingJavadocTags=ignore
55
org.eclipse.jdt.core.compiler.problem.missingJavadocTagsOverriding=enabled
56
org.eclipse.jdt.core.compiler.problem.missingJavadocTagsVisibility=private
57
org.eclipse.jdt.core.compiler.problem.missingOverrideAnnotation=warning
58
org.eclipse.jdt.core.compiler.problem.missingOverrideAnnotationForInterfaceMethodImplementation=enabled
59
org.eclipse.jdt.core.compiler.problem.missingSerialVersion=warning
60
org.eclipse.jdt.core.compiler.problem.missingSynchronizedOnInheritedMethod=warning
61
org.eclipse.jdt.core.compiler.problem.noEffectAssignment=warning
62
org.eclipse.jdt.core.compiler.problem.noImplicitStringConversion=warning
63
org.eclipse.jdt.core.compiler.problem.nonExternalizedStringLiteral=warning
64
org.eclipse.jdt.core.compiler.problem.nullReference=warning
65
org.eclipse.jdt.core.compiler.problem.overridingPackageDefaultMethod=warning
66
org.eclipse.jdt.core.compiler.problem.parameterAssignment=ignore
67
org.eclipse.jdt.core.compiler.problem.possibleAccidentalBooleanAssignment=warning
68
org.eclipse.jdt.core.compiler.problem.potentialNullReference=ignore
69
org.eclipse.jdt.core.compiler.problem.potentiallyUnclosedCloseable=warning
70
org.eclipse.jdt.core.compiler.problem.rawTypeReference=warning
71
org.eclipse.jdt.core.compiler.problem.redundantNullCheck=warning
72
org.eclipse.jdt.core.compiler.problem.redundantSpecificationOfTypeArguments=warning
73
org.eclipse.jdt.core.compiler.problem.redundantSuperinterface=warning
74
org.eclipse.jdt.core.compiler.problem.reportMethodCanBePotentiallyStatic=ignore
75
org.eclipse.jdt.core.compiler.problem.reportMethodCanBeStatic=ignore
76
org.eclipse.jdt.core.compiler.problem.specialParameterHidingField=disabled
77
org.eclipse.jdt.core.compiler.problem.staticAccessReceiver=warning
78
org.eclipse.jdt.core.compiler.problem.suppressOptionalErrors=disabled
79
org.eclipse.jdt.core.compiler.problem.suppressWarnings=enabled
80
org.eclipse.jdt.core.compiler.problem.syntheticAccessEmulation=warning
81
org.eclipse.jdt.core.compiler.problem.typeParameterHiding=warning
82
org.eclipse.jdt.core.compiler.problem.unavoidableGenericTypeProblems=disabled
83
org.eclipse.jdt.core.compiler.problem.uncheckedTypeOperation=warning
84
org.eclipse.jdt.core.compiler.problem.unclosedCloseable=warning
85
org.eclipse.jdt.core.compiler.problem.undocumentedEmptyBlock=warning
86
org.eclipse.jdt.core.compiler.problem.unhandledWarningToken=warning
87
org.eclipse.jdt.core.compiler.problem.unnecessaryElse=ignore
88
org.eclipse.jdt.core.compiler.problem.unnecessaryTypeCheck=warning
89
org.eclipse.jdt.core.compiler.problem.unqualifiedFieldAccess=warning
90
org.eclipse.jdt.core.compiler.problem.unsafeTypeOperation=warning
91
org.eclipse.jdt.core.compiler.problem.unusedDeclaredThrownException=ignore
92
org.eclipse.jdt.core.compiler.problem.unusedDeclaredThrownExceptionExemptExceptionAndThrowable=enabled
93
org.eclipse.jdt.core.compiler.problem.unusedDeclaredThrownExceptionIncludeDocCommentReference=enabled
94
org.eclipse.jdt.core.compiler.problem.unusedDeclaredThrownExceptionWhenOverriding=disabled
95
org.eclipse.jdt.core.compiler.problem.unusedImport=error
96
org.eclipse.jdt.core.compiler.problem.unusedLabel=warning
97
org.eclipse.jdt.core.compiler.problem.unusedLocal=warning
98
org.eclipse.jdt.core.compiler.problem.unusedObjectAllocation=warning
99
org.eclipse.jdt.core.compiler.problem.unusedParameter=ignore
100
org.eclipse.jdt.core.compiler.problem.unusedParameterIncludeDocCommentReference=enabled
101
org.eclipse.jdt.core.compiler.problem.unusedParameterWhenImplementingAbstract=disabled
102
org.eclipse.jdt.core.compiler.problem.unusedParameterWhenOverridingConcrete=disabled
103
org.eclipse.jdt.core.compiler.problem.unusedPrivateMember=warning
104
org.eclipse.jdt.core.compiler.problem.unusedWarningToken=warning
105
org.eclipse.jdt.core.compiler.problem.varargsArgumentNeedCast=warning
106
org.eclipse.jdt.core.compiler.source=1.5
107
org.eclipse.jdt.core.formatter.align_type_members_on_columns=false
108
org.eclipse.jdt.core.formatter.alignment_for_arguments_in_allocation_expression=16
109
org.eclipse.jdt.core.formatter.alignment_for_arguments_in_enum_constant=16
110
org.eclipse.jdt.core.formatter.alignment_for_arguments_in_explicit_constructor_call=16
111
org.eclipse.jdt.core.formatter.alignment_for_arguments_in_method_invocation=16
112
org.eclipse.jdt.core.formatter.alignment_for_arguments_in_qualified_allocation_expression=16
113
org.eclipse.jdt.core.formatter.alignment_for_assignment=0
114
org.eclipse.jdt.core.formatter.alignment_for_binary_expression=16
115
org.eclipse.jdt.core.formatter.alignment_for_compact_if=16
116
org.eclipse.jdt.core.formatter.alignment_for_conditional_expression=80
117
org.eclipse.jdt.core.formatter.alignment_for_enum_constants=0
118
org.eclipse.jdt.core.formatter.alignment_for_expressions_in_array_initializer=16
119
org.eclipse.jdt.core.formatter.alignment_for_multiple_fields=16
120
org.eclipse.jdt.core.formatter.alignment_for_parameters_in_constructor_declaration=16
121
org.eclipse.jdt.core.formatter.alignment_for_parameters_in_method_declaration=16
122
org.eclipse.jdt.core.formatter.alignment_for_selector_in_method_invocation=16
123
org.eclipse.jdt.core.formatter.alignment_for_superclass_in_type_declaration=16
124
org.eclipse.jdt.core.formatter.alignment_for_superinterfaces_in_enum_declaration=16
125
org.eclipse.jdt.core.formatter.alignment_for_superinterfaces_in_type_declaration=16
126
org.eclipse.jdt.core.formatter.alignment_for_throws_clause_in_constructor_declaration=16
127
org.eclipse.jdt.core.formatter.alignment_for_throws_clause_in_method_declaration=16
128
org.eclipse.jdt.core.formatter.blank_lines_after_imports=1
129
org.eclipse.jdt.core.formatter.blank_lines_after_package=1
130
org.eclipse.jdt.core.formatter.blank_lines_before_field=0
131
org.eclipse.jdt.core.formatter.blank_lines_before_first_class_body_declaration=0
132
org.eclipse.jdt.core.formatter.blank_lines_before_imports=1
133
org.eclipse.jdt.core.formatter.blank_lines_before_member_type=1
134
org.eclipse.jdt.core.formatter.blank_lines_before_method=1
135
org.eclipse.jdt.core.formatter.blank_lines_before_new_chunk=1
136
org.eclipse.jdt.core.formatter.blank_lines_before_package=0
137
org.eclipse.jdt.core.formatter.blank_lines_between_import_groups=1
138
org.eclipse.jdt.core.formatter.blank_lines_between_type_declarations=1
139
org.eclipse.jdt.core.formatter.brace_position_for_annotation_type_declaration=end_of_line
140
org.eclipse.jdt.core.formatter.brace_position_for_anonymous_type_declaration=end_of_line
141
org.eclipse.jdt.core.formatter.brace_position_for_array_initializer=end_of_line
142
org.eclipse.jdt.core.formatter.brace_position_for_block=end_of_line
143
org.eclipse.jdt.core.formatter.brace_position_for_block_in_case=end_of_line
144
org.eclipse.jdt.core.formatter.brace_position_for_constructor_declaration=end_of_line
145
org.eclipse.jdt.core.formatter.brace_position_for_enum_constant=end_of_line
146
org.eclipse.jdt.core.formatter.brace_position_for_enum_declaration=end_of_line
147
org.eclipse.jdt.core.formatter.brace_position_for_method_declaration=end_of_line
148
org.eclipse.jdt.core.formatter.brace_position_for_switch=end_of_line
149
org.eclipse.jdt.core.formatter.brace_position_for_type_declaration=end_of_line
150
org.eclipse.jdt.core.formatter.comment.clear_blank_lines_in_block_comment=false
151
org.eclipse.jdt.core.formatter.comment.clear_blank_lines_in_javadoc_comment=false
152
org.eclipse.jdt.core.formatter.comment.format_block_comments=true
153
org.eclipse.jdt.core.formatter.comment.format_header=false
154
org.eclipse.jdt.core.formatter.comment.format_html=true
155
org.eclipse.jdt.core.formatter.comment.format_javadoc_comments=true
156
org.eclipse.jdt.core.formatter.comment.format_line_comments=true
157
org.eclipse.jdt.core.formatter.comment.format_source_code=true
158
org.eclipse.jdt.core.formatter.comment.indent_parameter_description=true
159
org.eclipse.jdt.core.formatter.comment.indent_root_tags=true
160
org.eclipse.jdt.core.formatter.comment.insert_new_line_before_root_tags=insert
161
org.eclipse.jdt.core.formatter.comment.insert_new_line_for_parameter=insert
162
org.eclipse.jdt.core.formatter.comment.line_length=120
163
org.eclipse.jdt.core.formatter.compact_else_if=true
164
org.eclipse.jdt.core.formatter.continuation_indentation=2
165
org.eclipse.jdt.core.formatter.continuation_indentation_for_array_initializer=2
166
org.eclipse.jdt.core.formatter.format_guardian_clause_on_one_line=false
167
org.eclipse.jdt.core.formatter.indent_body_declarations_compare_to_annotation_declaration_header=true
168
org.eclipse.jdt.core.formatter.indent_body_declarations_compare_to_enum_constant_header=true
169
org.eclipse.jdt.core.formatter.indent_body_declarations_compare_to_enum_declaration_header=true
170
org.eclipse.jdt.core.formatter.indent_body_declarations_compare_to_type_header=true
171
org.eclipse.jdt.core.formatter.indent_breaks_compare_to_cases=true
172
org.eclipse.jdt.core.formatter.indent_empty_lines=false
173
org.eclipse.jdt.core.formatter.indent_statements_compare_to_block=true
174
org.eclipse.jdt.core.formatter.indent_statements_compare_to_body=true
175
org.eclipse.jdt.core.formatter.indent_switchstatements_compare_to_cases=true
176
org.eclipse.jdt.core.formatter.indent_switchstatements_compare_to_switch=true
177
org.eclipse.jdt.core.formatter.indentation.size=4
178
org.eclipse.jdt.core.formatter.insert_new_line_after_annotation_on_local_variable=insert
179
org.eclipse.jdt.core.formatter.insert_new_line_after_annotation_on_member=insert
180
org.eclipse.jdt.core.formatter.insert_new_line_after_annotation_on_parameter=do not insert
181
org.eclipse.jdt.core.formatter.insert_new_line_after_opening_brace_in_array_initializer=do not insert
182
org.eclipse.jdt.core.formatter.insert_new_line_at_end_of_file_if_missing=do not insert
183
org.eclipse.jdt.core.formatter.insert_new_line_before_catch_in_try_statement=do not insert
184
org.eclipse.jdt.core.formatter.insert_new_line_before_closing_brace_in_array_initializer=do not insert
185
org.eclipse.jdt.core.formatter.insert_new_line_before_else_in_if_statement=do not insert
186
org.eclipse.jdt.core.formatter.insert_new_line_before_finally_in_try_statement=do not insert
187
org.eclipse.jdt.core.formatter.insert_new_line_before_while_in_do_statement=do not insert
188
org.eclipse.jdt.core.formatter.insert_new_line_in_empty_annotation_declaration=insert
189
org.eclipse.jdt.core.formatter.insert_new_line_in_empty_anonymous_type_declaration=insert
190
org.eclipse.jdt.core.formatter.insert_new_line_in_empty_block=insert
191
org.eclipse.jdt.core.formatter.insert_new_line_in_empty_enum_constant=insert
192
org.eclipse.jdt.core.formatter.insert_new_line_in_empty_enum_declaration=insert
193
org.eclipse.jdt.core.formatter.insert_new_line_in_empty_method_body=insert
194
org.eclipse.jdt.core.formatter.insert_new_line_in_empty_type_declaration=insert
195
org.eclipse.jdt.core.formatter.insert_space_after_and_in_type_parameter=insert
196
org.eclipse.jdt.core.formatter.insert_space_after_assignment_operator=insert
197
org.eclipse.jdt.core.formatter.insert_space_after_at_in_annotation=do not insert
198
org.eclipse.jdt.core.formatter.insert_space_after_at_in_annotation_type_declaration=do not insert
199
org.eclipse.jdt.core.formatter.insert_space_after_binary_operator=insert
200
org.eclipse.jdt.core.formatter.insert_space_after_closing_angle_bracket_in_type_arguments=insert
201
org.eclipse.jdt.core.formatter.insert_space_after_closing_angle_bracket_in_type_parameters=insert
202
org.eclipse.jdt.core.formatter.insert_space_after_closing_brace_in_block=insert
203
org.eclipse.jdt.core.formatter.insert_space_after_closing_paren_in_cast=insert
204
org.eclipse.jdt.core.formatter.insert_space_after_colon_in_assert=insert
205
org.eclipse.jdt.core.formatter.insert_space_after_colon_in_case=insert
206
org.eclipse.jdt.core.formatter.insert_space_after_colon_in_conditional=insert
207
org.eclipse.jdt.core.formatter.insert_space_after_colon_in_for=insert
208
org.eclipse.jdt.core.formatter.insert_space_after_colon_in_labeled_statement=insert
209
org.eclipse.jdt.core.formatter.insert_space_after_comma_in_allocation_expression=insert
210
org.eclipse.jdt.core.formatter.insert_space_after_comma_in_annotation=insert
211
org.eclipse.jdt.core.formatter.insert_space_after_comma_in_array_initializer=insert
212
org.eclipse.jdt.core.formatter.insert_space_after_comma_in_constructor_declaration_parameters=insert
213
org.eclipse.jdt.core.formatter.insert_space_after_comma_in_constructor_declaration_throws=insert
214
org.eclipse.jdt.core.formatter.insert_space_after_comma_in_enum_constant_arguments=insert
215
org.eclipse.jdt.core.formatter.insert_space_after_comma_in_enum_declarations=insert
216
org.eclipse.jdt.core.formatter.insert_space_after_comma_in_explicitconstructorcall_arguments=insert
217
org.eclipse.jdt.core.formatter.insert_space_after_comma_in_for_increments=insert
218
org.eclipse.jdt.core.formatter.insert_space_after_comma_in_for_inits=insert
219
org.eclipse.jdt.core.formatter.insert_space_after_comma_in_method_declaration_parameters=insert
220
org.eclipse.jdt.core.formatter.insert_space_after_comma_in_method_declaration_throws=insert
221
org.eclipse.jdt.core.formatter.insert_space_after_comma_in_method_invocation_arguments=insert
222
org.eclipse.jdt.core.formatter.insert_space_after_comma_in_multiple_field_declarations=insert
223
org.eclipse.jdt.core.formatter.insert_space_after_comma_in_multiple_local_declarations=insert
224
org.eclipse.jdt.core.formatter.insert_space_after_comma_in_parameterized_type_reference=insert
225
org.eclipse.jdt.core.formatter.insert_space_after_comma_in_superinterfaces=insert
226
org.eclipse.jdt.core.formatter.insert_space_after_comma_in_type_arguments=insert
227
org.eclipse.jdt.core.formatter.insert_space_after_comma_in_type_parameters=insert
228
org.eclipse.jdt.core.formatter.insert_space_after_ellipsis=insert
229
org.eclipse.jdt.core.formatter.insert_space_after_opening_angle_bracket_in_parameterized_type_reference=do not insert
230
org.eclipse.jdt.core.formatter.insert_space_after_opening_angle_bracket_in_type_arguments=do not insert
231
org.eclipse.jdt.core.formatter.insert_space_after_opening_angle_bracket_in_type_parameters=do not insert
232
org.eclipse.jdt.core.formatter.insert_space_after_opening_brace_in_array_initializer=insert
233
org.eclipse.jdt.core.formatter.insert_space_after_opening_bracket_in_array_allocation_expression=do not insert
234
org.eclipse.jdt.core.formatter.insert_space_after_opening_bracket_in_array_reference=do not insert
235
org.eclipse.jdt.core.formatter.insert_space_after_opening_paren_in_annotation=do not insert
236
org.eclipse.jdt.core.formatter.insert_space_after_opening_paren_in_cast=do not insert
237
org.eclipse.jdt.core.formatter.insert_space_after_opening_paren_in_catch=do not insert
238
org.eclipse.jdt.core.formatter.insert_space_after_opening_paren_in_constructor_declaration=do not insert
239
org.eclipse.jdt.core.formatter.insert_space_after_opening_paren_in_enum_constant=do not insert
240
org.eclipse.jdt.core.formatter.insert_space_after_opening_paren_in_for=do not insert
241
org.eclipse.jdt.core.formatter.insert_space_after_opening_paren_in_if=do not insert
242
org.eclipse.jdt.core.formatter.insert_space_after_opening_paren_in_method_declaration=do not insert
243
org.eclipse.jdt.core.formatter.insert_space_after_opening_paren_in_method_invocation=do not insert
244
org.eclipse.jdt.core.formatter.insert_space_after_opening_paren_in_parenthesized_expression=do not insert
245
org.eclipse.jdt.core.formatter.insert_space_after_opening_paren_in_switch=do not insert
246
org.eclipse.jdt.core.formatter.insert_space_after_opening_paren_in_synchronized=do not insert
247
org.eclipse.jdt.core.formatter.insert_space_after_opening_paren_in_while=do not insert
248
org.eclipse.jdt.core.formatter.insert_space_after_postfix_operator=do not insert
249
org.eclipse.jdt.core.formatter.insert_space_after_prefix_operator=do not insert
250
org.eclipse.jdt.core.formatter.insert_space_after_question_in_conditional=insert
251
org.eclipse.jdt.core.formatter.insert_space_after_question_in_wildcard=do not insert
252
org.eclipse.jdt.core.formatter.insert_space_after_semicolon_in_for=insert
253
org.eclipse.jdt.core.formatter.insert_space_after_unary_operator=do not insert
254
org.eclipse.jdt.core.formatter.insert_space_before_and_in_type_parameter=insert
255
org.eclipse.jdt.core.formatter.insert_space_before_assignment_operator=insert
256
org.eclipse.jdt.core.formatter.insert_space_before_at_in_annotation_type_declaration=insert
257
org.eclipse.jdt.core.formatter.insert_space_before_binary_operator=insert
258
org.eclipse.jdt.core.formatter.insert_space_before_closing_angle_bracket_in_parameterized_type_reference=do not insert
259
org.eclipse.jdt.core.formatter.insert_space_before_closing_angle_bracket_in_type_arguments=do not insert
260
org.eclipse.jdt.core.formatter.insert_space_before_closing_angle_bracket_in_type_parameters=do not insert
261
org.eclipse.jdt.core.formatter.insert_space_before_closing_brace_in_array_initializer=insert
262
org.eclipse.jdt.core.formatter.insert_space_before_closing_bracket_in_array_allocation_expression=do not insert
263
org.eclipse.jdt.core.formatter.insert_space_before_closing_bracket_in_array_reference=do not insert
264
org.eclipse.jdt.core.formatter.insert_space_before_closing_paren_in_annotation=do not insert
265
org.eclipse.jdt.core.formatter.insert_space_before_closing_paren_in_cast=do not insert
266
org.eclipse.jdt.core.formatter.insert_space_before_closing_paren_in_catch=do not insert
267
org.eclipse.jdt.core.formatter.insert_space_before_closing_paren_in_constructor_declaration=do not insert
268
org.eclipse.jdt.core.formatter.insert_space_before_closing_paren_in_enum_constant=do not insert
269
org.eclipse.jdt.core.formatter.insert_space_before_closing_paren_in_for=do not insert
270
org.eclipse.jdt.core.formatter.insert_space_before_closing_paren_in_if=do not insert
271
org.eclipse.jdt.core.formatter.insert_space_before_closing_paren_in_method_declaration=do not insert
272
org.eclipse.jdt.core.formatter.insert_space_before_closing_paren_in_method_invocation=do not insert
273
org.eclipse.jdt.core.formatter.insert_space_before_closing_paren_in_parenthesized_expression=do not insert
274
org.eclipse.jdt.core.formatter.insert_space_before_closing_paren_in_switch=do not insert
275
org.eclipse.jdt.core.formatter.insert_space_before_closing_paren_in_synchronized=do not insert
276
org.eclipse.jdt.core.formatter.insert_space_before_closing_paren_in_while=do not insert
277
org.eclipse.jdt.core.formatter.insert_space_before_colon_in_assert=insert
278
org.eclipse.jdt.core.formatter.insert_space_before_colon_in_case=do not insert
279
org.eclipse.jdt.core.formatter.insert_space_before_colon_in_conditional=insert
280
org.eclipse.jdt.core.formatter.insert_space_before_colon_in_default=do not insert
281
org.eclipse.jdt.core.formatter.insert_space_before_colon_in_for=insert
282
org.eclipse.jdt.core.formatter.insert_space_before_colon_in_labeled_statement=do not insert
283
org.eclipse.jdt.core.formatter.insert_space_before_comma_in_allocation_expression=do not insert
284
org.eclipse.jdt.core.formatter.insert_space_before_comma_in_annotation=do not insert
285
org.eclipse.jdt.core.formatter.insert_space_before_comma_in_array_initializer=do not insert
286
org.eclipse.jdt.core.formatter.insert_space_before_comma_in_constructor_declaration_parameters=do not insert
287
org.eclipse.jdt.core.formatter.insert_space_before_comma_in_constructor_declaration_throws=do not insert
288
org.eclipse.jdt.core.formatter.insert_space_before_comma_in_enum_constant_arguments=do not insert
289
org.eclipse.jdt.core.formatter.insert_space_before_comma_in_enum_declarations=do not insert
290
org.eclipse.jdt.core.formatter.insert_space_before_comma_in_explicitconstructorcall_arguments=do not insert
291
org.eclipse.jdt.core.formatter.insert_space_before_comma_in_for_increments=do not insert
292
org.eclipse.jdt.core.formatter.insert_space_before_comma_in_for_inits=do not insert
293
org.eclipse.jdt.core.formatter.insert_space_before_comma_in_method_declaration_parameters=do not insert
294
org.eclipse.jdt.core.formatter.insert_space_before_comma_in_method_declaration_throws=do not insert
295
org.eclipse.jdt.core.formatter.insert_space_before_comma_in_method_invocation_arguments=do not insert
296
org.eclipse.jdt.core.formatter.insert_space_before_comma_in_multiple_field_declarations=do not insert
297
org.eclipse.jdt.core.formatter.insert_space_before_comma_in_multiple_local_declarations=do not insert
298
org.eclipse.jdt.core.formatter.insert_space_before_comma_in_parameterized_type_reference=do not insert
299
org.eclipse.jdt.core.formatter.insert_space_before_comma_in_superinterfaces=do not insert
300
org.eclipse.jdt.core.formatter.insert_space_before_comma_in_type_arguments=do not insert
301
org.eclipse.jdt.core.formatter.insert_space_before_comma_in_type_parameters=do not insert
302
org.eclipse.jdt.core.formatter.insert_space_before_ellipsis=do not insert
303
org.eclipse.jdt.core.formatter.insert_space_before_opening_angle_bracket_in_parameterized_type_reference=do not insert
304
org.eclipse.jdt.core.formatter.insert_space_before_opening_angle_bracket_in_type_arguments=do not insert
305
org.eclipse.jdt.core.formatter.insert_space_before_opening_angle_bracket_in_type_parameters=do not insert
306
org.eclipse.jdt.core.formatter.insert_space_before_opening_brace_in_annotation_type_declaration=insert
307
org.eclipse.jdt.core.formatter.insert_space_before_opening_brace_in_anonymous_type_declaration=insert
308
org.eclipse.jdt.core.formatter.insert_space_before_opening_brace_in_array_initializer=insert
309
org.eclipse.jdt.core.formatter.insert_space_before_opening_brace_in_block=insert
310
org.eclipse.jdt.core.formatter.insert_space_before_opening_brace_in_constructor_declaration=insert
311
org.eclipse.jdt.core.formatter.insert_space_before_opening_brace_in_enum_constant=insert
312
org.eclipse.jdt.core.formatter.insert_space_before_opening_brace_in_enum_declaration=insert
313
org.eclipse.jdt.core.formatter.insert_space_before_opening_brace_in_method_declaration=insert
314
org.eclipse.jdt.core.formatter.insert_space_before_opening_brace_in_switch=insert
315
org.eclipse.jdt.core.formatter.insert_space_before_opening_brace_in_type_declaration=insert
316
org.eclipse.jdt.core.formatter.insert_space_before_opening_bracket_in_array_allocation_expression=do not insert
317
org.eclipse.jdt.core.formatter.insert_space_before_opening_bracket_in_array_reference=do not insert
318
org.eclipse.jdt.core.formatter.insert_space_before_opening_bracket_in_array_type_reference=do not insert
319
org.eclipse.jdt.core.formatter.insert_space_before_opening_paren_in_annotation=do not insert
320
org.eclipse.jdt.core.formatter.insert_space_before_opening_paren_in_annotation_type_member_declaration=do not insert
321
org.eclipse.jdt.core.formatter.insert_space_before_opening_paren_in_catch=insert
322
org.eclipse.jdt.core.formatter.insert_space_before_opening_paren_in_constructor_declaration=do not insert
323
org.eclipse.jdt.core.formatter.insert_space_before_opening_paren_in_enum_constant=do not insert
324
org.eclipse.jdt.core.formatter.insert_space_before_opening_paren_in_for=insert
325
org.eclipse.jdt.core.formatter.insert_space_before_opening_paren_in_if=insert
326
org.eclipse.jdt.core.formatter.insert_space_before_opening_paren_in_method_declaration=do not insert
327
org.eclipse.jdt.core.formatter.insert_space_before_opening_paren_in_method_invocation=do not insert
328
org.eclipse.jdt.core.formatter.insert_space_before_opening_paren_in_parenthesized_expression=do not insert
329
org.eclipse.jdt.core.formatter.insert_space_before_opening_paren_in_switch=insert
330
org.eclipse.jdt.core.formatter.insert_space_before_opening_paren_in_synchronized=insert
331
org.eclipse.jdt.core.formatter.insert_space_before_opening_paren_in_while=insert
332
org.eclipse.jdt.core.formatter.insert_space_before_parenthesized_expression_in_return=insert
333
org.eclipse.jdt.core.formatter.insert_space_before_parenthesized_expression_in_throw=insert
334
org.eclipse.jdt.core.formatter.insert_space_before_postfix_operator=do not insert
335
org.eclipse.jdt.core.formatter.insert_space_before_prefix_operator=do not insert
336
org.eclipse.jdt.core.formatter.insert_space_before_question_in_conditional=insert
337
org.eclipse.jdt.core.formatter.insert_space_before_question_in_wildcard=do not insert
338
org.eclipse.jdt.core.formatter.insert_space_before_semicolon=do not insert
339
org.eclipse.jdt.core.formatter.insert_space_before_semicolon_in_for=do not insert
340
org.eclipse.jdt.core.formatter.insert_space_before_unary_operator=do not insert
341
org.eclipse.jdt.core.formatter.insert_space_between_brackets_in_array_type_reference=do not insert
342
org.eclipse.jdt.core.formatter.insert_space_between_empty_braces_in_array_initializer=do not insert
343
org.eclipse.jdt.core.formatter.insert_space_between_empty_brackets_in_array_allocation_expression=do not insert
344
org.eclipse.jdt.core.formatter.insert_space_between_empty_parens_in_annotation_type_member_declaration=do not insert
345
org.eclipse.jdt.core.formatter.insert_space_between_empty_parens_in_constructor_declaration=do not insert
346
org.eclipse.jdt.core.formatter.insert_space_between_empty_parens_in_enum_constant=do not insert
347
org.eclipse.jdt.core.formatter.insert_space_between_empty_parens_in_method_declaration=do not insert
348
org.eclipse.jdt.core.formatter.insert_space_between_empty_parens_in_method_invocation=do not insert
349
org.eclipse.jdt.core.formatter.keep_else_statement_on_same_line=false
350
org.eclipse.jdt.core.formatter.keep_empty_array_initializer_on_one_line=false
351
org.eclipse.jdt.core.formatter.keep_imple_if_on_one_line=false
352
org.eclipse.jdt.core.formatter.keep_then_statement_on_same_line=false
353
org.eclipse.jdt.core.formatter.lineSplit=120
354
org.eclipse.jdt.core.formatter.never_indent_block_comments_on_first_column=false
355
org.eclipse.jdt.core.formatter.never_indent_line_comments_on_first_column=false
356
org.eclipse.jdt.core.formatter.number_of_blank_lines_at_beginning_of_method_body=0
357
org.eclipse.jdt.core.formatter.number_of_empty_lines_to_preserve=1
358
org.eclipse.jdt.core.formatter.put_empty_statement_on_new_line=true
359
org.eclipse.jdt.core.formatter.tabulation.char=tab
360
org.eclipse.jdt.core.formatter.tabulation.size=4
361
org.eclipse.jdt.core.formatter.use_tabs_only_for_leading_indentations=false
362
org.eclipse.jdt.core.formatter.wrap_before_binary_operator=true
363
org.eclipse.jdt.core.incompatibleJDKLevel=ignore
364
org.eclipse.jdt.core.incompleteClasspath=error
(-)a/org.eclipse.jdt.annotation/.settings/org.eclipse.jdt.launching.prefs (+3 lines)
Added Link Here
1
#Wed Feb 02 11:25:08 EST 2011
2
eclipse.preferences.version=1
3
org.eclipse.jdt.launching.PREF_STRICTLY_COMPATIBLE_JRE_NOT_AVAILABLE=error
(-)a/org.eclipse.jdt.annotation/.settings/org.eclipse.jdt.ui.prefs (+105 lines)
Added Link Here
1
#Tue Jan 05 12:29:35 EST 2010
2
cleanup.add_default_serial_version_id=true
3
cleanup.add_generated_serial_version_id=false
4
cleanup.add_missing_annotations=true
5
cleanup.add_missing_deprecated_annotations=true
6
cleanup.add_missing_nls_tags=false
7
cleanup.add_missing_override_annotations=true
8
cleanup.add_serial_version_id=false
9
cleanup.always_use_blocks=true
10
cleanup.always_use_parentheses_in_expressions=false
11
cleanup.always_use_this_for_non_static_field_access=true
12
cleanup.always_use_this_for_non_static_method_access=false
13
cleanup.convert_to_enhanced_for_loop=false
14
cleanup.format_comment=false
15
cleanup.format_javadoc=true
16
cleanup.format_multi_line_comment=true
17
cleanup.format_single_line_comment=true
18
cleanup.format_source_code=false
19
cleanup.make_local_variable_final=true
20
cleanup.make_parameters_final=false
21
cleanup.make_private_fields_final=true
22
cleanup.make_variable_declarations_final=false
23
cleanup.never_use_blocks=false
24
cleanup.never_use_parentheses_in_expressions=true
25
cleanup.organize_imports=true
26
cleanup.qualify_static_field_accesses_with_declaring_class=true
27
cleanup.qualify_static_member_accesses_through_instances_with_declaring_class=true
28
cleanup.qualify_static_member_accesses_through_subtypes_with_declaring_class=true
29
cleanup.qualify_static_member_accesses_with_declaring_class=true
30
cleanup.qualify_static_method_accesses_with_declaring_class=false
31
cleanup.remove_private_constructors=true
32
cleanup.remove_unnecessary_casts=true
33
cleanup.remove_unnecessary_nls_tags=true
34
cleanup.remove_unused_imports=true
35
cleanup.remove_unused_local_variables=false
36
cleanup.remove_unused_private_fields=true
37
cleanup.remove_unused_private_members=false
38
cleanup.remove_unused_private_methods=true
39
cleanup.remove_unused_private_types=true
40
cleanup.use_blocks=false
41
cleanup.use_blocks_only_for_return_and_throw=false
42
cleanup.use_parentheses_in_expressions=false
43
cleanup.use_this_for_non_static_field_access=true
44
cleanup.use_this_for_non_static_field_access_only_if_necessary=false
45
cleanup.use_this_for_non_static_method_access=false
46
cleanup.use_this_for_non_static_method_access_only_if_necessary=true
47
cleanup_profile=_Numbat
48
cleanup_settings_version=2
49
eclipse.preferences.version=1
50
editor_save_participant_org.eclipse.jdt.ui.postsavelistener.cleanup=true
51
formatter_profile=_Jdtcore [built-in + Indent switch body + LineWidth\:120]
52
formatter_settings_version=11
53
sp_cleanup.add_default_serial_version_id=true
54
sp_cleanup.add_generated_serial_version_id=false
55
sp_cleanup.add_missing_annotations=false
56
sp_cleanup.add_missing_deprecated_annotations=true
57
sp_cleanup.add_missing_methods=false
58
sp_cleanup.add_missing_nls_tags=false
59
sp_cleanup.add_missing_override_annotations=true
60
sp_cleanup.add_missing_override_annotations_interface_methods=false
61
sp_cleanup.add_serial_version_id=false
62
sp_cleanup.always_use_blocks=true
63
sp_cleanup.always_use_parentheses_in_expressions=false
64
sp_cleanup.always_use_this_for_non_static_field_access=false
65
sp_cleanup.always_use_this_for_non_static_method_access=false
66
sp_cleanup.convert_to_enhanced_for_loop=false
67
sp_cleanup.correct_indentation=false
68
sp_cleanup.format_source_code=false
69
sp_cleanup.format_source_code_changes_only=false
70
sp_cleanup.make_local_variable_final=false
71
sp_cleanup.make_parameters_final=false
72
sp_cleanup.make_private_fields_final=true
73
sp_cleanup.make_type_abstract_if_missing_method=false
74
sp_cleanup.make_variable_declarations_final=false
75
sp_cleanup.never_use_blocks=false
76
sp_cleanup.never_use_parentheses_in_expressions=true
77
sp_cleanup.on_save_use_additional_actions=true
78
sp_cleanup.organize_imports=false
79
sp_cleanup.qualify_static_field_accesses_with_declaring_class=false
80
sp_cleanup.qualify_static_member_accesses_through_instances_with_declaring_class=true
81
sp_cleanup.qualify_static_member_accesses_through_subtypes_with_declaring_class=true
82
sp_cleanup.qualify_static_member_accesses_with_declaring_class=false
83
sp_cleanup.qualify_static_method_accesses_with_declaring_class=false
84
sp_cleanup.remove_private_constructors=true
85
sp_cleanup.remove_trailing_whitespaces=false
86
sp_cleanup.remove_trailing_whitespaces_all=true
87
sp_cleanup.remove_trailing_whitespaces_ignore_empty=false
88
sp_cleanup.remove_unnecessary_casts=false
89
sp_cleanup.remove_unnecessary_nls_tags=false
90
sp_cleanup.remove_unused_imports=false
91
sp_cleanup.remove_unused_local_variables=false
92
sp_cleanup.remove_unused_private_fields=true
93
sp_cleanup.remove_unused_private_members=false
94
sp_cleanup.remove_unused_private_methods=true
95
sp_cleanup.remove_unused_private_types=true
96
sp_cleanup.sort_members=false
97
sp_cleanup.sort_members_all=false
98
sp_cleanup.update_ibm_copyright_to_current_year=true
99
sp_cleanup.use_blocks=false
100
sp_cleanup.use_blocks_only_for_return_and_throw=false
101
sp_cleanup.use_parentheses_in_expressions=false
102
sp_cleanup.use_this_for_non_static_field_access=false
103
sp_cleanup.use_this_for_non_static_field_access_only_if_necessary=true
104
sp_cleanup.use_this_for_non_static_method_access=false
105
sp_cleanup.use_this_for_non_static_method_access_only_if_necessary=true
(-)a/org.eclipse.jdt.annotation/.settings/org.eclipse.pde.api.tools.prefs (+94 lines)
Added Link Here
1
#Fri May 21 10:24:07 EDT 2010
2
ANNOTATION_ELEMENT_TYPE_ADDED_METHOD_WITHOUT_DEFAULT_VALUE=Error
3
ANNOTATION_ELEMENT_TYPE_CHANGED_TYPE_CONVERSION=Error
4
ANNOTATION_ELEMENT_TYPE_REMOVED_FIELD=Error
5
ANNOTATION_ELEMENT_TYPE_REMOVED_METHOD=Error
6
ANNOTATION_ELEMENT_TYPE_REMOVED_TYPE_MEMBER=Error
7
API_COMPONENT_ELEMENT_TYPE_REMOVED_API_TYPE=Error
8
API_COMPONENT_ELEMENT_TYPE_REMOVED_REEXPORTED_API_TYPE=Error
9
API_COMPONENT_ELEMENT_TYPE_REMOVED_REEXPORTED_TYPE=Error
10
API_COMPONENT_ELEMENT_TYPE_REMOVED_TYPE=Error
11
CLASS_ELEMENT_TYPE_ADDED_METHOD=Error
12
CLASS_ELEMENT_TYPE_ADDED_RESTRICTIONS=Error
13
CLASS_ELEMENT_TYPE_ADDED_TYPE_PARAMETER=Error
14
CLASS_ELEMENT_TYPE_CHANGED_CONTRACTED_SUPERINTERFACES_SET=Error
15
CLASS_ELEMENT_TYPE_CHANGED_DECREASE_ACCESS=Error
16
CLASS_ELEMENT_TYPE_CHANGED_NON_ABSTRACT_TO_ABSTRACT=Error
17
CLASS_ELEMENT_TYPE_CHANGED_NON_FINAL_TO_FINAL=Error
18
CLASS_ELEMENT_TYPE_CHANGED_TYPE_CONVERSION=Error
19
CLASS_ELEMENT_TYPE_REMOVED_CONSTRUCTOR=Error
20
CLASS_ELEMENT_TYPE_REMOVED_FIELD=Error
21
CLASS_ELEMENT_TYPE_REMOVED_METHOD=Error
22
CLASS_ELEMENT_TYPE_REMOVED_SUPERCLASS=Error
23
CLASS_ELEMENT_TYPE_REMOVED_TYPE_MEMBER=Error
24
CLASS_ELEMENT_TYPE_REMOVED_TYPE_PARAMETER=Error
25
CONSTRUCTOR_ELEMENT_TYPE_ADDED_TYPE_PARAMETER=Error
26
CONSTRUCTOR_ELEMENT_TYPE_CHANGED_DECREASE_ACCESS=Error
27
CONSTRUCTOR_ELEMENT_TYPE_CHANGED_VARARGS_TO_ARRAY=Error
28
CONSTRUCTOR_ELEMENT_TYPE_REMOVED_TYPE_PARAMETER=Error
29
ENUM_ELEMENT_TYPE_CHANGED_CONTRACTED_SUPERINTERFACES_SET=Error
30
ENUM_ELEMENT_TYPE_CHANGED_TYPE_CONVERSION=Error
31
ENUM_ELEMENT_TYPE_REMOVED_ENUM_CONSTANT=Error
32
ENUM_ELEMENT_TYPE_REMOVED_FIELD=Error
33
ENUM_ELEMENT_TYPE_REMOVED_METHOD=Error
34
ENUM_ELEMENT_TYPE_REMOVED_TYPE_MEMBER=Error
35
FIELD_ELEMENT_TYPE_ADDED_VALUE=Error
36
FIELD_ELEMENT_TYPE_CHANGED_DECREASE_ACCESS=Error
37
FIELD_ELEMENT_TYPE_CHANGED_FINAL_TO_NON_FINAL_STATIC_CONSTANT=Error
38
FIELD_ELEMENT_TYPE_CHANGED_NON_FINAL_TO_FINAL=Error
39
FIELD_ELEMENT_TYPE_CHANGED_NON_STATIC_TO_STATIC=Error
40
FIELD_ELEMENT_TYPE_CHANGED_STATIC_TO_NON_STATIC=Error
41
FIELD_ELEMENT_TYPE_CHANGED_TYPE=Error
42
FIELD_ELEMENT_TYPE_CHANGED_VALUE=Error
43
FIELD_ELEMENT_TYPE_REMOVED_TYPE_ARGUMENT=Error
44
FIELD_ELEMENT_TYPE_REMOVED_VALUE=Error
45
ILLEGAL_EXTEND=Warning
46
ILLEGAL_IMPLEMENT=Warning
47
ILLEGAL_INSTANTIATE=Warning
48
ILLEGAL_OVERRIDE=Warning
49
ILLEGAL_REFERENCE=Warning
50
INTERFACE_ELEMENT_TYPE_ADDED_FIELD=Error
51
INTERFACE_ELEMENT_TYPE_ADDED_METHOD=Error
52
INTERFACE_ELEMENT_TYPE_ADDED_RESTRICTIONS=Error
53
INTERFACE_ELEMENT_TYPE_ADDED_SUPER_INTERFACE_WITH_METHODS=Error
54
INTERFACE_ELEMENT_TYPE_ADDED_TYPE_PARAMETER=Error
55
INTERFACE_ELEMENT_TYPE_CHANGED_CONTRACTED_SUPERINTERFACES_SET=Error
56
INTERFACE_ELEMENT_TYPE_CHANGED_TYPE_CONVERSION=Error
57
INTERFACE_ELEMENT_TYPE_REMOVED_FIELD=Error
58
INTERFACE_ELEMENT_TYPE_REMOVED_METHOD=Error
59
INTERFACE_ELEMENT_TYPE_REMOVED_TYPE_MEMBER=Error
60
INTERFACE_ELEMENT_TYPE_REMOVED_TYPE_PARAMETER=Error
61
INVALID_JAVADOC_TAG=Warning
62
INVALID_REFERENCE_IN_SYSTEM_LIBRARIES=Warning
63
LEAK_EXTEND=Warning
64
LEAK_FIELD_DECL=Warning
65
LEAK_IMPLEMENT=Warning
66
LEAK_METHOD_PARAM=Warning
67
LEAK_METHOD_RETURN_TYPE=Warning
68
METHOD_ELEMENT_TYPE_ADDED_RESTRICTIONS=Error
69
METHOD_ELEMENT_TYPE_ADDED_TYPE_PARAMETER=Error
70
METHOD_ELEMENT_TYPE_CHANGED_DECREASE_ACCESS=Error
71
METHOD_ELEMENT_TYPE_CHANGED_NON_ABSTRACT_TO_ABSTRACT=Error
72
METHOD_ELEMENT_TYPE_CHANGED_NON_FINAL_TO_FINAL=Error
73
METHOD_ELEMENT_TYPE_CHANGED_NON_STATIC_TO_STATIC=Error
74
METHOD_ELEMENT_TYPE_CHANGED_STATIC_TO_NON_STATIC=Error
75
METHOD_ELEMENT_TYPE_CHANGED_VARARGS_TO_ARRAY=Error
76
METHOD_ELEMENT_TYPE_REMOVED_ANNOTATION_DEFAULT_VALUE=Error
77
METHOD_ELEMENT_TYPE_REMOVED_TYPE_PARAMETER=Error
78
TYPE_PARAMETER_ELEMENT_TYPE_ADDED_CLASS_BOUND=Error
79
TYPE_PARAMETER_ELEMENT_TYPE_ADDED_INTERFACE_BOUND=Error
80
TYPE_PARAMETER_ELEMENT_TYPE_CHANGED_CLASS_BOUND=Error
81
TYPE_PARAMETER_ELEMENT_TYPE_CHANGED_INTERFACE_BOUND=Error
82
TYPE_PARAMETER_ELEMENT_TYPE_REMOVED_CLASS_BOUND=Error
83
TYPE_PARAMETER_ELEMENT_TYPE_REMOVED_INTERFACE_BOUND=Error
84
UNUSED_PROBLEM_FILTERS=Warning
85
automatically_removed_unused_problem_filters=false
86
eclipse.preferences.version=1
87
incompatible_api_component_version=Error
88
incompatible_api_component_version_include_major_without_breaking_change=Disabled
89
incompatible_api_component_version_include_minor_without_api_change=Disabled
90
invalid_since_tag_version=Error
91
malformed_since_tag=Error
92
missing_since_tag=Error
93
report_api_breakage_when_major_version_incremented=Disabled
94
report_resolution_errors_api_component=Warning
(-)a/org.eclipse.jdt.annotation/.settings/org.eclipse.pde.prefs (+35 lines)
Added Link Here
1
#Fri May 21 10:24:08 EDT 2010
2
compilers.f.unresolved-features=1
3
compilers.f.unresolved-plugins=1
4
compilers.incompatible-environment=1
5
compilers.p.build=1
6
compilers.p.build.bin.includes=1
7
compilers.p.build.encodings=2
8
compilers.p.build.java.compiler=2
9
compilers.p.build.java.compliance=2
10
compilers.p.build.missing.output=2
11
compilers.p.build.output.library=2
12
compilers.p.build.source.library=2
13
compilers.p.build.src.includes=1
14
compilers.p.deprecated=1
15
compilers.p.discouraged-class=1
16
compilers.p.internal=1
17
compilers.p.missing-bundle-classpath-entries=2
18
compilers.p.missing-packages=2
19
compilers.p.missing-version-export-package=2
20
compilers.p.missing-version-import-package=2
21
compilers.p.missing-version-require-bundle=2
22
compilers.p.no-required-att=0
23
compilers.p.not-externalized-att=2
24
compilers.p.unknown-attribute=1
25
compilers.p.unknown-class=1
26
compilers.p.unknown-element=1
27
compilers.p.unknown-identifier=1
28
compilers.p.unknown-resource=1
29
compilers.p.unresolved-ex-points=0
30
compilers.p.unresolved-import=0
31
compilers.s.create-docs=false
32
compilers.s.doc-folder=doc
33
compilers.s.open-tags=1
34
compilers.use-project=true
35
eclipse.preferences.version=1
(-)a/org.eclipse.jdt.annotation/META-INF/MANIFEST.MF (+9 lines)
Added Link Here
1
Manifest-Version: 1.0
2
Bundle-ManifestVersion: 2
3
Bundle-Name: %bundleName
4
Bundle-Localization: bundle
5
Bundle-SymbolicName: org.eclipse.jdt.annotation
6
Bundle-Version: 1.0.0.qualifier
7
Export-Package: org.eclipse.jdt.annotation
8
Bundle-RequiredExecutionEnvironment: J2SE-1.5
9
Bundle-Vendor: %providerName
(-)a/org.eclipse.jdt.annotation/about.html (+28 lines)
Added Link Here
1
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"
2
    "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
3
<html xmlns="http://www.w3.org/1999/xhtml">
4
<head>
5
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1"/>
6
<title>About</title>
7
</head>
8
<body lang="EN-US">
9
<h2>About This Content</h2>
10
 
11
<p>June 5, 2006</p>	
12
<h3>License</h3>
13
14
<p>The Eclipse Foundation makes available all content in this plug-in (&quot;Content&quot;).  Unless otherwise 
15
indicated below, the Content is provided to you under the terms and conditions of the
16
Eclipse Public License Version 1.0 (&quot;EPL&quot;).  A copy of the EPL is available 
17
at <a href="http://www.eclipse.org/legal/epl-v10.html">http://www.eclipse.org/legal/epl-v10.html</a>.
18
For purposes of the EPL, &quot;Program&quot; will mean the Content.</p>
19
20
<p>If you did not receive this Content directly from the Eclipse Foundation, the Content is 
21
being redistributed by another party (&quot;Redistributor&quot;) and different terms and conditions may
22
apply to your use of any object code in the Content.  Check the Redistributor's license that was 
23
provided with the Content.  If no such license exists, contact the Redistributor.  Unless otherwise
24
indicated below, the terms and conditions of the EPL still apply to any source code in the Content
25
and such source code may be obtained at <a href="http://www.eclipse.org/">http://www.eclipse.org</a>.</p>
26
27
</body>
28
</html>
(-)a/org.eclipse.jdt.annotation/build.properties (+18 lines)
Added Link Here
1
###############################################################################
2
# Copyright (c) 2011 Stephan Herrmann 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
#     IBM Corporation - bug fixes
11
###############################################################################
12
source.. = src/
13
bin.includes = META-INF/,\
14
               .,\
15
               bundle.properties,\
16
               src/,\
17
               about.html
18
src.includes = about.html
(-)a/org.eclipse.jdt.annotation/bundle.properties (+12 lines)
Added Link Here
1
###############################################################################
2
# Copyright (c) 2011 Stephan Herrmann.
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
providerName=Eclipse.org
12
bundleName=JDT Annotations for Enhanced Null Analysis
(-)a/org.eclipse.jdt.annotation/src/org/eclipse/jdt/annotation/NonNull.java (+50 lines)
Added Link Here
1
/*******************************************************************************
2
 * Copyright (c) 2011 Stephan Herrmann 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
 *     IBM Corporation - bug fixes
11
 *******************************************************************************/
12
package org.eclipse.jdt.annotation;
13
14
import static java.lang.annotation.ElementType.LOCAL_VARIABLE;
15
import static java.lang.annotation.ElementType.METHOD;
16
import static java.lang.annotation.ElementType.PARAMETER;
17
18
import java.lang.annotation.Documented;
19
import java.lang.annotation.Retention;
20
import java.lang.annotation.RetentionPolicy;
21
import java.lang.annotation.Target;
22
 
23
/**
24
 * Qualifier for a type in a method signature or a local variable declaration:
25
 * The entity (return value, parameter, local variable) whose type has this
26
 * annotation can never have the value <code>null</code> at runtime.
27
 * <p>
28
 * This has two consequences:
29
 * <ol>
30
 * <li>Dereferencing the entity is safe, i.e., no <code>NullPointerException</code> can occur at runtime.</li>
31
 * <li>An attempt to bind a <code>null</code> value to the entity is a compile time error.</li>
32
 * </ol>
33
 * For the second case, diagnostics issued by the compiler should distinguish three situations:
34
 * <ol>
35
 * <li>Nullness of the value can be statically determined, the entity is definitely bound from either of:
36
 *     <ul><li>the value <code>null</code>, or</li>
37
 *         <li>an entity with a {@link Nullable @Nullable} type.</li></ul></li>
38
 * <li>Nullness cannot definitely be determined, because different code branches yield different results.</li>
39
 * <li>Nullness cannot be determined, because other program elements are involved for which
40
 *     null annotations are lacking.</li>
41
 * </ol>
42
 * </p>
43
 * @since 1.0
44
 */
45
@Documented
46
@Retention(RetentionPolicy.CLASS)
47
@Target({ METHOD, PARAMETER, LOCAL_VARIABLE })
48
public @interface NonNull {
49
	// marker annotation with no members
50
}
(-)a/org.eclipse.jdt.annotation/src/org/eclipse/jdt/annotation/NonNullByDefault.java (+52 lines)
Added Link Here
1
/*******************************************************************************
2
 * Copyright (c) 2011 Stephan Herrmann 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
 *     IBM Corporation - bug fixes
11
 *******************************************************************************/
12
package org.eclipse.jdt.annotation;
13
14
import static java.lang.annotation.ElementType.CONSTRUCTOR;
15
import static java.lang.annotation.ElementType.METHOD;
16
import static java.lang.annotation.ElementType.PACKAGE;
17
import static java.lang.annotation.ElementType.TYPE;
18
19
import java.lang.annotation.Documented;
20
import java.lang.annotation.Retention;
21
import java.lang.annotation.RetentionPolicy;
22
import java.lang.annotation.Target;
23
 
24
/**
25
 * This annotation can be applied to a package, type, method or constructor in order to 
26
 * define that all contained entities for which a null annotation is otherwise lacking
27
 * should be considered as {@link NonNull @NonNull}.
28
 * <dl>
29
 * <dt>Canceling a default</dt>
30
 * <dd>By using a <code>@NonNullByDefault</code> annotation with the argument <code>false</code>,
31
 * a default from any enclosing scope can be canceled for the element being annotated.
32
 * <dt>Nested defaults</dt>
33
 * <dd>If a <code>@NonNullByDefault</code>
34
 * annotation is used within the scope of another <code>@NonNullByDefault</code>
35
 * annotation or a project-wide default setting, the innermost annotation defines the
36
 * default applicable at any given position (depending on the parameter {@link #value()}).</dd>
37
 * </dl>
38
 * Note that for applying an annotation to a package, a file by the name
39
 * <code>package-info.java</code> is used.
40
 * 
41
 * @since 1.0
42
 */
43
@Documented
44
@Retention(RetentionPolicy.CLASS)
45
@Target({ PACKAGE, TYPE, METHOD, CONSTRUCTOR })
46
public @interface NonNullByDefault {
47
	/**
48
	 * When parameterized with <code>false</code>, the annotation specifies that the current element should not apply
49
	 * any default to un-annotated types.
50
	 */
51
	boolean value() default true;
52
}
(-)a/org.eclipse.jdt.annotation/src/org/eclipse/jdt/annotation/Nullable.java (+41 lines)
Added Link Here
1
/*******************************************************************************
2
 * Copyright (c) 2011 Stephan Herrmann 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
 *     IBM Corporation - bug fixes
11
 *******************************************************************************/
12
package org.eclipse.jdt.annotation;
13
14
import static java.lang.annotation.ElementType.LOCAL_VARIABLE;
15
import static java.lang.annotation.ElementType.METHOD;
16
import static java.lang.annotation.ElementType.PARAMETER;
17
18
import java.lang.annotation.Documented;
19
import java.lang.annotation.Retention;
20
import java.lang.annotation.RetentionPolicy;
21
import java.lang.annotation.Target;
22
 
23
/**
24
 * Qualifier for a type in a method signature or a local variable declaration:
25
 * The entity (return value, parameter, local variable) whose type has this
26
 * annotation is allowed to have the value <code>null</code> at runtime.
27
 * <p>
28
 * This has two consequences:
29
 * <ul>
30
 * <li>Binding a <code>null</code> value to the entity is legal.</li>
31
 * <li>Dereferencing the entity is unsafe, i.e., a <code>NullPointerException</code> can occur at runtime.</li>
32
 * </ul>
33
 * </p>
34
 * @since 1.0
35
 */
36
@Documented
37
@Retention(RetentionPolicy.CLASS)
38
@Target({ METHOD, PARAMETER, LOCAL_VARIABLE })
39
public @interface Nullable {
40
	// marker annotation with no members
41
}
(-)a/org.eclipse.jdt.annotation/src/org/eclipse/jdt/annotation/package-info.java (+10 lines)
Added Link Here
1
/**
2
 * This package contains annotations that can trigger special behavior
3
 * when annotated types are compiled by the Eclipse Compiler for Java.
4
 * <p>
5
 * Currently, the package contains annotations that specify nullness contracts
6
 * for annotated elements.
7
 * </p>
8
 */
9
package org.eclipse.jdt.annotation;
10
(-)a/org.eclipse.jdt.apt.core/.cvsignore (-2 lines)
Lines 1-2 Link Here
1
bin
2
tools.jar
(-)a/org.eclipse.jdt.apt.core/.settings/org.eclipse.core.resources.prefs (-5 / +5 lines)
Lines 1-5 Link Here
1
#Mon Mar 20 17:21:22 PST 2006
1
#Mon Mar 20 17:21:22 PST 2006
2
eclipse.preferences.version=1
2
eclipse.preferences.version=1
3
encoding//src/org/eclipse/jdt/apt/core/internal/build/messages.properties=8859_1
3
encoding//src/org/eclipse/jdt/apt/core/internal/build/messages.properties=8859_1
4
encoding//src/org/eclipse/jdt/apt/core/internal/messages.properties=8859_1
4
encoding//src/org/eclipse/jdt/apt/core/internal/messages.properties=8859_1
5
encoding//src/org/eclipse/jdt/apt/core/internal/util/messages.properties=8859_1
5
encoding//src/org/eclipse/jdt/apt/core/internal/util/messages.properties=8859_1
(-)a/org.eclipse.jdt.apt.core/.settings/org.eclipse.core.runtime.prefs (+2 lines)
Added Link Here
1
eclipse.preferences.version=1
2
line.separator=\n
(-)a/org.eclipse.jdt.apt.pluggable.core/.cvsignore (-1 lines)
Line 1 Link Here
1
bin
(-)a/org.eclipse.jdt.apt.pluggable.core/.settings/org.eclipse.core.runtime.prefs (+2 lines)
Added Link Here
1
eclipse.preferences.version=1
2
line.separator=\n
(-)a/org.eclipse.jdt.apt.pluggable.tests/.cvsignore (-1 lines)
Line 1 Link Here
1
bin
(-)a/org.eclipse.jdt.apt.pluggable.tests/.settings/org.eclipse.core.runtime.prefs (+2 lines)
Added Link Here
1
eclipse.preferences.version=1
2
line.separator=\n
(-)a/org.eclipse.jdt.apt.pluggable.tests/src/org/eclipse/jdt/apt/pluggable/tests/processors/modeltester/ModelTesterProc.java (-4 / +2 lines)
Lines 54-65 Link Here
54
	
54
	
55
	public static final String TEST_FIELD_TYPE_PKG = "p";
55
	public static final String TEST_FIELD_TYPE_PKG = "p";
56
	public static final String TEST_FIELD_TYPE_CLASS = "Foo";
56
	public static final String TEST_FIELD_TYPE_CLASS = "Foo";
57
	public static final String TEST_FIELD_TYPE_SOURCE = 				
57
	public static final String TEST_FIELD_TYPE_SOURCE =
58
		"package p;\n" +
58
		"package p;\n" +
59
		"import org.eclipse.jdt.apt.pluggable.tests.annotations.ModelTestTrigger;\n" +
59
		"import org.eclipse.jdt.apt.pluggable.tests.annotations.ModelTestTrigger;\n" +
60
		"import org.eclipse.jdt.apt.pluggable.tests.annotations.LookAt;\n" +
60
		"import org.eclipse.jdt.apt.pluggable.tests.annotations.LookAt;\n" +
61
		"@ModelTestTrigger(test = \"testFieldType\")" +
61
		"@ModelTestTrigger(test = \"testFieldType\")" +
62
		"@SuppressWarnings(\"unused\")\n" +
63
		"public class Foo {\n" +
62
		"public class Foo {\n" +
64
		"    @LookAt\n" +
63
		"    @LookAt\n" +
65
		"    private int _fInt = 0;\n" +
64
		"    private int _fInt = 0;\n" +
Lines 71-82 Link Here
71
70
72
	public static final String TEST_METHOD_TYPE_PKG = "p";
71
	public static final String TEST_METHOD_TYPE_PKG = "p";
73
	public static final String TEST_METHOD_TYPE_CLASS = "Foo";
72
	public static final String TEST_METHOD_TYPE_CLASS = "Foo";
74
	public static final String TEST_METHOD_TYPE_SOURCE = 				
73
	public static final String TEST_METHOD_TYPE_SOURCE =
75
		"package p;\n" +
74
		"package p;\n" +
76
		"import org.eclipse.jdt.apt.pluggable.tests.annotations.ModelTestTrigger;\n" +
75
		"import org.eclipse.jdt.apt.pluggable.tests.annotations.ModelTestTrigger;\n" +
77
		"import org.eclipse.jdt.apt.pluggable.tests.annotations.LookAt;\n" +
76
		"import org.eclipse.jdt.apt.pluggable.tests.annotations.LookAt;\n" +
78
		"@ModelTestTrigger(test = \"testMethodType\")" +
77
		"@ModelTestTrigger(test = \"testMethodType\")" +
79
		"@SuppressWarnings(\"unused\")\n" +
80
		"public class Foo {\n" +
78
		"public class Foo {\n" +
81
		"    @LookAt\n" +
79
		"    @LookAt\n" +
82
		"    private Foo self() { return this;}\n" +
80
		"    private Foo self() { return this;}\n" +
(-)a/org.eclipse.jdt.apt.pluggable.tests/test.xml (-2 / +2 lines)
Lines 1-7 Link Here
1
<?xml version="1.0"?>
1
<?xml version="1.0" encoding="UTF-8"?>
2
2
3
<!--
3
<!--
4
    Copyright (c) 2005, 2010 IBM Corporation and others.
4
    Copyright (c) 2005, 2011 IBM Corporation and others.
5
    All rights reserved. This program and the accompanying materials
5
    All rights reserved. This program and the accompanying materials
6
    are made available under the terms of the Eclipse Public License v1.0
6
    are made available under the terms of the Eclipse Public License v1.0
7
    which accompanies this distribution, and is available at
7
    which accompanies this distribution, and is available at
(-)a/org.eclipse.jdt.apt.tests/.cvsignore (-2 lines)
Lines 1-2 Link Here
1
bin
2
binext
(-)a/org.eclipse.jdt.apt.tests/.settings/org.eclipse.core.runtime.prefs (+2 lines)
Added Link Here
1
eclipse.preferences.version=1
2
line.separator=\n
(-)a/org.eclipse.jdt.apt.tests/META-INF/MANIFEST.MF (-1 / +2 lines)
Lines 36-42 Link Here
36
 org.eclipse.jdt.core.tests.model,
36
 org.eclipse.jdt.core.tests.model,
37
 org.eclipse.core.resources,
37
 org.eclipse.core.resources,
38
 org.eclipse.core.runtime,
38
 org.eclipse.core.runtime,
39
 org.eclipse.test.performance
39
 org.eclipse.test.performance,
40
 org.eclipse.jdt.core.tests.binaries;bundle-version="1.0.0"
40
Bundle-ActivationPolicy: lazy
41
Bundle-ActivationPolicy: lazy
41
Bundle-RequiredExecutionEnvironment: J2SE-1.5
42
Bundle-RequiredExecutionEnvironment: J2SE-1.5
42
Bundle-Vendor: %providerName
43
Bundle-Vendor: %providerName
(-)a/org.eclipse.jdt.apt.tests/build.properties (-2 / +1 lines)
Lines 1-5 Link Here
1
###############################################################################
1
###############################################################################
2
# Copyright (c) 2005, 2007 BEA Systems, Inc.
2
# Copyright (c) 2005, 2011 BEA Systems, Inc.
3
# All rights reserved. This program and the accompanying materials
3
# All rights reserved. This program and the accompanying materials
4
# are made available under the terms of the Eclipse Public License v1.0
4
# are made available under the terms of the Eclipse Public License v1.0
5
# which accompanies this distribution, and is available at
5
# which accompanies this distribution, and is available at
Lines 10-16 Link Here
10
output.apt.jar = bin/
10
output.apt.jar = bin/
11
bin.includes = plugin.xml,\
11
bin.includes = plugin.xml,\
12
               test.xml,\
12
               test.xml,\
13
               perf-test-project.zip,\
14
               META-INF/,\
13
               META-INF/,\
15
               resources/,\
14
               resources/,\
16
               *.jar,\
15
               *.jar,\
(-)a/org.eclipse.jdt.apt.tests/src/org/eclipse/jdt/apt/tests/PerfTests.java (-4 / +2 lines)
Lines 1-5 Link Here
1
/*******************************************************************************
1
/*******************************************************************************
2
 * Copyright (c) 2005, 2007 BEA Systems, Inc. 
2
 * Copyright (c) 2005, 2011 BEA Systems, Inc. 
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 59-70 Link Here
59
		IPath path = root.getLocation();
59
		IPath path = root.getLocation();
60
		File destRoot = path.toFile();
60
		File destRoot = path.toFile();
61
		
61
		
62
		URL platformURL = Platform.getBundle("org.eclipse.jdt.apt.tests").getEntry("/");  //$NON-NLS-1$//$NON-NLS-2$
62
		URL platformURL = Platform.getBundle("org.eclipse.jdt.core.tests.binaries").getEntry("/");  //$NON-NLS-1$//$NON-NLS-2$
63
		File f = new File(FileLocator.toFileURL(platformURL).getFile());
63
		File f = new File(FileLocator.toFileURL(platformURL).getFile());
64
		f = new File(f, "perf-test-project.zip"); //$NON-NLS-1$
64
		f = new File(f, "perf-test-project.zip"); //$NON-NLS-1$
65
65
66
		
67
		//InputStream in = PerfTests.class.getClassLoader().getResourceAsStream("perf-test-project.zip");
68
		InputStream in = new FileInputStream(f);
66
		InputStream in = new FileInputStream(f);
69
		ZipInputStream zipIn = new ZipInputStream(in);
67
		ZipInputStream zipIn = new ZipInputStream(in);
70
		try {
68
		try {
(-)a/org.eclipse.jdt.apt.tests/test.xml (-2 / +2 lines)
Lines 1-7 Link Here
1
<?xml version="1.0"?>
1
<?xml version="1.0" encoding="UTF-8"?>
2
2
3
<!--
3
<!--
4
    Copyright (c) 2005, 2010 IBM Corporation and others.
4
    Copyright (c) 2005, 2011 IBM Corporation and others.
5
    All rights reserved. This program and the accompanying materials
5
    All rights reserved. This program and the accompanying materials
6
    are made available under the terms of the Eclipse Public License v1.0
6
    are made available under the terms of the Eclipse Public License v1.0
7
    which accompanies this distribution, and is available at
7
    which accompanies this distribution, and is available at
(-)a/org.eclipse.jdt.apt.ui/.cvsignore (-1 lines)
Line 1 Link Here
1
bin
(-)a/org.eclipse.jdt.apt.ui/.settings/org.eclipse.core.runtime.prefs (+2 lines)
Added Link Here
1
eclipse.preferences.version=1
2
line.separator=\n
(-)a/org.eclipse.jdt.compiler.apt.tests/.cvsignore (-3 lines)
Lines 1-3 Link Here
1
bin
2
binprocessors
3
lib
(-)a/org.eclipse.jdt.compiler.apt.tests/.gitignore (+1 lines)
Added Link Here
1
/lib
(-)a/org.eclipse.jdt.compiler.apt.tests/.settings/org.eclipse.core.runtime.prefs (+2 lines)
Added Link Here
1
eclipse.preferences.version=1
2
line.separator=\n
(-)a/org.eclipse.jdt.compiler.apt.tests/test.xml (-2 / +2 lines)
Lines 1-7 Link Here
1
<?xml version="1.0"?>
1
<?xml version="1.0" encoding="UTF-8"?>
2
2
3
<!--
3
<!--
4
    Copyright (c) 2005, 2010 IBM Corporation and others.
4
    Copyright (c) 2005, 2011 IBM Corporation and others.
5
    All rights reserved. This program and the accompanying materials
5
    All rights reserved. This program and the accompanying materials
6
    are made available under the terms of the Eclipse Public License v1.0
6
    are made available under the terms of the Eclipse Public License v1.0
7
    which accompanies this distribution, and is available at
7
    which accompanies this distribution, and is available at
(-)a/org.eclipse.jdt.compiler.apt/.settings/org.eclipse.core.runtime.prefs (+2 lines)
Added Link Here
1
eclipse.preferences.version=1
2
line.separator=\n
(-)a/org.eclipse.jdt.compiler.apt/META-INF/MANIFEST.MF (-1 / +1 lines)
Lines 2-8 Link Here
2
Bundle-ManifestVersion: 2
2
Bundle-ManifestVersion: 2
3
Bundle-Name: %fragmentName
3
Bundle-Name: %fragmentName
4
Bundle-SymbolicName: org.eclipse.jdt.compiler.apt;singleton:=true
4
Bundle-SymbolicName: org.eclipse.jdt.compiler.apt;singleton:=true
5
Bundle-Version: 1.0.400.qualifier
5
Bundle-Version: 1.0.500.qualifier
6
Bundle-RequiredExecutionEnvironment: JavaSE-1.6
6
Bundle-RequiredExecutionEnvironment: JavaSE-1.6
7
Bundle-Vendor: %providerName
7
Bundle-Vendor: %providerName
8
Fragment-Host: org.eclipse.jdt.core;bundle-version="[3.5.0,4.0.0)"
8
Fragment-Host: org.eclipse.jdt.core;bundle-version="[3.5.0,4.0.0)"
(-)a/org.eclipse.jdt.compiler.apt/src/org/eclipse/jdt/internal/compiler/apt/dispatch/BaseAnnotationProcessorManager.java (-1 / +1 lines)
Lines 126-132 Link Here
126
126
127
	/**
127
	/**
128
	 * A single "round" of processing, in the sense implied in
128
	 * A single "round" of processing, in the sense implied in
129
	 * {@link javax.lang.annotation.processing.Processor}.
129
	 * {@link javax.annotation.processing.Processor}.
130
	 * <p>
130
	 * <p>
131
	 * The Java 6 Processor spec contains ambiguities about how processors that support "*" are
131
	 * The Java 6 Processor spec contains ambiguities about how processors that support "*" are
132
	 * handled. Eclipse tries to match Sun's implementation in javac. What that actually does is
132
	 * handled. Eclipse tries to match Sun's implementation in javac. What that actually does is
(-)a/org.eclipse.jdt.compiler.apt/src/org/eclipse/jdt/internal/compiler/apt/dispatch/BatchAnnotationProcessorManager.java (-4 / +3 lines)
Lines 1-5 Link Here
1
/*******************************************************************************
1
/*******************************************************************************
2
 * Copyright (c) 2005, 2007 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 25-31 Link Here
25
/**
25
/**
26
 * Java 6 annotation processor manager used when compiling from the command line
26
 * Java 6 annotation processor manager used when compiling from the command line
27
 * or via the javax.tools.JavaCompiler interface.
27
 * or via the javax.tools.JavaCompiler interface.
28
 * @see org.eclipse.jdt.internal.compiler.apt.ide.dispatch.IdeAnnotationProcessorManager
28
 * @see org.eclipse.jdt.internal.apt.pluggable.core.dispatch.IdeAnnotationProcessorManager
29
 */
29
 */
30
public class BatchAnnotationProcessorManager extends BaseAnnotationProcessorManager
30
public class BatchAnnotationProcessorManager extends BaseAnnotationProcessorManager
31
{
31
{
Lines 54-60 Link Here
54
	/**
54
	/**
55
	 * Zero-arg constructor so this object can be easily created via reflection.
55
	 * Zero-arg constructor so this object can be easily created via reflection.
56
	 * A BatchAnnotationProcessorManager cannot be used until its
56
	 * A BatchAnnotationProcessorManager cannot be used until its
57
	 * {@link #configure(Main, String[])} method has been called.
57
	 * {@link #configure(Object, String[])} method has been called.
58
	 */
58
	 */
59
	public BatchAnnotationProcessorManager() 
59
	public BatchAnnotationProcessorManager() 
60
	{
60
	{
Lines 77-83 Link Here
77
	 * If a -processor option was specified in command line arguments,
77
	 * If a -processor option was specified in command line arguments,
78
	 * parse it into a list of qualified classnames.
78
	 * parse it into a list of qualified classnames.
79
	 * @param commandLineArguments contains one string for every space-delimited token on the command line
79
	 * @param commandLineArguments contains one string for every space-delimited token on the command line
80
	 * @return a list of qualified classnames, or null if there was no -processor option.
81
	 */
80
	 */
82
	private void parseCommandLine(String[] commandLineArguments) {
81
	private void parseCommandLine(String[] commandLineArguments) {
83
		List<String> commandLineProcessors = null;
82
		List<String> commandLineProcessors = null;
(-)a/org.eclipse.jdt.compiler.apt/src/org/eclipse/jdt/internal/compiler/apt/dispatch/BatchProcessingEnvImpl.java (-1 / +1 lines)
Lines 96-102 Link Here
96
96
97
	/**
97
	/**
98
	 * Parse the -A command line arguments so that they can be delivered to
98
	 * Parse the -A command line arguments so that they can be delivered to
99
	 * processors with {@link ProcessingEnvironment#getOptions().  In Sun's Java 6
99
	 * processors with {@link javax.annotation.processing.ProcessingEnvironment#getOptions()}.  In Sun's Java 6
100
	 * version of javac, unlike in the Java 5 apt tool, only the -A options are
100
	 * version of javac, unlike in the Java 5 apt tool, only the -A options are
101
	 * passed to processors, not the other command line options; that behavior
101
	 * passed to processors, not the other command line options; that behavior
102
	 * is repeated here.
102
	 * is repeated here.
(-)a/org.eclipse.jdt.compiler.apt/src/org/eclipse/jdt/internal/compiler/apt/dispatch/ProcessorInfo.java (-2 lines)
Lines 88-95 Link Here
88
	 * subsequent calls.
88
	 * subsequent calls.
89
	 * 
89
	 * 
90
	 * @param annotations a set of annotation types
90
	 * @param annotations a set of annotation types
91
	 * @param annotationTypes a set of names, which may use the wildcard "*", as described in
92
	 * {@link Processor#getSupportedAnnotationTypes()}.
93
	 * @param result an empty modifiable set, which upon return will contain a subset of <code>annotations</code>, which may be empty but will not be null.
91
	 * @param result an empty modifiable set, which upon return will contain a subset of <code>annotations</code>, which may be empty but will not be null.
94
	 * @return true if the processor should be called on this round.
92
	 * @return true if the processor should be called on this round.
95
	 */
93
	 */
(-)a/org.eclipse.jdt.compiler.apt/src/org/eclipse/jdt/internal/compiler/apt/dispatch/RoundEnvImpl.java (-3 / +3 lines)
Lines 117-125 Link Here
117
117
118
	/**
118
	/**
119
	 * From the set of root elements and their enclosed elements, return the subset that are annotated
119
	 * From the set of root elements and their enclosed elements, return the subset that are annotated
120
	 * with {@code a}.  If {@code a} is annotated with the {@link java.lang.annotations.Inherited} 
120
	 * with {@code a}.  If {@code a} is annotated with the {@link java.lang.annotation.Inherited} 
121
	 * annotation, include those elements that inherit the annotation from their superclasses.
121
	 * annotation, include those elements that inherit the annotation from their superclasses.
122
	 * Note that {@link java.lang.annotations.Inherited} only applies to classes (i.e. TypeElements).
122
	 * Note that {@link java.lang.annotation.Inherited} only applies to classes (i.e. TypeElements).
123
	 */
123
	 */
124
	@Override
124
	@Override
125
	public Set<? extends Element> getElementsAnnotatedWith(TypeElement a)
125
	public Set<? extends Element> getElementsAnnotatedWith(TypeElement a)
Lines 146-152 Link Here
146
	 * For every type in types that is a class and that is annotated with anno, either directly or by inheritance,
146
	 * For every type in types that is a class and that is annotated with anno, either directly or by inheritance,
147
	 * add that type to result.  Recursively descend on each types's child classes as well.
147
	 * add that type to result.  Recursively descend on each types's child classes as well.
148
	 * @param anno the compiler binding for an annotation type
148
	 * @param anno the compiler binding for an annotation type
149
	 * @param types a set of types, not necessarily all classes
149
	 * @param type a type, not necessarily a class
150
	 * @param result must be a modifiable Set; will accumulate annotated classes
150
	 * @param result must be a modifiable Set; will accumulate annotated classes
151
	 */
151
	 */
152
	private void addAnnotatedElements(ReferenceBinding anno, ReferenceBinding type, Set<Element> result) {
152
	private void addAnnotatedElements(ReferenceBinding anno, ReferenceBinding type, Set<Element> result) {
(-)a/org.eclipse.jdt.compiler.apt/src/org/eclipse/jdt/internal/compiler/apt/model/AnnotationMirrorImpl.java (-2 / +2 lines)
Lines 121-127 Link Here
121
	}
121
	}
122
	
122
	
123
	/**
123
	/**
124
	 * {@see Elements#getElementValuesWithDefaults()}
124
	 * @see javax.lang.model.util.Elements#getElementValuesWithDefaults(AnnotationMirror)
125
	 * @return all the members of this annotation mirror that have explicit or default
125
	 * @return all the members of this annotation mirror that have explicit or default
126
	 * values.
126
	 * values.
127
	 */
127
	 */
Lines 280-286 Link Here
280
	 * and must be either a primitive type, String, Class, an enum constant, an annotation, or an
280
	 * and must be either a primitive type, String, Class, an enum constant, an annotation, or an
281
	 * array of any of those.  Multidimensional arrays are not permitted.
281
	 * array of any of those.  Multidimensional arrays are not permitted.
282
	 * 
282
	 * 
283
	 * @param annoValue the value as represented by {@link ElementValuePair#getValue()}
283
	 * @param actualValue the value as represented by {@link ElementValuePair#getValue()}
284
	 * @param actualType the return type of the corresponding {@link MethodBinding}
284
	 * @param actualType the return type of the corresponding {@link MethodBinding}
285
	 * @param expectedType the type that the reflective method invoker is expecting
285
	 * @param expectedType the type that the reflective method invoker is expecting
286
	 * @return an object of the expected type representing the annotation member value, 
286
	 * @return an object of the expected type representing the annotation member value, 
(-)a/org.eclipse.jdt.compiler.apt/src/org/eclipse/jdt/internal/compiler/apt/model/ElementImpl.java (-2 / +2 lines)
Lines 1-5 Link Here
1
/*******************************************************************************
1
/*******************************************************************************
2
 * Copyright (c) 2005, 2007 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 149-155 Link Here
149
	/**
149
	/**
150
	 * Subclassed by VariableElementImpl, TypeElementImpl, and ExecutableElementImpl.
150
	 * Subclassed by VariableElementImpl, TypeElementImpl, and ExecutableElementImpl.
151
	 * This base implementation suffices for other types.
151
	 * This base implementation suffices for other types.
152
	 * @see Elements#hides()
152
	 * @see Elements#hides
153
	 * @return true if this element hides {@code hidden}
153
	 * @return true if this element hides {@code hidden}
154
	 */
154
	 */
155
	public boolean hides(Element hidden)
155
	public boolean hides(Element hidden)
(-)a/org.eclipse.jdt.compiler.apt/src/org/eclipse/jdt/internal/compiler/apt/model/IElementInfo.java (-1 / +1 lines)
Lines 15-21 Link Here
15
/**
15
/**
16
 * Additional information available for Elements that are implemented 
16
 * Additional information available for Elements that are implemented 
17
 * within the Eclipse APT framework.
17
 * within the Eclipse APT framework.
18
 * @see javax.lang.model.Element
18
 * @see javax.lang.model.element.Element
19
 * @since 3.3
19
 * @since 3.3
20
 */
20
 */
21
public interface IElementInfo {
21
public interface IElementInfo {
(-)a/org.eclipse.jdt.compiler.apt/src/org/eclipse/jdt/internal/compiler/apt/model/NoTypeImpl.java (-1 / +1 lines)
Lines 18-24 Link Here
18
18
19
/**
19
/**
20
 * An implementation of NoType, which is used to represent certain psuedo-types.
20
 * An implementation of NoType, which is used to represent certain psuedo-types.
21
 * @see NoType. 
21
 * @see NoType
22
 */
22
 */
23
public class NoTypeImpl implements NoType, NullType
23
public class NoTypeImpl implements NoType, NullType
24
{
24
{
(-)a/org.eclipse.jdt.compiler.tool.tests/.cvsignore (-1 lines)
Line 1 Link Here
1
bin
(-)a/org.eclipse.jdt.compiler.tool.tests/.settings/org.eclipse.core.runtime.prefs (+2 lines)
Added Link Here
1
eclipse.preferences.version=1
2
line.separator=\n
(-)a/org.eclipse.jdt.compiler.tool.tests/META-INF/MANIFEST.MF (-1 / +1 lines)
Lines 2-8 Link Here
2
Bundle-ManifestVersion: 2
2
Bundle-ManifestVersion: 2
3
Bundle-Name: %pluginName
3
Bundle-Name: %pluginName
4
Bundle-SymbolicName: org.eclipse.jdt.compiler.tool.tests
4
Bundle-SymbolicName: org.eclipse.jdt.compiler.tool.tests
5
Bundle-Version: 1.0.100.qualifier
5
Bundle-Version: 1.0.101.qualifier
6
Bundle-Vendor: %providerName
6
Bundle-Vendor: %providerName
7
Bundle-Localization: plugin
7
Bundle-Localization: plugin
8
Bundle-RequiredExecutionEnvironment: JavaSE-1.6
8
Bundle-RequiredExecutionEnvironment: JavaSE-1.6
(-)a/org.eclipse.jdt.compiler.tool.tests/src/org/eclipse/jdt/compiler/tool/tests/AbstractCompilerToolTest.java (-10 / +19 lines)
Lines 12-17 Link Here
12
package org.eclipse.jdt.compiler.tool.tests;
12
package org.eclipse.jdt.compiler.tool.tests;
13
13
14
import java.io.File;
14
import java.io.File;
15
import java.io.IOException;
15
import java.io.PrintWriter;
16
import java.io.PrintWriter;
16
import java.util.ArrayList;
17
import java.util.ArrayList;
17
import java.util.List;
18
import java.util.List;
Lines 98-113 Link Here
98
		if (manager == null) {
99
		if (manager == null) {
99
			manager = COMPILER.getStandardFileManager(null, null, null); // will pick defaults up
100
			manager = COMPILER.getStandardFileManager(null, null, null); // will pick defaults up
100
		}
101
		}
101
		List<File> files = new ArrayList<File>();
102
		try {
102
		String[] fileNames = arguments.fileNames;
103
			List<File> files = new ArrayList<File>();
103
		for (int i = 0, l = fileNames.length; i < l; i++) {
104
			String[] fileNames = arguments.fileNames;
104
			if (fileNames[i].startsWith(OUTPUT_DIR)) {
105
			for (int i = 0, l = fileNames.length; i < l; i++) {
105
				files.add(new File(fileNames[i]));
106
				if (fileNames[i].startsWith(OUTPUT_DIR)) {
106
			} else {
107
					files.add(new File(fileNames[i]));
107
				files.add(new File(OUTPUT_DIR + File.separator + fileNames[i]));
108
				} else {
109
					files.add(new File(OUTPUT_DIR + File.separator + fileNames[i]));
110
				}
108
			}
111
			}
109
		}
112
			CompilationTask task = COMPILER.getTask(out, arguments.standardJavaFileManager /* carry the null over */, new CompilerInvocationDiagnosticListener(err), arguments.options, null, manager.getJavaFileObjectsFromFiles(files));
110
		CompilationTask task = COMPILER.getTask(out, arguments.standardJavaFileManager /* carry the null over */, new CompilerInvocationDiagnosticListener(err), arguments.options, null, manager.getJavaFileObjectsFromFiles(files));
113
			return task.call();
111
		return task.call();
114
		} finally {
115
			try {
116
				manager.close();
117
			} catch (IOException e) {
118
				// nop
119
			}
120
		}		
112
	}
121
	}
113
}
122
}
(-)a/org.eclipse.jdt.compiler.tool.tests/src/org/eclipse/jdt/compiler/tool/tests/CompilerInvocationTests.java (+4 lines)
Lines 502-508 Link Here
502
		remaining = remainingAsList.iterator();
502
		remaining = remainingAsList.iterator();
503
		assertTrue("does not support -d option", javacStandardJavaFileManager.handleOption("-d", remaining));
503
		assertTrue("does not support -d option", javacStandardJavaFileManager.handleOption("-d", remaining));
504
		assertEquals("unexpected consumption rate", "remainder", remaining.next());
504
		assertEquals("unexpected consumption rate", "remainder", remaining.next());
505
		javacStandardJavaFileManager.close();
505
	}
506
	}
507
	ecjStandardJavaFileManager.close();
506
}
508
}
507
// https://bugs.eclipse.org/bugs/show_bug.cgi?id=226918
509
// https://bugs.eclipse.org/bugs/show_bug.cgi?id=226918
508
// options consumption - check consumption rate on supported zero-args options
510
// options consumption - check consumption rate on supported zero-args options
Lines 525-530 Link Here
525
			assertEquals("unexpected consumption rate", REMAINDER, remaining.next());
527
			assertEquals("unexpected consumption rate", REMAINDER, remaining.next());
526
		}
528
		}
527
	}
529
	}
530
	ecjStandardJavaFileManager.close();
528
}
531
}
529
// https://bugs.eclipse.org/bugs/show_bug.cgi?id=226918
532
// https://bugs.eclipse.org/bugs/show_bug.cgi?id=226918
530
// options consumption - check consumption rate on supported one-arg options
533
// options consumption - check consumption rate on supported one-arg options
Lines 540-545 Link Here
540
			assertEquals("unexpected consumption rate", REMAINDER, remaining.next());
543
			assertEquals("unexpected consumption rate", REMAINDER, remaining.next());
541
		}
544
		}
542
	}
545
	}
546
	ecjStandardJavaFileManager.close();
543
}
547
}
544
// tests #10-11 show that ecj throws a RuntimeException when encountering a wrong
548
// tests #10-11 show that ecj throws a RuntimeException when encountering a wrong
545
// encoding in its parameters, while the default compiler swallows it silently
549
// encoding in its parameters, while the default compiler swallows it silently
(-)a/org.eclipse.jdt.compiler.tool.tests/src/org/eclipse/jdt/compiler/tool/tests/CompilerToolTests.java (-4 / +9 lines)
Lines 19-24 Link Here
19
import java.io.StringWriter;
19
import java.io.StringWriter;
20
import java.nio.charset.Charset;
20
import java.nio.charset.Charset;
21
import java.util.ArrayList;
21
import java.util.ArrayList;
22
import java.util.Collections;
22
import java.util.HashSet;
23
import java.util.HashSet;
23
import java.util.Iterator;
24
import java.util.Iterator;
24
import java.util.List;
25
import java.util.List;
Lines 604-610 Link Here
604
		assertTrue("delete failed", inputFile.delete());
605
		assertTrue("delete failed", inputFile.delete());
605
	}
606
	}
606
607
607
	public void testCompilerOneClassWithEclipseCompiler4() {
608
	public void testCompilerOneClassWithEclipseCompiler4() throws IOException {
608
		JavaCompiler systemCompiler = ToolProvider.getSystemJavaCompiler();
609
		JavaCompiler systemCompiler = ToolProvider.getSystemJavaCompiler();
609
		if (systemCompiler == null) {
610
		if (systemCompiler == null) {
610
			System.out.println("No system java compiler available");
611
			System.out.println("No system java compiler available");
Lines 653-658 Link Here
653
		}
654
		}
654
		// check that the .class file exist for X
655
		// check that the .class file exist for X
655
		assertTrue("delete failed", inputFile.delete());
656
		assertTrue("delete failed", inputFile.delete());
657
		manager.close();
656
	}
658
	}
657
659
658
	public void testCompilerOneClassWithEclipseCompiler5() {
660
	public void testCompilerOneClassWithEclipseCompiler5() {
Lines 869-874 Link Here
869
				builder.append(name.substring(lastIndexOf + 1));
871
				builder.append(name.substring(lastIndexOf + 1));
870
			}
872
			}
871
			assertEquals("Wrong contents", "X.java", String.valueOf(builder));
873
			assertEquals("Wrong contents", "X.java", String.valueOf(builder));
874
			fileManager.close();
872
		} catch (IOException e) {
875
		} catch (IOException e) {
873
			e.printStackTrace();
876
			e.printStackTrace();
874
		}
877
		}
Lines 934-948 Link Here
934
			Iterable<? extends JavaFileObject> compilationUnits = fileManager.list(sourceLoc, "", fileTypes, true);
937
			Iterable<? extends JavaFileObject> compilationUnits = fileManager.list(sourceLoc, "", fileTypes, true);
935
	
938
	
936
			Iterator<? extends JavaFileObject> it = compilationUnits.iterator();
939
			Iterator<? extends JavaFileObject> it = compilationUnits.iterator();
937
			StringBuilder builder = new StringBuilder();
940
			List<String> names = new ArrayList<String>();
938
			while (it.hasNext()) {
941
			while (it.hasNext()) {
939
				JavaFileObject next = it.next();
942
				JavaFileObject next = it.next();
940
				String name = next.getName();
943
				String name = next.getName();
941
				name = name.replace('\\', '/');
944
				name = name.replace('\\', '/');
942
				int lastIndexOf = name.lastIndexOf('/');
945
				int lastIndexOf = name.lastIndexOf('/');
943
				builder.append(name.substring(lastIndexOf + 1));
946
				names.add(name.substring(lastIndexOf + 1));
944
			}
947
			}
945
			assertEquals("Wrong contents", "X2.javaX.java", String.valueOf(builder));
948
			Collections.sort(names);
949
			assertEquals("Wrong contents", "[X.java, X2.java]", names.toString());
950
			fileManager.close();
946
		} catch (IOException e) {
951
		} catch (IOException e) {
947
			e.printStackTrace();
952
			e.printStackTrace();
948
		}
953
		}
(-)a/org.eclipse.jdt.compiler.tool.tests/test.xml (-3 / +4 lines)
Lines 1-6 Link Here
1
<?xml version="1.0"?>
1
<?xml version="1.0" encoding="UTF-8"?>
2
<!--
2
3
    Copyright (c) 2006, 2009 IBM Corporation and others.
3
<!--
4
    Copyright (c) 2006, 2011 IBM Corporation and others.
4
    All rights reserved. This program and the accompanying materials
5
    All rights reserved. This program and the accompanying materials
5
    are made available under the terms of the Eclipse Public License v1.0
6
    are made available under the terms of the Eclipse Public License v1.0
6
    which accompanies this distribution, and is available at
7
    which accompanies this distribution, and is available at
(-)a/org.eclipse.jdt.compiler.tool/.cvsignore (-1 lines)
Line 1 Link Here
1
bin
(-)a/org.eclipse.jdt.compiler.tool/.settings/org.eclipse.core.runtime.prefs (+2 lines)
Added Link Here
1
eclipse.preferences.version=1
2
line.separator=\n
(-)a/org.eclipse.jdt.compiler.tool/META-INF/MANIFEST.MF (-1 / +1 lines)
Lines 2-8 Link Here
2
Bundle-ManifestVersion: 2
2
Bundle-ManifestVersion: 2
3
Bundle-Name: %fragmentName
3
Bundle-Name: %fragmentName
4
Bundle-SymbolicName: org.eclipse.jdt.compiler.tool;singleton:=true
4
Bundle-SymbolicName: org.eclipse.jdt.compiler.tool;singleton:=true
5
Bundle-Version: 1.0.100.qualifier
5
Bundle-Version: 1.0.101.qualifier
6
Bundle-Vendor: %providerName
6
Bundle-Vendor: %providerName
7
Bundle-Localization: compiler_tool_fragment
7
Bundle-Localization: compiler_tool_fragment
8
Bundle-RequiredExecutionEnvironment: JavaSE-1.6
8
Bundle-RequiredExecutionEnvironment: JavaSE-1.6
(-)a/org.eclipse.jdt.compiler.tool/src/org/eclipse/jdt/internal/compiler/tool/Options.java (-2 / +23 lines)
Lines 1-5 Link Here
1
/*******************************************************************************
1
/*******************************************************************************
2
 * Copyright (c) 2006, 2010 IBM Corporation and others.
2
 * Copyright (c) 2006, 2012 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 41-47 Link Here
41
		Options.ZERO_ARGUMENT_OPTIONS.add("-inlineJSR");//$NON-NLS-1$
41
		Options.ZERO_ARGUMENT_OPTIONS.add("-inlineJSR");//$NON-NLS-1$
42
		Options.ZERO_ARGUMENT_OPTIONS.add("-g");//$NON-NLS-1$
42
		Options.ZERO_ARGUMENT_OPTIONS.add("-g");//$NON-NLS-1$
43
		Options.ZERO_ARGUMENT_OPTIONS.add("-g:none");//$NON-NLS-1$
43
		Options.ZERO_ARGUMENT_OPTIONS.add("-g:none");//$NON-NLS-1$
44
		Options.ZERO_ARGUMENT_OPTIONS.add("-nowarn");//$NON-NLS-1$
45
		Options.ZERO_ARGUMENT_OPTIONS.add("-warn:none");//$NON-NLS-1$
44
		Options.ZERO_ARGUMENT_OPTIONS.add("-warn:none");//$NON-NLS-1$
46
		Options.ZERO_ARGUMENT_OPTIONS.add("-preserveAllLocals");//$NON-NLS-1$
45
		Options.ZERO_ARGUMENT_OPTIONS.add("-preserveAllLocals");//$NON-NLS-1$
47
		Options.ZERO_ARGUMENT_OPTIONS.add("-enableJavadoc");//$NON-NLS-1$
46
		Options.ZERO_ARGUMENT_OPTIONS.add("-enableJavadoc");//$NON-NLS-1$
Lines 243-248 Link Here
243
				return 0;
242
				return 0;
244
			}
243
			}
245
		}
244
		}
245
		if (option.startsWith("-nowarn")) {//$NON-NLS-1$
246
			switch (option.length()) {
247
				case 7:
248
					return 0;
249
				case 8:
250
					return -1;
251
				default:
252
					int foldersStart = option.indexOf('[') + 1;
253
					int foldersEnd = option.lastIndexOf(']');
254
					if (foldersStart <= 8 || foldersEnd == -1
255
							|| foldersStart > foldersEnd
256
							|| foldersEnd < option.length() - 1) {
257
						return -1;
258
					}
259
					String folders = option.substring(foldersStart, foldersEnd);
260
					if (folders.length() > 0) {
261
						return 0;
262
					} else {
263
						return -1;
264
					}
265
			}
266
		}
246
		if (option.startsWith("-J")//$NON-NLS-1$
267
		if (option.startsWith("-J")//$NON-NLS-1$
247
				|| option.startsWith("-X")//$NON-NLS-1$
268
				|| option.startsWith("-X")//$NON-NLS-1$
248
				|| option.startsWith("-A")) {//$NON-NLS-1$
269
				|| option.startsWith("-A")) {//$NON-NLS-1$
(-)a/org.eclipse.jdt.core.tests.builder/.cvsignore (-1 lines)
Line 1 Link Here
1
bin
(-)a/org.eclipse.jdt.core.tests.builder/.settings/org.eclipse.core.runtime.prefs (+2 lines)
Added Link Here
1
eclipse.preferences.version=1
2
line.separator=\n
(-)a/org.eclipse.jdt.core.tests.builder/META-INF/MANIFEST.MF (-1 / +1 lines)
Lines 2-8 Link Here
2
Bundle-ManifestVersion: 2
2
Bundle-ManifestVersion: 2
3
Bundle-Name: %pluginName
3
Bundle-Name: %pluginName
4
Bundle-SymbolicName: org.eclipse.jdt.core.tests.builder; singleton:=true
4
Bundle-SymbolicName: org.eclipse.jdt.core.tests.builder; singleton:=true
5
Bundle-Version: 3.8.0.qualifier
5
Bundle-Version: 3.8.1.qualifier
6
Bundle-ClassPath: jdtcoretestsbuilder.jar
6
Bundle-ClassPath: jdtcoretestsbuilder.jar
7
Bundle-Vendor: %providerName
7
Bundle-Vendor: %providerName
8
Bundle-Localization: plugin
8
Bundle-Localization: plugin
(-)a/org.eclipse.jdt.core.tests.builder/plugin.xml (-1 / +2 lines)
Lines 1-5 Link Here
1
<?xml version="1.0" encoding="UTF-8"?>
1
<?xml version="1.0" encoding="UTF-8"?>
2
<?eclipse version="3.0"?>
<!--
2
<?eclipse version="3.0"?>
3
<!--
3
    Copyright (c) 2002, 2009 IBM Corporation and others.
4
    Copyright (c) 2002, 2009 IBM Corporation and others.
4
    All rights reserved. This program and the accompanying materials
5
    All rights reserved. This program and the accompanying materials
5
    are made available under the terms of the Eclipse Public License v1.0
6
    are made available under the terms of the Eclipse Public License v1.0
(-)a/org.eclipse.jdt.core.tests.builder/src/org/eclipse/jdt/core/tests/builder/AnnotationDependencyTests.java (+136 lines)
Lines 8-20 Link Here
8
 * Contributors:
8
 * Contributors:
9
 *     Walter Harley (eclipse@cafewalter.com) - initial implementation
9
 *     Walter Harley (eclipse@cafewalter.com) - initial implementation
10
 *     IBM Corporation - initial API and implementation
10
 *     IBM Corporation - initial API and implementation
11
 *     Stephan Herrmann - Contribution for bug 365992 - [builder] [null] Change of nullness for a parameter doesn't trigger a build for the files that call the method
11
 *******************************************************************************/
12
 *******************************************************************************/
12
package org.eclipse.jdt.core.tests.builder;
13
package org.eclipse.jdt.core.tests.builder;
14
15
import java.io.File;
16
import java.io.IOException;
13
17
14
import junit.framework.Test;
18
import junit.framework.Test;
15
19
16
import org.eclipse.core.resources.IMarker;
20
import org.eclipse.core.resources.IMarker;
21
import org.eclipse.core.runtime.FileLocator;
17
import org.eclipse.core.runtime.IPath;
22
import org.eclipse.core.runtime.IPath;
23
import org.eclipse.core.runtime.Path;
24
import org.eclipse.core.runtime.Platform;
25
import org.eclipse.jdt.core.IClasspathEntry;
26
import org.eclipse.jdt.core.IJavaProject;
27
import org.eclipse.jdt.core.JavaCore;
28
import org.eclipse.jdt.core.JavaModelException;
18
import org.eclipse.jdt.core.compiler.CategorizedProblem;
29
import org.eclipse.jdt.core.compiler.CategorizedProblem;
19
import org.eclipse.jdt.core.tests.util.Util;
30
import org.eclipse.jdt.core.tests.util.Util;
20
31
Lines 127-132 Link Here
127
		env.addClass(this.srcRoot, "p1", "AnnoClass", annoCode);
138
		env.addClass(this.srcRoot, "p1", "AnnoClass", annoCode);
128
	}
139
	}
129
	
140
	
141
	void setupProjectForNullAnnotations() throws IOException, JavaModelException {
142
		// add the org.eclipse.jdt.annotation library (bin/ folder or jar) to the project:
143
		File bundleFile = FileLocator.getBundleFile(Platform.getBundle("org.eclipse.jdt.annotation"));
144
		String annotationsLib = bundleFile.isDirectory() ? bundleFile.getPath()+"/bin" : bundleFile.getPath();
145
		IJavaProject javaProject = env.getJavaProject(this.projectPath);
146
		IClasspathEntry[] rawClasspath = javaProject.getRawClasspath();
147
		int len = rawClasspath.length;
148
		System.arraycopy(rawClasspath, 0, rawClasspath = new IClasspathEntry[len+1], 0, len);
149
		rawClasspath[len] = JavaCore.newLibraryEntry(new Path(annotationsLib), null, null);
150
		javaProject.setRawClasspath(rawClasspath, null);
151
152
		javaProject.setOption(JavaCore.COMPILER_ANNOTATION_NULL_ANALYSIS, JavaCore.ENABLED);
153
	}
154
130
	/**
155
	/**
131
	 * This test makes sure that changing an annotation on type A causes type B
156
	 * This test makes sure that changing an annotation on type A causes type B
132
	 * to be recompiled, if B references A.  See http://bugs.eclipse.org/149768
157
	 * to be recompiled, if B references A.  See http://bugs.eclipse.org/149768
Lines 1371-1374 Link Here
1371
		// verify that B was recompiled
1396
		// verify that B was recompiled
1372
		expectingUniqueCompiledClasses(new String[] { "p1.A", "p1.B" });
1397
		expectingUniqueCompiledClasses(new String[] { "p1.A", "p1.B" });
1373
	}
1398
	}
1399
1400
	// Bug 365992 - [builder] [null] Change of nullness for a parameter doesn't trigger a build for the files that call the method
1401
	public void testParameterAnnotationDependency01() throws JavaModelException, IOException {
1402
		// prepare the project:
1403
		setupProjectForNullAnnotations();
1404
1405
		String test1Code = "package p1;\n"	+
1406
			"public class Test1 {\n" +
1407
			"    public void foo() {\n" +
1408
			"        new Test2().bar(null);\n" +
1409
			"    }\n" +
1410
			"}";
1411
		String test2Code = "package p1;\n" +
1412
			"public class Test2 {\n" +
1413
			"    public void bar(String str) {}\n" +
1414
			"}";
1415
1416
		IPath test1Path = env.addClass( this.srcRoot, "p1", "Test1", test1Code );
1417
		env.addClass( this.srcRoot, "p1", "Test2", test2Code );
1418
1419
		fullBuild( this.projectPath );
1420
		expectingNoProblems();
1421
1422
		// edit Test2 to add @NonNull annotation (changes number of annotations)
1423
		String test2CodeB = "package p1;\n" +
1424
			"import org.eclipse.jdt.annotation.NonNull;\n" +
1425
			"public class Test2 {\n" +
1426
			"    public void bar(@NonNull String str) {}\n" +
1427
			"}";
1428
		env.addClass( this.srcRoot, "p1", "Test2", test2CodeB );
1429
		incrementalBuild( this.projectPath );
1430
		expectingProblemsFor(test1Path, 
1431
				"Problem : Type mismatch: required \'@NonNull String\' but the provided value is null [ resource : </Project/src/p1/Test1.java> range : <81,85> category : <90> severity : <2>]");
1432
1433
		// verify that Test1 was recompiled
1434
		expectingUniqueCompiledClasses(new String[] { "p1.Test1", "p1.Test2" });
1435
1436
		// fix error by changing to @Nullable (change is only in an annotation name)
1437
		String test2CodeC = "package p1;\n" +
1438
			"import org.eclipse.jdt.annotation.Nullable;\n" +
1439
			"public class Test2 {\n" +
1440
			"    public void bar(@Nullable String str) {}\n" +
1441
			"}";
1442
		env.addClass( this.srcRoot, "p1", "Test2", test2CodeC );
1443
		incrementalBuild( this.projectPath );
1444
		expectingNoProblems();
1445
1446
		// verify that Test1 was recompiled
1447
		expectingUniqueCompiledClasses(new String[] { "p1.Test1", "p1.Test2" });
1448
	}
1449
1450
	// Bug 365992 - [builder] [null] Change of nullness for a parameter doesn't trigger a build for the files that call the method
1451
	// Bug 366341 - Incremental compiler fails to detect right scope for annotation related code changes
1452
	public void testReturnAnnotationDependency01() throws JavaModelException, IOException {
1453
		// prepare the project:
1454
		setupProjectForNullAnnotations();
1455
1456
		String test1Code = "package p1;\n" +
1457
			"import org.eclipse.jdt.annotation.NonNull;\n" +
1458
			"public class Test1 {\n" +
1459
			"    public @NonNull Object foo() {\n" +
1460
			"        return new Test2().bar();\n" +
1461
			"    }\n" +
1462
			"}";
1463
		String test2Code = "package p1;\n" +
1464
			"import org.eclipse.jdt.annotation.NonNull;\n" +
1465
			"public class Test2 {\n" +
1466
			"    public @NonNull Object bar() { return this; }\n" +
1467
			"}";
1468
1469
		IPath test1Path = env.addClass( this.srcRoot, "p1", "Test1", test1Code );
1470
		env.addClass( this.srcRoot, "p1", "Test2", test2Code );
1471
1472
		fullBuild( this.projectPath );
1473
		expectingNoProblems();
1474
1475
		// edit Test2 to replace annotation
1476
		String test2CodeB = "package p1;\n" +
1477
			"import org.eclipse.jdt.annotation.Nullable;\n" +
1478
			"public class Test2 {\n" +
1479
			"    public @Nullable Object bar() { return null; }\n" +
1480
			"}";
1481
		env.addClass( this.srcRoot, "p1", "Test2", test2CodeB );
1482
		incrementalBuild( this.projectPath );
1483
		expectingProblemsFor(test1Path, 
1484
			"Problem : Type mismatch: required \'@NonNull Object\' but the provided value can be null [ resource : </Project/src/p1/Test1.java> range : <126,143> category : <90> severity : <2>]");
1485
1486
		// verify that Test1 was recompiled
1487
		expectingUniqueCompiledClasses(new String[] { "p1.Test1", "p1.Test2" });
1488
1489
		// remove annotation, error changes from can be null to unknown nullness
1490
		String test2CodeC = "package p1;\n" +
1491
			"public class Test2 {\n" +
1492
			"    public Object bar() { return null; }\n" +
1493
			"}";
1494
		env.addClass( this.srcRoot, "p1", "Test2", test2CodeC );
1495
		incrementalBuild( this.projectPath );
1496
		expectingProblemsFor(test1Path, 
1497
			"Problem : Potential type mismatch: required \'@NonNull Object\' but nullness of the provided value is unknown [ resource : </Project/src/p1/Test1.java> range : <126,143> category : <90> severity : <1>]");
1498
1499
		// verify that Test1 was recompiled
1500
		expectingUniqueCompiledClasses(new String[] { "p1.Test1", "p1.Test2" });
1501
1502
		// back to initial OK version (re-add @NonNull annotation)
1503
		env.addClass( this.srcRoot, "p1", "Test2", test2Code );
1504
		incrementalBuild( this.projectPath );
1505
		expectingNoProblems();
1506
1507
		// verify that Test1 was recompiled
1508
		expectingUniqueCompiledClasses(new String[] { "p1.Test1", "p1.Test2" });
1509
	}
1374
}
1510
}
(-)a/org.eclipse.jdt.core.tests.builder/src/org/eclipse/jdt/core/tests/builder/ErrorsTests.java (-2 / +202 lines)
Lines 1-5 Link Here
1
/*******************************************************************************
1
/*******************************************************************************
2
 * Copyright (c) 2000, 2010 IBM Corporation and others.
2
 * Copyright (c) 2000, 2012 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 17-30 Link Here
17
import java.io.StringWriter;
17
import java.io.StringWriter;
18
import java.util.Arrays;
18
import java.util.Arrays;
19
import java.util.Comparator;
19
import java.util.Comparator;
20
import java.util.Hashtable;
20
21
21
import junit.framework.*;
22
import junit.framework.Test;
22
23
23
import org.eclipse.core.resources.IFile;
24
import org.eclipse.core.resources.IFile;
24
import org.eclipse.core.resources.IMarker;
25
import org.eclipse.core.resources.IMarker;
25
import org.eclipse.core.resources.IResource;
26
import org.eclipse.core.resources.IResource;
26
import org.eclipse.core.runtime.CoreException;
27
import org.eclipse.core.runtime.CoreException;
27
import org.eclipse.core.runtime.IPath;
28
import org.eclipse.core.runtime.IPath;
29
import org.eclipse.core.runtime.Path;
30
import org.eclipse.jdt.core.IClasspathAttribute;
28
import org.eclipse.jdt.core.IJavaProject;
31
import org.eclipse.jdt.core.IJavaProject;
29
import org.eclipse.jdt.core.IRegion;
32
import org.eclipse.jdt.core.IRegion;
30
import org.eclipse.jdt.core.JavaCore;
33
import org.eclipse.jdt.core.JavaCore;
Lines 43-48 Link Here
43
 * Basic errors tests of the image builder.
46
 * Basic errors tests of the image builder.
44
 */
47
 */
45
public class ErrorsTests extends BuilderTests {
48
public class ErrorsTests extends BuilderTests {
49
	private static final IClasspathAttribute ATTR_IGNORE_OPTIONAL_PROBLEMS_TRUE = JavaCore.newClasspathAttribute(IClasspathAttribute.IGNORE_OPTIONAL_PROBLEMS, "true");
50
46
	private static final Comparator COMPARATOR = new Comparator() {
51
	private static final Comparator COMPARATOR = new Comparator() {
47
		public int compare(Object o1, Object o2) {
52
		public int compare(Object o1, Object o2) {
48
			IResource resource1 = (IResource) o1;
53
			IResource resource1 = (IResource) o1;
Lines 441-444 Link Here
441
	writer.close();
446
	writer.close();
442
	return Util.convertToIndependantLineDelimiter(String.valueOf(stringWriter));
447
	return Util.convertToIndependantLineDelimiter(String.valueOf(stringWriter));
443
}
448
}
449
450
// ignore optional errors
451
public void test0108() throws JavaModelException {
452
	Hashtable options = JavaCore.getOptions();
453
	Hashtable newOptions = JavaCore.getOptions();
454
	newOptions.put(JavaCore.COMPILER_PB_UNUSED_LOCAL, JavaCore.ERROR);
455
456
	JavaCore.setOptions(newOptions);
457
458
	IPath projectPath = env.addProject("P");
459
	env.addExternalJars(projectPath, Util.getJavaClassLibs());
460
461
	// remove old package fragment root so that names don't collide
462
	env.removePackageFragmentRoot(projectPath, "");
463
464
	env.setOutputFolder(projectPath, "bin");
465
	IPath root = new Path("/P/src");
466
	env.addEntry(projectPath, JavaCore.newSourceEntry(root, null, null,
467
			null, new IClasspathAttribute[] { ATTR_IGNORE_OPTIONAL_PROBLEMS_TRUE }));
468
469
	env.addClass(root, "p", "X",
470
			"package p;\n" +
471
			"public class X {\n" +
472
			"	public void foo() {\n" +
473
			"		int i;\n" +
474
			"	}\n" +
475
			"}");
476
477
	fullBuild(projectPath);
478
	expectingNoProblems();
479
480
	JavaCore.setOptions(options);
481
}
482
483
// two different source folders ignore only from one
484
public void test0109() throws JavaModelException {
485
	Hashtable options = JavaCore.getOptions();
486
	Hashtable newOptions = JavaCore.getOptions();
487
	newOptions.put(JavaCore.COMPILER_PB_UNUSED_LOCAL, JavaCore.ERROR);
488
489
	JavaCore.setOptions(newOptions);
490
491
	IPath projectPath = env.addProject("P");
492
	env.addExternalJars(projectPath, Util.getJavaClassLibs());
493
494
	// remove old package fragment root so that names don't collide
495
	env.removePackageFragmentRoot(projectPath, "");
496
497
	env.setOutputFolder(projectPath, "bin");
498
	IPath src = new Path("/P/src");
499
	IPath src2 = new Path("/P/src2");
500
	env.addEntry(projectPath, JavaCore.newSourceEntry(src, null, null,
501
			null, new IClasspathAttribute[] { ATTR_IGNORE_OPTIONAL_PROBLEMS_TRUE }));
502
	env.addEntry(projectPath, JavaCore.newSourceEntry(src2));
503
504
	env.addClass(src, "p", "X",
505
			"package p;\n" +
506
			"public class X {\n" +
507
			"	public void foo() {\n" +
508
			"		int i;\n" +
509
			"	}\n" +
510
			"}");
511
512
	IPath classY = env.addClass(src2, "q", "Y",
513
			"package q;\n" +
514
			"public class Y {\n" +
515
			"	public void foo() {\n" +
516
			"		int i;\n" +
517
			"	}\n" +
518
			"}");
519
520
	fullBuild(projectPath);
521
	expectingNoProblemsFor(src);
522
	expectingOnlySpecificProblemFor(classY, new Problem("q", "The value of the local variable i is not used", classY, 55, 56, CategorizedProblem.CAT_UNNECESSARY_CODE, IMarker.SEVERITY_ERROR));
523
524
	JavaCore.setOptions(options);
525
}
526
527
// two different source folders ignore from both
528
public void test0110() throws JavaModelException {
529
	Hashtable options = JavaCore.getOptions();
530
	Hashtable newOptions = JavaCore.getOptions();
531
	newOptions.put(JavaCore.COMPILER_PB_UNUSED_LOCAL, JavaCore.ERROR);
532
533
	JavaCore.setOptions(newOptions);
534
535
	IPath projectPath = env.addProject("P");
536
	env.addExternalJars(projectPath, Util.getJavaClassLibs());
537
538
	// remove old package fragment root so that names don't collide
539
	env.removePackageFragmentRoot(projectPath, "");
540
541
	env.setOutputFolder(projectPath, "bin");
542
	IPath src = new Path("/P/src");
543
	IPath src2 = new Path("/P/src2");
544
	env.addEntry(projectPath, JavaCore.newSourceEntry(src, null, null,
545
			null, new IClasspathAttribute[] { ATTR_IGNORE_OPTIONAL_PROBLEMS_TRUE }));
546
	env.addEntry(projectPath, JavaCore.newSourceEntry(src2, null, null,
547
			null, new IClasspathAttribute[] { ATTR_IGNORE_OPTIONAL_PROBLEMS_TRUE }));
548
549
	env.addClass(src, "p", "X",
550
			"package p;\n" +
551
			"public class X {\n" +
552
			"	public void foo() {\n" +
553
			"		int i;\n" +
554
			"	}\n" +
555
			"}");
556
557
	env.addClass(src2, "q", "Y",
558
			"package q;\n" +
559
			"public class Y {\n" +
560
			"	public void foo() {\n" +
561
			"		int i;\n" +
562
			"	}\n" +
563
			"}");
564
565
	fullBuild(projectPath);
566
	expectingNoProblems();
567
568
	JavaCore.setOptions(options);
569
}
570
571
//non-optional errors cannot be ignored
572
public void test0111() throws JavaModelException {
573
	Hashtable options = JavaCore.getOptions();
574
	Hashtable newOptions = JavaCore.getOptions();
575
	newOptions.put(JavaCore.COMPILER_PB_UNUSED_LOCAL, JavaCore.ERROR);
576
577
	JavaCore.setOptions(newOptions);
578
579
	IPath projectPath = env.addProject("P");
580
	env.addExternalJars(projectPath, Util.getJavaClassLibs());
581
582
	// remove old package fragment root so that names don't collide
583
	env.removePackageFragmentRoot(projectPath, "");
584
585
	env.setOutputFolder(projectPath, "bin");
586
	IPath root = new Path("/P/src");
587
	env.addEntry(projectPath, JavaCore.newSourceEntry(root, null, null,
588
			null, new IClasspathAttribute[] { ATTR_IGNORE_OPTIONAL_PROBLEMS_TRUE }));
589
590
	IPath classX = env.addClass(root, "p", "X",
591
			"package p;\n" +
592
			"public class X {\n" +
593
			"	public void foo() {\n" +
594
			"		int i;\n" +
595
			"	}\n" +
596
			"	public void bar() {\n" +
597
			"		a++;\n" +
598
			"	}\n" +
599
			"}");
600
601
	fullBuild(projectPath);
602
	expectingOnlySpecificProblemFor(classX, new Problem("p", "a cannot be resolved to a variable", classX, 84, 85, CategorizedProblem.CAT_MEMBER, IMarker.SEVERITY_ERROR));
603
604
	JavaCore.setOptions(options);
605
}
606
607
//task tags cannot be ignored
608
public void test0112() throws JavaModelException {
609
	Hashtable options = JavaCore.getOptions();
610
	Hashtable newOptions = JavaCore.getOptions();
611
	newOptions.put(JavaCore.COMPILER_PB_UNUSED_LOCAL, JavaCore.ERROR);
612
	newOptions.put(JavaCore.COMPILER_TASK_TAGS, "TODO");
613
	newOptions.put(JavaCore.COMPILER_TASK_PRIORITIES, "NORMAL");
614
615
	JavaCore.setOptions(newOptions);
616
617
	IPath projectPath = env.addProject("P");
618
	env.addExternalJars(projectPath, Util.getJavaClassLibs());
619
620
	// remove old package fragment root so that names don't collide
621
	env.removePackageFragmentRoot(projectPath, "");
622
623
	env.setOutputFolder(projectPath, "bin");
624
	IPath root = new Path("/P/src");
625
	env.addEntry(projectPath, JavaCore.newSourceEntry(root, null, null,
626
			null, new IClasspathAttribute[] { ATTR_IGNORE_OPTIONAL_PROBLEMS_TRUE }));
627
628
	IPath classX = env.addClass(root, "p", "X",
629
			"package p;\n" +
630
			"public class X {\n" +
631
			"	public void foo() {\n" +
632
			"		int i;\n" +
633
			"	}\n" +
634
			"	public void bar() {\n" +
635
			"		// TODO nothing\n" +
636
			"	}\n" +
637
			"}");
638
639
	fullBuild(projectPath);
640
	expectingOnlySpecificProblemFor(classX, new Problem("p", "TODO nothing", classX, 87, 99, -1, IMarker.SEVERITY_ERROR));
641
642
	JavaCore.setOptions(options);
643
}
444
}
644
}
(-)a/org.eclipse.jdt.core.tests.builder/src/org/eclipse/jdt/core/tests/builder/IncrementalTests.java (+33 lines)
Lines 1053-1056 Link Here
1053
			JavaCore.setOptions(options);
1053
			JavaCore.setOptions(options);
1054
		}
1054
		}
1055
	}
1055
	}
1056
	
1057
	// https://bugs.eclipse.org/bugs/show_bug.cgi?id=364450
1058
	// Incremental build should not generate buildpath error
1059
	// NOT generated by full build.
1060
	public void testBug364450() throws JavaModelException {
1061
		IPath projectPath = env.addProject("Project"); //$NON-NLS-1$
1062
		env.addExternalJars(projectPath, Util.getJavaClassLibs());
1063
		env.setOutputFolder(projectPath, "bin"); //$NON-NLS-1$
1064
1065
		IPath wPath = env.addClass(projectPath, "w", "W", //$NON-NLS-1$ //$NON-NLS-2$
1066
			"package w;\n" +
1067
			"public class W {\n" +
1068
			"	private w.I i;}"); //$NON-NLS-1$
1069
1070
		IPath aPath = env.addClass(projectPath, "a", "A", //$NON-NLS-1$ //$NON-NLS-2$
1071
			"package a;\n" +
1072
			"import w.I;\n" +
1073
			"import w.W;\n" +
1074
			"public class A {}"); //$NON-NLS-1$
1075
1076
		fullBuild(projectPath);
1077
		expectingSpecificProblemFor(wPath, new Problem("W", "w.I cannot be resolved to a type", wPath, 37, 40, CategorizedProblem.CAT_TYPE, IMarker.SEVERITY_ERROR)); //$NON-NLS-1$ //$NON-NLS-2$
1078
		expectingSpecificProblemFor(aPath, new Problem("A", "The import w.I cannot be resolved", aPath, 18, 21, CategorizedProblem.CAT_IMPORT, IMarker.SEVERITY_ERROR)); //$NON-NLS-1$ //$NON-NLS-2$
1079
1080
		aPath = env.addClass(projectPath, "a", "A", //$NON-NLS-1$ //$NON-NLS-2$
1081
				"package a;\n" +
1082
				"import w.I;\n" +
1083
				"import w.W;\n" +
1084
				"public class A {}"); //$NON-NLS-1$
1085
1086
		incrementalBuild(projectPath);
1087
		expectingSpecificProblemFor(aPath, new Problem("A", "The import w.I cannot be resolved", aPath, 18, 21, CategorizedProblem.CAT_IMPORT, IMarker.SEVERITY_ERROR)); //$NON-NLS-1$ //$NON-NLS-2$
1088
	}
1056
}
1089
}
(-)a/org.eclipse.jdt.core.tests.builder/test.xml (-3 / +4 lines)
Lines 1-6 Link Here
1
<?xml version="1.0"?>
1
<?xml version="1.0" encoding="UTF-8"?>
2
<!--
2
3
    Copyright (c) 2002, 2009 IBM Corporation and others.
3
<!--
4
    Copyright (c) 2002, 2011 IBM Corporation and others.
4
    All rights reserved. This program and the accompanying materials
5
    All rights reserved. This program and the accompanying materials
5
    are made available under the terms of the Eclipse Public License v1.0
6
    are made available under the terms of the Eclipse Public License v1.0
6
    which accompanies this distribution, and is available at
7
    which accompanies this distribution, and is available at
(-)a/org.eclipse.jdt.core.tests.compiler/.cvsignore (-1 lines)
Line 1 Link Here
1
bin
(-)a/org.eclipse.jdt.core.tests.compiler/.settings/org.eclipse.core.resources.prefs (+3 lines)
Added Link Here
1
#Thu Sep 08 10:09:40 EDT 2011
2
eclipse.preferences.version=1
3
encoding//src/org/eclipse/jdt/core/tests/compiler/regression/ScannerTest.java=UTF-8
(-)a/org.eclipse.jdt.core.tests.compiler/.settings/org.eclipse.core.runtime.prefs (+2 lines)
Added Link Here
1
eclipse.preferences.version=1
2
line.separator=\n
(-)a/org.eclipse.jdt.core.tests.compiler/META-INF/MANIFEST.MF (-2 / +3 lines)
Lines 2-8 Link Here
2
Bundle-ManifestVersion: 2
2
Bundle-ManifestVersion: 2
3
Bundle-Name: %pluginName
3
Bundle-Name: %pluginName
4
Bundle-SymbolicName: org.eclipse.jdt.core.tests.compiler
4
Bundle-SymbolicName: org.eclipse.jdt.core.tests.compiler
5
Bundle-Version: 3.8.0.qualifier
5
Bundle-Version: 3.8.1.qualifier
6
Bundle-ClassPath: jdtcoretestscompiler.jar
6
Bundle-ClassPath: jdtcoretestscompiler.jar
7
Bundle-Vendor: %providerName
7
Bundle-Vendor: %providerName
8
Bundle-Localization: plugin
8
Bundle-Localization: plugin
Lines 18-22 Link Here
18
 org.eclipse.jdt.core;bundle-version="[3.7.0,4.0.0)",
18
 org.eclipse.jdt.core;bundle-version="[3.7.0,4.0.0)",
19
 org.eclipse.core.runtime;bundle-version="[3.2.0,4.0.0)",
19
 org.eclipse.core.runtime;bundle-version="[3.2.0,4.0.0)",
20
 org.eclipse.test.performance;bundle-version="[3.1.0,4.0.0)",
20
 org.eclipse.test.performance;bundle-version="[3.1.0,4.0.0)",
21
 org.eclipse.core.resources;bundle-version="[3.2.0,4.0.0)"
21
 org.eclipse.core.resources;bundle-version="[3.2.0,4.0.0)",
22
 org.eclipse.jdt.annotation;bundle-version="[1.0.0,2.0.0)"
22
Bundle-RequiredExecutionEnvironment: J2SE-1.4
23
Bundle-RequiredExecutionEnvironment: J2SE-1.4
(-)a/org.eclipse.jdt.core.tests.compiler/src/org/eclipse/jdt/core/tests/compiler/parser/AnnotationDietRecoveryTest.java (-1 / +56 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 1909-1912 Link Here
1909
		expectedCompletionDietUnitToString,
1909
		expectedCompletionDietUnitToString,
1910
		testName);
1910
		testName);
1911
}
1911
}
1912
// https://bugs.eclipse.org/bugs/show_bug.cgi?id=366003
1913
public void test0041() {
1914
1915
	String s =
1916
			"package snippet;\n" +
1917
					"public class Bug366003 {\n" +
1918
					"        void foo(Object o1){}\n" +
1919
					"        @Blah org.User(@Bla String str){}\n" +
1920
					"}\n";
1921
1922
	String expectedDietUnitToString =
1923
			"package snippet;\n" + 
1924
					"public class Bug366003 {\n" + 
1925
					"  public Bug366003() {\n" + 
1926
					"  }\n" + 
1927
					"  void foo(Object o1) {\n" + 
1928
					"  }\n" + 
1929
					"  @Blah User(@Bla String str) {\n" + 
1930
					"  }\n" + 
1931
					"}\n";
1932
1933
	String expectedDietPlusBodyUnitToString =
1934
			"package snippet;\n" + 
1935
					"public class Bug366003 {\n" + 
1936
					"  public Bug366003() {\n" + 
1937
					"    super();\n" + 
1938
					"  }\n" + 
1939
					"  void foo(Object o1) {\n" + 
1940
					"  }\n" + 
1941
					"  @Blah User(@Bla String str) {\n" + 
1942
					"  }\n" + 
1943
					"}\n";
1944
1945
	String expectedFullUnitToString = expectedDietUnitToString;
1946
1947
	String expectedCompletionDietUnitToString =
1948
			"package snippet;\n" + 
1949
					"public class Bug366003 {\n" + 
1950
					"  public Bug366003() {\n" + 
1951
					"  }\n" + 
1952
					"  void foo(Object o1) {\n" + 
1953
					"  }\n" + 
1954
					"  User(@Bla String str) {\n" + 
1955
					"  }\n" + 
1956
					"}\n";
1957
1958
	String testName = "<annotation recovery>";
1959
	checkParse(
1960
		s.toCharArray(),
1961
		expectedDietUnitToString,
1962
		expectedDietPlusBodyUnitToString,
1963
		expectedFullUnitToString,
1964
		expectedCompletionDietUnitToString,
1965
		testName);
1966
}
1912
}
1967
}
(-)a/org.eclipse.jdt.core.tests.compiler/src/org/eclipse/jdt/core/tests/compiler/parser/SelectionTest.java (-1 / +63 lines)
Lines 1-5 Link Here
1
/*******************************************************************************
1
/*******************************************************************************
2
 * Copyright (c) 2000, 2009 IBM Corporation and others.
2
 * Copyright (c) 2000, 2012 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 2448-2451 Link Here
2448
		expectedReplacedSource,
2448
		expectedReplacedSource,
2449
		testName);
2449
		testName);
2450
}
2450
}
2451
// https://bugs.eclipse.org/bugs/show_bug.cgi?id=291040
2452
public void test56() {
2453
2454
	String str =
2455
			"class X {\n" +
2456
			"    void foo() {\n" +
2457
			"        new X(null) {\n" +
2458
			"            void goo() {\n" +
2459
			"                new X(zoo()) {\n" +
2460
			"                    void voo() {\n" +
2461
			"                    }\n" +
2462
			"                };\n" +
2463
			"            }\n" +
2464
			"\n" +
2465
			"            Object zoo() {\n" +
2466
			"                return null;\n" +
2467
			"            }\n" +
2468
			"        };\n" +
2469
			"    }\n" +
2470
			"\n" +
2471
			"    X(Object k) {\n" +
2472
			"    }\n" +
2473
			"}\n";
2474
2475
	String selection = "zoo";
2476
2477
	String expectedCompletionNodeToString = "<SelectOnMessageSend:zoo()>";
2478
2479
	String completionIdentifier = "zoo";
2480
	String expectedUnitDisplayString =
2481
			"class X {\n" + 
2482
			"  void foo() {\n" + 
2483
			"    new X(null) {\n" + 
2484
			"      void goo() {\n" + 
2485
			"        new X(<SelectOnMessageSend:zoo()>) {\n" + 
2486
			"          void voo() {\n" + 
2487
			"          }\n" + 
2488
			"        };\n" + 
2489
			"      }\n" + 
2490
			"      Object zoo() {\n" + 
2491
			"      }\n" + 
2492
			"    };\n" + 
2493
			"  }\n" + 
2494
			"  X(Object k) {\n" + 
2495
			"  }\n" + 
2496
			"}\n";
2497
	String expectedReplacedSource = "zoo()";
2498
	String testName = "<select>";
2499
2500
	int selectionStart = str.indexOf(selection);
2501
	int selectionEnd = str.indexOf(selection) + selection.length() - 1;
2502
2503
	this.checkMethodParse(
2504
		str.toCharArray(),
2505
		selectionStart,
2506
		selectionEnd,
2507
		expectedCompletionNodeToString,
2508
		expectedUnitDisplayString,
2509
		completionIdentifier,
2510
		expectedReplacedSource,
2511
		testName);
2512
}
2451
}
2513
}
(-)a/org.eclipse.jdt.core.tests.compiler/src/org/eclipse/jdt/core/tests/compiler/regression/AbstractRegressionTest.java (+15 lines)
Lines 21-26 Link Here
21
import java.io.InputStream;
21
import java.io.InputStream;
22
import java.io.InputStreamReader;
22
import java.io.InputStreamReader;
23
import java.io.PrintWriter;
23
import java.io.PrintWriter;
24
import java.net.URL;
24
import java.text.SimpleDateFormat;
25
import java.text.SimpleDateFormat;
25
import java.util.ArrayList;
26
import java.util.ArrayList;
26
import java.util.Date;
27
import java.util.Date;
Lines 31-38 Link Here
31
import java.util.Map;
32
import java.util.Map;
32
import java.util.StringTokenizer;
33
import java.util.StringTokenizer;
33
34
35
import org.eclipse.core.runtime.FileLocator;
34
import org.eclipse.core.runtime.IPath;
36
import org.eclipse.core.runtime.IPath;
35
import org.eclipse.core.runtime.Path;
37
import org.eclipse.core.runtime.Path;
38
import org.eclipse.core.runtime.Platform;
36
import org.eclipse.jdt.core.JavaCore;
39
import org.eclipse.jdt.core.JavaCore;
37
import org.eclipse.jdt.core.ToolFactory;
40
import org.eclipse.jdt.core.ToolFactory;
38
import org.eclipse.jdt.core.compiler.batch.BatchCompiler;
41
import org.eclipse.jdt.core.compiler.batch.BatchCompiler;
Lines 2754-2757 Link Here
2754
			printJavacResultsSummary();
2757
			printJavacResultsSummary();
2755
		}
2758
		}
2756
	}
2759
	}
2760
	/**
2761
	 * Returns the OS path to the directory that contains this plugin.
2762
	 */
2763
	protected String getCompilerTestsPluginDirectoryPath() {
2764
		try {
2765
			URL platformURL = Platform.getBundle("org.eclipse.jdt.core.tests.compiler").getEntry("/");
2766
			return new File(FileLocator.toFileURL(platformURL).getFile()).getAbsolutePath();
2767
		} catch (IOException e) {
2768
			e.printStackTrace();
2769
		}
2770
		return null;
2771
	}
2757
}
2772
}
(-)a/org.eclipse.jdt.core.tests.compiler/src/org/eclipse/jdt/core/tests/compiler/regression/AmbiguousMethodTest.java (-3 / +27 lines)
Lines 1-5 Link Here
1
/*******************************************************************************
1
/*******************************************************************************
2
 * Copyright (c) 2000, 2011 IBM Corporation and others.
2
 * Copyright (c) 2000, 2012 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 76-81 Link Here
76
	}
76
	}
77
	//https://bugs.eclipse.org/bugs/show_bug.cgi?id=122881
77
	//https://bugs.eclipse.org/bugs/show_bug.cgi?id=122881
78
	public void test002() {
78
	public void test002() {
79
		if (this.complianceLevel < ClassFileConstants.JDK1_7) {
79
		this.runConformTest(
80
		this.runConformTest(
80
			new String[] {
81
			new String[] {
81
				"X.java",
82
				"X.java",
Lines 92-99 Link Here
92
				"	}\n" +
93
				"	}\n" +
93
				"}"
94
				"}"
94
			},
95
			},
95
			"works"
96
			"works");
96
		);
97
		} else {
98
			this.runNegativeTest(
99
					new String[] {
100
						"X.java",
101
						"public class X {\n" +
102
						"	static interface I1<E1> { void method(E1 o); }\n" +
103
						"	static interface I2<E2> { void method(E2 o); }\n" +
104
						"	static interface I3<E3, E4> extends I1<E3>, I2<E4> {}\n" +
105
						"	static class Class1 implements I3<String, String> {\n" +
106
						"		public void method(String o) { System.out.println(o); }\n" +
107
						"	}\n" +
108
						"	public static void main(String[] args) {\n" +
109
						"		I3<String, String> i = new Class1();\n" +
110
						"		i.method(\"works\");\n" +
111
						"	}\n" +
112
						"}"
113
					},
114
					"----------\n" + 
115
					"1. ERROR in X.java (at line 4)\n" + 
116
					"	static interface I3<E3, E4> extends I1<E3>, I2<E4> {}\n" + 
117
					"	                 ^^\n" + 
118
					"Name clash: The method method(E1) of type X.I1<E1> has the same erasure as method(E2) of type X.I2<E2> but does not override it\n" + 
119
					"----------\n");
120
		}
97
	}
121
	}
98
	//https://bugs.eclipse.org/bugs/show_bug.cgi?id=122881
122
	//https://bugs.eclipse.org/bugs/show_bug.cgi?id=122881
99
	public void test002a() {
123
	public void test002a() {
(-)a/org.eclipse.jdt.core.tests.compiler/src/org/eclipse/jdt/core/tests/compiler/regression/AnnotationTest.java (-4 / +673 lines)
Lines 1-5 Link Here
1
/*******************************************************************************
1
/*******************************************************************************
2
 * Copyright (c) 2000, 2011 IBM Corporation and others.
2
 * Copyright (c) 2000, 2012 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-14 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 295551
10
 *     Stephan Herrmann  - Contributions for
11
 *     Stephan Herrmann <stephan@cs.tu-berlin.de> - Contribution for bug 185682 - Increment/decrement operators mark local variables as read
11
 *								bug 295551 - Add option to automatically promote all warnings to error
12
 *								bug 185682 - Increment/decrement operators mark local variables as read
13
 *								bug 366003 - CCE in ASTNode.resolveAnnotations(ASTNode.java:639)
12
 *******************************************************************************/
14
 *******************************************************************************/
13
package org.eclipse.jdt.core.tests.compiler.regression;
15
package org.eclipse.jdt.core.tests.compiler.regression;
14
16
Lines 45-51 Link Here
45
	// Static initializer to specify tests subset using TESTS_* static variables
47
	// Static initializer to specify tests subset using TESTS_* static variables
46
	// All specified tests which do not belong to the class are skipped...
48
	// All specified tests which do not belong to the class are skipped...
47
	static {
49
	static {
48
//		TESTS_NAMES = new String[] { "test293" };
50
//		TESTS_NAMES = new String[] { "testBug365437" };
49
//		TESTS_NUMBERS = new int[] { 297 };
51
//		TESTS_NUMBERS = new int[] { 297 };
50
//		TESTS_RANGE = new int[] { 294, -1 };
52
//		TESTS_RANGE = new int[] { 294, -1 };
51
	}
53
	}
Lines 9848-9851 Link Here
9848
			true,
9850
			true,
9849
			customOptions);
9851
			customOptions);
9850
}
9852
}
9853
// Bug 366003 - CCE in ASTNode.resolveAnnotations(ASTNode.java:639) 
9854
// many syntax errors fixed, does not trigger CCE 
9855
public void testBug366003() {
9856
	runNegativeTest(
9857
		new String[] {
9858
			"snippet/Bug366003.java",
9859
			"package snippet;\n" +
9860
			"public class Bug366003 {\n" + 
9861
			"    public void foo(@NonNull Object o1) {\n" + 
9862
			"        System.out.println(o1.toString()); // OK: o1 cannot be null\n" +
9863
			"    }         \n" + 
9864
			"    @NonNull Object bar(@Nullable String s1) {\n" +
9865
			"        foo(null); // cannot pass null argument\n" +
9866
			"        @NonNull String s= null; // cannot assign null value\n" +
9867
			"        @NonNull String t= s1; // cannot assign potentially null value\n" + 
9868
			"        return null; // cannot return null value\n" +
9869
			"    }\n" + 
9870
			"}\n" + 
9871
			"org.eclipse.User.User(@NonNull String name, int uid, @Nullable String email)\n" + 
9872
			""
9873
		},
9874
		"----------\n" + 
9875
		"1. ERROR in snippet\\Bug366003.java (at line 3)\n" + 
9876
		"	public void foo(@NonNull Object o1) {\n" + 
9877
		"	                 ^^^^^^^\n" + 
9878
		"NonNull cannot be resolved to a type\n" + 
9879
		"----------\n" + 
9880
		"2. ERROR in snippet\\Bug366003.java (at line 6)\n" + 
9881
		"	@NonNull Object bar(@Nullable String s1) {\n" + 
9882
		"	 ^^^^^^^\n" + 
9883
		"NonNull cannot be resolved to a type\n" + 
9884
		"----------\n" + 
9885
		"3. ERROR in snippet\\Bug366003.java (at line 6)\n" + 
9886
		"	@NonNull Object bar(@Nullable String s1) {\n" + 
9887
		"	                     ^^^^^^^^\n" + 
9888
		"Nullable cannot be resolved to a type\n" + 
9889
		"----------\n" + 
9890
		"4. ERROR in snippet\\Bug366003.java (at line 8)\n" + 
9891
		"	@NonNull String s= null; // cannot assign null value\n" + 
9892
		"	 ^^^^^^^\n" + 
9893
		"NonNull cannot be resolved to a type\n" + 
9894
		"----------\n" + 
9895
		"5. ERROR in snippet\\Bug366003.java (at line 9)\n" + 
9896
		"	@NonNull String t= s1; // cannot assign potentially null value\n" + 
9897
		"	 ^^^^^^^\n" + 
9898
		"NonNull cannot be resolved to a type\n" + 
9899
		"----------\n" + 
9900
		"6. ERROR in snippet\\Bug366003.java (at line 12)\n" + 
9901
		"	}\n" + 
9902
		"	^\n" + 
9903
		"Syntax error on token \"}\", delete this token\n" + 
9904
		"----------\n" + 
9905
		"7. ERROR in snippet\\Bug366003.java (at line 13)\n" + 
9906
		"	org.eclipse.User.User(@NonNull String name, int uid, @Nullable String email)\n" + 
9907
		"	^^^^^^^^^^^^^^^^\n" + 
9908
		"Syntax error on tokens, delete these tokens\n" + 
9909
		"----------\n" + 
9910
		"8. ERROR in snippet\\Bug366003.java (at line 13)\n" + 
9911
		"	org.eclipse.User.User(@NonNull String name, int uid, @Nullable String email)\n" + 
9912
		"	            ^^^^\n" + 
9913
		"Syntax error, insert \"enum Identifier\" to complete EnumHeaderName\n" + 
9914
		"----------\n" + 
9915
		"9. ERROR in snippet\\Bug366003.java (at line 13)\n" + 
9916
		"	org.eclipse.User.User(@NonNull String name, int uid, @Nullable String email)\n" + 
9917
		"	            ^^^^\n" + 
9918
		"Syntax error, insert \"EnumBody\" to complete EnumDeclaration\n" + 
9919
		"----------\n" + 
9920
		"10. ERROR in snippet\\Bug366003.java (at line 13)\n" + 
9921
		"	org.eclipse.User.User(@NonNull String name, int uid, @Nullable String email)\n" + 
9922
		"	            ^^^^\n" + 
9923
		"Syntax error, insert \"}\" to complete ClassBody\n" + 
9924
		"----------\n" + 
9925
		"11. ERROR in snippet\\Bug366003.java (at line 13)\n" + 
9926
		"	org.eclipse.User.User(@NonNull String name, int uid, @Nullable String email)\n" + 
9927
		"	                 ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^\n" + 
9928
		"Return type for the method is missing\n" + 
9929
		"----------\n" + 
9930
		"12. ERROR in snippet\\Bug366003.java (at line 13)\n" + 
9931
		"	org.eclipse.User.User(@NonNull String name, int uid, @Nullable String email)\n" + 
9932
		"	                       ^^^^^^^\n" + 
9933
		"NonNull cannot be resolved to a type\n" + 
9934
		"----------\n" + 
9935
		"13. ERROR in snippet\\Bug366003.java (at line 13)\n" + 
9936
		"	org.eclipse.User.User(@NonNull String name, int uid, @Nullable String email)\n" + 
9937
		"	                                                      ^^^^^^^^\n" + 
9938
		"Nullable cannot be resolved to a type\n" + 
9939
		"----------\n" + 
9940
		"14. ERROR in snippet\\Bug366003.java (at line 13)\n" + 
9941
		"	org.eclipse.User.User(@NonNull String name, int uid, @Nullable String email)\n" + 
9942
		"	                                                                           ^\n" + 
9943
		"Syntax error, insert \";\" to complete ConstructorDeclaration\n" + 
9944
		"----------\n");
9945
}
9946
// Bug 366003 - CCE in ASTNode.resolveAnnotations(ASTNode.java:639) 
9947
// code is garbage, triggers CCE 
9948
public void testBug366003b() {
9949
	runNegativeTest(
9950
		new String[] {
9951
			"snippet/Bug366003.java",
9952
			"package snippet;\n" +
9953
			"public class Bug366003 {\n" +
9954
			"    public void foo(@Blah Object o1) {        \n" +
9955
			"System.out.println(o1.toString()); // OK: o1 cannot be null     }         \n" +
9956
			"@Blah Object bar(@BlahBlah String s1) {         foo(null); // cannot pass\n" +
9957
			"null argument         @Blah String s= null; // cannot assign null value     \n" +
9958
			"    @Blah String t= s1; // cannot assign potentially null value         \n" +
9959
			"return null; // cannot return null value     }\n" +
9960
			"}\n" +
9961
			"\n" +
9962
			"org.eclipse.User.User(@NonNull String name, int uid, @Nullable String email)\n" +
9963
			""
9964
		},
9965
		"----------\n" + 
9966
		"1. ERROR in snippet\\Bug366003.java (at line 3)\n" + 
9967
		"	public void foo(@Blah Object o1) {        \n" + 
9968
		"	                 ^^^^\n" + 
9969
		"Blah cannot be resolved to a type\n" + 
9970
		"----------\n" + 
9971
		"2. ERROR in snippet\\Bug366003.java (at line 4)\n" + 
9972
		"	System.out.println(o1.toString()); // OK: o1 cannot be null     }         \n" + 
9973
		"	                                 ^\n" + 
9974
		"Syntax error, insert \"}\" to complete MethodBody\n" + 
9975
		"----------\n" + 
9976
		"3. ERROR in snippet\\Bug366003.java (at line 5)\n" + 
9977
		"	@Blah Object bar(@BlahBlah String s1) {         foo(null); // cannot pass\n" + 
9978
		"	 ^^^^\n" + 
9979
		"Blah cannot be resolved to a type\n" + 
9980
		"----------\n" + 
9981
		"4. ERROR in snippet\\Bug366003.java (at line 5)\n" + 
9982
		"	@Blah Object bar(@BlahBlah String s1) {         foo(null); // cannot pass\n" + 
9983
		"	                  ^^^^^^^^\n" + 
9984
		"BlahBlah cannot be resolved to a type\n" + 
9985
		"----------\n" + 
9986
		"5. ERROR in snippet\\Bug366003.java (at line 6)\n" + 
9987
		"	null argument         @Blah String s= null; // cannot assign null value     \n" + 
9988
		"	^^^^\n" + 
9989
		"Syntax error on token \"null\", @ expected\n" + 
9990
		"----------\n" + 
9991
		"6. ERROR in snippet\\Bug366003.java (at line 11)\n" + 
9992
		"	org.eclipse.User.User(@NonNull String name, int uid, @Nullable String email)\n" + 
9993
		"	^^^^^^^^^^^^^^^^\n" + 
9994
		"Syntax error on tokens, delete these tokens\n" + 
9995
		"----------\n" + 
9996
		"7. ERROR in snippet\\Bug366003.java (at line 11)\n" + 
9997
		"	org.eclipse.User.User(@NonNull String name, int uid, @Nullable String email)\n" + 
9998
		"	            ^^^^\n" + 
9999
		"Syntax error, insert \"enum Identifier\" to complete EnumHeaderName\n" + 
10000
		"----------\n" + 
10001
		"8. ERROR in snippet\\Bug366003.java (at line 11)\n" + 
10002
		"	org.eclipse.User.User(@NonNull String name, int uid, @Nullable String email)\n" + 
10003
		"	            ^^^^\n" + 
10004
		"Syntax error, insert \"EnumBody\" to complete EnumDeclaration\n" + 
10005
		"----------\n" + 
10006
		"9. ERROR in snippet\\Bug366003.java (at line 11)\n" + 
10007
		"	org.eclipse.User.User(@NonNull String name, int uid, @Nullable String email)\n" + 
10008
		"	            ^^^^\n" + 
10009
		"Syntax error, insert \"}\" to complete ClassBody\n" + 
10010
		"----------\n" + 
10011
		"10. ERROR in snippet\\Bug366003.java (at line 11)\n" + 
10012
		"	org.eclipse.User.User(@NonNull String name, int uid, @Nullable String email)\n" + 
10013
		"	                 ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^\n" + 
10014
		"Return type for the method is missing\n" + 
10015
		"----------\n" + 
10016
		"11. ERROR in snippet\\Bug366003.java (at line 11)\n" + 
10017
		"	org.eclipse.User.User(@NonNull String name, int uid, @Nullable String email)\n" + 
10018
		"	                       ^^^^^^^\n" + 
10019
		"NonNull cannot be resolved to a type\n" + 
10020
		"----------\n" + 
10021
		"12. ERROR in snippet\\Bug366003.java (at line 11)\n" + 
10022
		"	org.eclipse.User.User(@NonNull String name, int uid, @Nullable String email)\n" + 
10023
		"	                                                      ^^^^^^^^\n" + 
10024
		"Nullable cannot be resolved to a type\n" + 
10025
		"----------\n" + 
10026
		"13. ERROR in snippet\\Bug366003.java (at line 11)\n" + 
10027
		"	org.eclipse.User.User(@NonNull String name, int uid, @Nullable String email)\n" + 
10028
		"	                                                                           ^\n" + 
10029
		"Syntax error, insert \";\" to complete ConstructorDeclaration\n" + 
10030
		"----------\n");
10031
}
10032
// Bug 366003 - CCE in ASTNode.resolveAnnotations(ASTNode.java:639) 
10033
// minimal syntax error to trigger CCE 
10034
public void testBug366003c() {
10035
	runNegativeTest(
10036
		new String[] {
10037
			"snippet/Bug366003.java",
10038
			"package snippet;\n" +
10039
			"public class Bug366003 {\n" +
10040
			"    void foo(Object o1) {\n" + 
10041
			"    }\n" + 
10042
			"org.User(@Bla String a)"
10043
		},
10044
		"----------\n" + 
10045
		"1. ERROR in snippet\\Bug366003.java (at line 5)\n" + 
10046
		"	org.User(@Bla String a)\n" + 
10047
		"	^^^\n" + 
10048
		"Syntax error on token \"org\", delete this token\n" + 
10049
		"----------\n" + 
10050
		"2. ERROR in snippet\\Bug366003.java (at line 5)\n" + 
10051
		"	org.User(@Bla String a)\n" + 
10052
		"	^^^\n" + 
10053
		"Syntax error, insert \"enum Identifier\" to complete EnumHeaderName\n" + 
10054
		"----------\n" + 
10055
		"3. ERROR in snippet\\Bug366003.java (at line 5)\n" + 
10056
		"	org.User(@Bla String a)\n" + 
10057
		"	^^^\n" + 
10058
		"Syntax error, insert \"EnumBody\" to complete EnumDeclaration\n" + 
10059
		"----------\n" + 
10060
		"4. ERROR in snippet\\Bug366003.java (at line 5)\n" + 
10061
		"	org.User(@Bla String a)\n" + 
10062
		"	^^^\n" + 
10063
		"Syntax error, insert \"}\" to complete ClassBody\n" + 
10064
		"----------\n" + 
10065
		"5. ERROR in snippet\\Bug366003.java (at line 5)\n" + 
10066
		"	org.User(@Bla String a)\n" + 
10067
		"	    ^^^^^^^^^^^^^^^^^^^\n" + 
10068
		"Return type for the method is missing\n" + 
10069
		"----------\n" + 
10070
		"6. ERROR in snippet\\Bug366003.java (at line 5)\n" + 
10071
		"	org.User(@Bla String a)\n" + 
10072
		"	          ^^^\n" + 
10073
		"Bla cannot be resolved to a type\n" + 
10074
		"----------\n" + 
10075
		"7. ERROR in snippet\\Bug366003.java (at line 5)\n" + 
10076
		"	org.User(@Bla String a)\n" + 
10077
		"	                      ^\n" + 
10078
		"Syntax error, insert \";\" to complete ConstructorDeclaration\n" + 
10079
		"----------\n");
10080
}
10081
// unfinished attempt to trigger the same CCE via catch formal parameters
10082
public void testBug366003d() {
10083
	runNegativeTest(
10084
		new String[] {
10085
			"snippet/Bug366003.java",
10086
			"package snippet; \n" +
10087
			"public class Bug366003 {\n" +
10088
			"	void foo() {\n" +
10089
			"		try {\n" +
10090
			"			System.out.println(\"\");\n" +
10091
			"		} catch (Exeption eFirst) {\n" +
10092
			"			e } catch (@Blah Exception eSecond) {\n" +
10093
			"			e }\n" +
10094
			"	}\n" +
10095
			"}\n"
10096
		},
10097
		"----------\n" +
10098
		"1. ERROR in snippet\\Bug366003.java (at line 7)\n" +
10099
		"	e } catch (@Blah Exception eSecond) {\n" +
10100
		"	^\n" +
10101
		"Syntax error, insert \"AssignmentOperator Expression\" to complete Assignment\n" +
10102
		"----------\n" +
10103
		"2. ERROR in snippet\\Bug366003.java (at line 7)\n" +
10104
		"	e } catch (@Blah Exception eSecond) {\n" +
10105
		"	^\n" +
10106
		"Syntax error, insert \";\" to complete BlockStatements\n" +
10107
		"----------\n" +
10108
		"3. ERROR in snippet\\Bug366003.java (at line 8)\n" +
10109
		"	e }\n" +
10110
		"	^\n" +
10111
		"Syntax error, insert \"AssignmentOperator Expression\" to complete Expression\n" +
10112
		"----------\n" +
10113
		"4. ERROR in snippet\\Bug366003.java (at line 8)\n" +
10114
		"	e }\n" +
10115
		"	^\n" +
10116
		"Syntax error, insert \";\" to complete BlockStatements\n" +
10117
		"----------\n");
10118
}
10119
public void testBug366003e() {
10120
	runNegativeTest(
10121
		new String[] {
10122
			"snippet/Bug366003.java",
10123
			"package snippet;\n" +
10124
			"public class Bug366003 {\n" +
10125
			"        void foo(Object o1){}\n" +
10126
			"        @Blah org.User(@Bla String str){}\n" +
10127
			"}\n"
10128
		},
10129
		"----------\n" + 
10130
		"1. ERROR in snippet\\Bug366003.java (at line 4)\n" + 
10131
		"	@Blah org.User(@Bla String str){}\n" + 
10132
		"	 ^^^^\n" + 
10133
		"Blah cannot be resolved to a type\n" + 
10134
		"----------\n" + 
10135
		"2. ERROR in snippet\\Bug366003.java (at line 4)\n" + 
10136
		"	@Blah org.User(@Bla String str){}\n" + 
10137
		"	          ^^^^\n" + 
10138
		"Syntax error on token \"User\", Identifier expected after this token\n" + 
10139
		"----------\n" + 
10140
		"3. ERROR in snippet\\Bug366003.java (at line 4)\n" + 
10141
		"	@Blah org.User(@Bla String str){}\n" + 
10142
		"	          ^^^^^^^^^^^^^^^^^^^^^\n" + 
10143
		"Return type for the method is missing\n" + 
10144
		"----------\n" + 
10145
		"4. ERROR in snippet\\Bug366003.java (at line 4)\n" + 
10146
		"	@Blah org.User(@Bla String str){}\n" + 
10147
		"	                ^^^\n" + 
10148
		"Bla cannot be resolved to a type\n" +
10149
		"----------\n");
10150
}
10151
// https://bugs.eclipse.org/bugs/show_bug.cgi?id=365437
10152
public void testBug365437a() {
10153
	Map customOptions = getCompilerOptions();
10154
	customOptions.put(CompilerOptions.OPTION_ReportUnusedPrivateMember, CompilerOptions.ERROR);
10155
	String testFiles [] = new String[] {
10156
			"p/A.java",
10157
			"package p;\n" +
10158
			"import p1.*;\n" +
10159
			"public class A {\n" +
10160
			"	@p1.PreDestroy\n" +
10161
			"	private void foo1(){}\n" +
10162
			"	@PreDestroy\n" +
10163
			"	private void foo2(){}\n" +
10164
			"	@SuppressWarnings(\"null\")\n" +
10165
			"	@PostConstruct\n" +
10166
			"	private void foo1a(){}\n" +
10167
			"	@PostConstruct\n" +
10168
			"	private void foo2a(){}\n" +
10169
			"	@Deprecated" +
10170
			"	private void foo3(){}" +
10171
			"}\n",
10172
			"p1/PreDestroy.java",
10173
			"package p1;\n" +
10174
			"public @interface PreDestroy{}",
10175
			"p1/PostConstruct.java",
10176
			"package p1;\n" +
10177
			"public @interface PostConstruct{}"
10178
			};
10179
	String expectedErrorString = 
10180
			"----------\n" + 
10181
			"1. WARNING in p\\A.java (at line 8)\n" + 
10182
			"	@SuppressWarnings(\"null\")\n" + 
10183
			"	                  ^^^^^^\n" + 
10184
			"Unnecessary @SuppressWarnings(\"null\")\n" + 
10185
			"----------\n" + 
10186
			"2. ERROR in p\\A.java (at line 13)\n" + 
10187
			"	@Deprecated	private void foo3(){}}\n" + 
10188
			"	           	             ^^^^^^\n" + 
10189
			"The method foo3() from the type A is never used locally\n" + 
10190
			"----------\n";
10191
	runNegativeTest(
10192
			true,
10193
			testFiles,
10194
			null, 
10195
			customOptions,
10196
			expectedErrorString,
10197
			JavacTestOptions.Excuse.EclipseWarningConfiguredAsError);
10198
}
10199
// https://bugs.eclipse.org/bugs/show_bug.cgi?id=365437
10200
public void testBug365437b() {
10201
	Map customOptions = getCompilerOptions();
10202
	customOptions.put(CompilerOptions.OPTION_ReportUnusedPrivateMember, CompilerOptions.ERROR);
10203
	customOptions.put(CompilerOptions.OPTION_AnnotationBasedNullAnalysis, CompilerOptions.ENABLED);
10204
	customOptions.put(CompilerOptions.OPTION_NonNullAnnotationName, "p.NonNull");
10205
	String testFiles [] = new String[] {
10206
			"A.java",
10207
			"import javax.annotation.*;\n" +
10208
			"public class A {\n" +
10209
			"	@javax.annotation.PreDestroy\n" +
10210
			"	private void foo1(){}\n" +
10211
			"	@PreDestroy\n" +
10212
			"	private void foo2(){}\n" +
10213
			"	@javax.annotation.Resource\n" +
10214
			"	private void foo1a(){}\n" +
10215
			"	@Resource\n" +
10216
			"	@p.NonNull\n" +
10217
			"	private Object foo2a(){ return new Object();}\n" +
10218
			"	@javax.annotation.PostConstruct\n" +
10219
			"	@Deprecated\n" +
10220
			"	private void foo3(){}\n" +
10221
			"	@p.NonNull\n" +
10222
			"	private Object foo3a(){ return new Object();}\n" +
10223
			"}\n",
10224
			"p/NonNull.java",
10225
			"package p;\n" +
10226
			"import static java.lang.annotation.ElementType.*;\n" +
10227
			"import java.lang.annotation.*;\n" +
10228
			"@Target({TYPE, METHOD,PARAMETER,LOCAL_VARIABLE})\n" +
10229
			"public @interface NonNull {\n" +
10230
			"}"
10231
			};
10232
	String expectedErrorString = 
10233
			"----------\n" + 
10234
			"1. ERROR in A.java (at line 16)\n" + 
10235
			"	private Object foo3a(){ return new Object();}\n" + 
10236
			"	               ^^^^^^^\n" + 
10237
			"The method foo3a() from the type A is never used locally\n" + 
10238
			"----------\n";
10239
	runNegativeTest(
10240
			true,
10241
			testFiles,
10242
			null, 
10243
			customOptions,
10244
			expectedErrorString,
10245
			JavacTestOptions.Excuse.EclipseWarningConfiguredAsError);
10246
}
10247
// https://bugs.eclipse.org/bugs/show_bug.cgi?id=365437
10248
// @SafeVarargs
10249
public void testBug365437c() {
10250
	if (this.complianceLevel < ClassFileConstants.JDK1_7) return;
10251
	Map customOptions = getCompilerOptions();
10252
	customOptions.put(CompilerOptions.OPTION_ReportUnusedPrivateMember, CompilerOptions.ERROR);
10253
	String testFiles [] = new String[] {
10254
			"p/A.java",
10255
			"package p;\n" +
10256
			"import p1.*;\n" +
10257
			"public class A {\n" +
10258
			"	@p1.PreDestroy\n" +
10259
			"	private void foo1(){}\n" +
10260
			"	@PreDestroy\n" +
10261
			"	private void foo2(){}\n" +
10262
			"	@SuppressWarnings(\"null\")\n" +
10263
			"	@PostConstruct\n" +
10264
			"	private void foo1a(){}\n" +
10265
			"	@PostConstruct\n" +
10266
			"	private void foo2a(){}\n" +
10267
			"	@SafeVarargs" +
10268
			"	private final void foo3(Object... o){}" +
10269
			"}\n",
10270
			"p1/PreDestroy.java",
10271
			"package p1;\n" +
10272
			"public @interface PreDestroy{}",
10273
			"p1/PostConstruct.java",
10274
			"package p1;\n" +
10275
			"public @interface PostConstruct{}"
10276
			};
10277
	String expectedErrorString = 
10278
			"----------\n" + 
10279
			"1. WARNING in p\\A.java (at line 8)\n" + 
10280
			"	@SuppressWarnings(\"null\")\n" + 
10281
			"	                  ^^^^^^\n" + 
10282
			"Unnecessary @SuppressWarnings(\"null\")\n" + 
10283
			"----------\n" + 
10284
			"2. ERROR in p\\A.java (at line 13)\n" + 
10285
			"	@SafeVarargs	private final void foo3(Object... o){}}\n" + 
10286
			"	            	                   ^^^^^^^^^^^^^^^^^\n" + 
10287
			"The method foo3(Object...) from the type A is never used locally\n" + 
10288
			"----------\n";
10289
	runNegativeTest(
10290
			true,
10291
			testFiles,
10292
			null, 
10293
			customOptions,
10294
			expectedErrorString,
10295
			JavacTestOptions.Excuse.EclipseWarningConfiguredAsError);
10296
}
10297
// https://bugs.eclipse.org/bugs/show_bug.cgi?id=365437
10298
// unused constructor
10299
public void testBug365437d() {
10300
	Map customOptions = getCompilerOptions();
10301
	customOptions.put(CompilerOptions.OPTION_ReportUnusedPrivateMember, CompilerOptions.ERROR);
10302
	customOptions.put(CompilerOptions.OPTION_ReportUnusedPrivateMember, CompilerOptions.ERROR);
10303
	customOptions.put(CompilerOptions.OPTION_AnnotationBasedNullAnalysis, CompilerOptions.ENABLED);
10304
	customOptions.put(CompilerOptions.OPTION_NonNullAnnotationName, "p.NonNull");
10305
	this.runNegativeTest(
10306
		true,
10307
		new String[] {
10308
			"Example.java",
10309
			"class Example {\n" +
10310
			"  @p.Annot\n" +
10311
			"  private Example() {\n" +
10312
			"  }\n" +
10313
			"  public Example(int i) {\n" +
10314
			"  }\n" +
10315
			"}\n" +
10316
			"class E1 {\n" +
10317
			"	 @Deprecated\n" +
10318
			"    private E1() {}\n" +
10319
			"    public E1(long l) {}\n" +
10320
			"}\n" +
10321
			"class E2 {\n" +
10322
			"	 @SuppressWarnings(\"null\")\n" +
10323
			"    private E2() {}\n" +
10324
			"    public E2(long l) {}\n" +
10325
			"}\n" +
10326
			"class E3 {\n" +
10327
			"	 @p.NonNull\n" +
10328
			"    private E3() {}\n" +
10329
			"    public E3(long l) {}\n" +
10330
			"}\n" +
10331
			"class E4 {\n" +
10332
			"	 @Deprecated\n" +
10333
			"	 @p.Annot\n" +
10334
			"    private E4() {}\n" +
10335
			"    public E4(long l) {}\n" +
10336
			"}\n",
10337
			"p/NonNull.java",
10338
			"package p;\n" +
10339
			"import static java.lang.annotation.ElementType.*;\n" +
10340
			"import java.lang.annotation.*;\n" +
10341
			"@Target({TYPE, METHOD,PARAMETER,CONSTRUCTOR})\n" +
10342
			"public @interface NonNull {\n" +
10343
			"}",
10344
			"p/Annot.java",
10345
			"package p;\n" +
10346
			"import static java.lang.annotation.ElementType.*;\n" +
10347
			"import java.lang.annotation.*;\n" +
10348
			"@Target({TYPE, METHOD,PARAMETER,LOCAL_VARIABLE, CONSTRUCTOR})\n" +
10349
			"public @interface Annot {\n" +
10350
			"}"
10351
		},
10352
		null, customOptions,
10353
		"----------\n" + 
10354
		"1. ERROR in Example.java (at line 10)\n" + 
10355
		"	private E1() {}\n" + 
10356
		"	        ^^^^\n" + 
10357
		"The constructor E1() is never used locally\n" + 
10358
		"----------\n" + 
10359
		"2. WARNING in Example.java (at line 14)\n" + 
10360
		"	@SuppressWarnings(\"null\")\n" + 
10361
		"	                  ^^^^^^\n" + 
10362
		"Unnecessary @SuppressWarnings(\"null\")\n" + 
10363
		"----------\n" + 
10364
		"3. ERROR in Example.java (at line 15)\n" + 
10365
		"	private E2() {}\n" + 
10366
		"	        ^^^^\n" + 
10367
		"The constructor E2() is never used locally\n" + 
10368
		"----------\n" + 
10369
		"4. ERROR in Example.java (at line 20)\n" + 
10370
		"	private E3() {}\n" + 
10371
		"	        ^^^^\n" + 
10372
		"The constructor E3() is never used locally\n" + 
10373
		"----------\n",
10374
		JavacTestOptions.Excuse.EclipseWarningConfiguredAsError);
10375
}
10376
// https://bugs.eclipse.org/bugs/show_bug.cgi?id=365437
10377
// unused field
10378
public void testBug365437e() {
10379
	Map customOptions = getCompilerOptions();
10380
	customOptions.put(CompilerOptions.OPTION_ReportUnusedPrivateMember, CompilerOptions.ERROR);
10381
	customOptions.put(CompilerOptions.OPTION_ReportUnusedPrivateMember, CompilerOptions.ERROR);
10382
	customOptions.put(CompilerOptions.OPTION_AnnotationBasedNullAnalysis, CompilerOptions.ENABLED);
10383
	customOptions.put(CompilerOptions.OPTION_NonNullAnnotationName, "p.NonNull");
10384
	this.runNegativeTest(
10385
		true,
10386
		new String[] {
10387
			"Example.java",
10388
			"class Example {\n" +
10389
			"  @p.Annot\n" +
10390
			"  private int Ex;\n" +
10391
			"}\n" +
10392
			"class E1 {\n" +
10393
			"	 @Deprecated\n" +
10394
			"    private int E1;\n" +
10395
			"}\n" +
10396
			"class E2 {\n" +
10397
			"	 @SuppressWarnings(\"null\")\n" +
10398
			"    private int E2;\n" +
10399
			"}\n" +
10400
			"class E3 {\n" +
10401
			"	 @p.NonNull\n" +
10402
			"    private int E3;\n" +
10403
			"}\n" +
10404
			"class E4 {\n" +
10405
			"	 @Deprecated\n" +
10406
			"	 @p.Annot\n" +
10407
			"    private int E4;\n" +
10408
			"}\n",
10409
			"p/NonNull.java",
10410
			"package p;\n" +
10411
			"import static java.lang.annotation.ElementType.*;\n" +
10412
			"import java.lang.annotation.*;\n" +
10413
			"@Target({TYPE, METHOD,PARAMETER,LOCAL_VARIABLE, FIELD})\n" +
10414
			"public @interface NonNull {\n" +
10415
			"}",
10416
			"p/Annot.java",
10417
			"package p;\n" +
10418
			"import static java.lang.annotation.ElementType.*;\n" +
10419
			"import java.lang.annotation.*;\n" +
10420
			"@Target({TYPE, METHOD,PARAMETER,LOCAL_VARIABLE, FIELD})\n" +
10421
			"public @interface Annot {\n" +
10422
			"}"
10423
		},
10424
		null, customOptions,
10425
		"----------\n" + 
10426
		"1. ERROR in Example.java (at line 7)\n" + 
10427
		"	private int E1;\n" + 
10428
		"	            ^^\n" + 
10429
		"The value of the field E1.E1 is not used\n" + 
10430
		"----------\n" + 
10431
		"2. WARNING in Example.java (at line 10)\n" + 
10432
		"	@SuppressWarnings(\"null\")\n" + 
10433
		"	                  ^^^^^^\n" + 
10434
		"Unnecessary @SuppressWarnings(\"null\")\n" + 
10435
		"----------\n" + 
10436
		"3. ERROR in Example.java (at line 11)\n" + 
10437
		"	private int E2;\n" + 
10438
		"	            ^^\n" + 
10439
		"The value of the field E2.E2 is not used\n" + 
10440
		"----------\n" + 
10441
		"4. ERROR in Example.java (at line 15)\n" + 
10442
		"	private int E3;\n" + 
10443
		"	            ^^\n" + 
10444
		"The value of the field E3.E3 is not used\n" + 
10445
		"----------\n",
10446
		JavacTestOptions.Excuse.EclipseWarningConfiguredAsError);
10447
}
10448
// https://bugs.eclipse.org/bugs/show_bug.cgi?id=365437
10449
// unused type
10450
public void testBug365437f() {
10451
	Map customOptions = getCompilerOptions();
10452
	customOptions.put(CompilerOptions.OPTION_ReportUnusedPrivateMember, CompilerOptions.ERROR);
10453
	customOptions.put(CompilerOptions.OPTION_ReportUnusedPrivateMember, CompilerOptions.ERROR);
10454
	customOptions.put(CompilerOptions.OPTION_AnnotationBasedNullAnalysis, CompilerOptions.ENABLED);
10455
	customOptions.put(CompilerOptions.OPTION_NonNullAnnotationName, "p.NonNull");
10456
	this.runNegativeTest(
10457
		true,
10458
		new String[] {
10459
			"Example.java",
10460
			"class Example {\n" +
10461
			"  @p.Annot\n" +
10462
			"  private class Ex{}\n" +
10463
			"}\n" +
10464
			"class E1 {\n" +
10465
			"	 @Deprecated\n" +
10466
			"    private class E11{}\n" +
10467
			"}\n" +
10468
			"class E2 {\n" +
10469
			"	 @SuppressWarnings(\"null\")\n" +
10470
			"    private class E22{}\n" +
10471
			"}\n" +
10472
			"class E3 {\n" +
10473
			"	 @p.NonNull\n" +
10474
			"    private class E33{}\n" +
10475
			"}\n" +
10476
			"class E4 {\n" +
10477
			"	 @Deprecated\n" +
10478
			"	 @p.Annot\n" +
10479
			"    private class E44{}\n" +
10480
			"}\n",
10481
			"p/NonNull.java",
10482
			"package p;\n" +
10483
			"import static java.lang.annotation.ElementType.*;\n" +
10484
			"import java.lang.annotation.*;\n" +
10485
			"@Target({TYPE, METHOD,PARAMETER,LOCAL_VARIABLE})\n" +
10486
			"public @interface NonNull {\n" +
10487
			"}",
10488
			"p/Annot.java",
10489
			"package p;\n" +
10490
			"import static java.lang.annotation.ElementType.*;\n" +
10491
			"import java.lang.annotation.*;\n" +
10492
			"@Target({TYPE, METHOD,PARAMETER,LOCAL_VARIABLE, CONSTRUCTOR})\n" +
10493
			"public @interface Annot {\n" +
10494
			"}"
10495
		},
10496
		null, customOptions,
10497
		"----------\n" + 
10498
		"1. ERROR in Example.java (at line 7)\n" + 
10499
		"	private class E11{}\n" + 
10500
		"	              ^^^\n" + 
10501
		"The type E1.E11 is never used locally\n" + 
10502
		"----------\n" + 
10503
		"2. WARNING in Example.java (at line 10)\n" + 
10504
		"	@SuppressWarnings(\"null\")\n" + 
10505
		"	                  ^^^^^^\n" + 
10506
		"Unnecessary @SuppressWarnings(\"null\")\n" + 
10507
		"----------\n" + 
10508
		"3. ERROR in Example.java (at line 11)\n" + 
10509
		"	private class E22{}\n" + 
10510
		"	              ^^^\n" + 
10511
		"The type E2.E22 is never used locally\n" + 
10512
		"----------\n" + 
10513
		"4. ERROR in Example.java (at line 15)\n" + 
10514
		"	private class E33{}\n" + 
10515
		"	              ^^^\n" + 
10516
		"The type E3.E33 is never used locally\n" + 
10517
		"----------\n",
10518
		JavacTestOptions.Excuse.EclipseWarningConfiguredAsError);
10519
}
9851
}
10520
}
(-)a/org.eclipse.jdt.core.tests.compiler/src/org/eclipse/jdt/core/tests/compiler/regression/AssignmentTest.java (-2 / +85 lines)
Lines 1-5 Link Here
1
/*******************************************************************************
1
/*******************************************************************************
2
 * Copyright (c) 2005, 2010 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 13-18 Link Here
13
13
14
import java.util.Map;
14
import java.util.Map;
15
15
16
import org.eclipse.jdt.internal.compiler.classfmt.ClassFileConstants;
16
import org.eclipse.jdt.internal.compiler.impl.CompilerOptions;
17
import org.eclipse.jdt.internal.compiler.impl.CompilerOptions;
17
18
18
import junit.framework.Test;
19
import junit.framework.Test;
Lines 1221-1227 Link Here
1221
		"1. ERROR in p\\X.java (at line 4)\n" +
1222
		"1. ERROR in p\\X.java (at line 4)\n" +
1222
		"	public static String s;\n" +
1223
		"	public static String s;\n" +
1223
		"	                     ^\n" +
1224
		"	                     ^\n" +
1224
		"The field s cannot be declared static; static fields can only be declared in static or top level types\n" +
1225
		"The field s cannot be declared static in a non-static inner type, unless initialized with a constant expression\n" +
1225
		"----------\n" +
1226
		"----------\n" +
1226
		"2. ERROR in p\\X.java (at line 6)\n" +
1227
		"2. ERROR in p\\X.java (at line 6)\n" +
1227
		"	X.XX.s = s;    }\n" +
1228
		"	X.XX.s = s;    }\n" +
Lines 1929-1934 Link Here
1929
		options
1930
		options
1930
	);
1931
	);
1931
}
1932
}
1933
// https://bugs.eclipse.org/bugs/show_bug.cgi?id=362279
1934
public void test068() {
1935
	this.runNegativeTest(
1936
		new String[] {
1937
			"X.java",
1938
			"public class X  {\n" +
1939
			"	Integer f = 'a'; // Field declaration.\n" +
1940
			"	public Integer main() {\n" +
1941
			"		Integer i = 'a'; // local declaration with initialization.\n" +
1942
			"		i = 'a'; // assignment\n" +
1943
			"                Integer [] ia = new Integer [] { 'a' }; // array initializer.\n" +
1944
			"		return 'a'; // return statement.\n" +
1945
			"		switch (i) {\n" +
1946
			"		case 'a' :   // case statement\n" +
1947
			"		}\n" +
1948
			"	}\n" +
1949
			"}\n"
1950
		},
1951
		this.complianceLevel < ClassFileConstants.JDK1_5 ? 
1952
		"----------\n" + 
1953
		"1. ERROR in X.java (at line 2)\n" + 
1954
		"	Integer f = \'a\'; // Field declaration.\n" + 
1955
		"	            ^^^\n" + 
1956
		"Type mismatch: cannot convert from char to Integer\n" + 
1957
		"----------\n" + 
1958
		"2. ERROR in X.java (at line 4)\n" + 
1959
		"	Integer i = \'a\'; // local declaration with initialization.\n" + 
1960
		"	            ^^^\n" + 
1961
		"Type mismatch: cannot convert from char to Integer\n" + 
1962
		"----------\n" + 
1963
		"3. ERROR in X.java (at line 5)\n" + 
1964
		"	i = \'a\'; // assignment\n" + 
1965
		"	    ^^^\n" + 
1966
		"Type mismatch: cannot convert from char to Integer\n" + 
1967
		"----------\n" + 
1968
		"4. ERROR in X.java (at line 6)\n" + 
1969
		"	Integer [] ia = new Integer [] { \'a\' }; // array initializer.\n" + 
1970
		"	                                 ^^^\n" + 
1971
		"Type mismatch: cannot convert from char to Integer\n" + 
1972
		"----------\n" + 
1973
		"5. ERROR in X.java (at line 7)\n" + 
1974
		"	return \'a\'; // return statement.\n" + 
1975
		"	       ^^^\n" + 
1976
		"Type mismatch: cannot convert from char to Integer\n" + 
1977
		"----------\n" + 
1978
		"6. ERROR in X.java (at line 8)\n" + 
1979
		"	switch (i) {\n" + 
1980
		"	        ^\n" + 
1981
		"Cannot switch on a value of type Integer. Only convertible int values or enum variables are permitted\n" + 
1982
		"----------\n" : 
1983
			"----------\n" + 
1984
			"1. ERROR in X.java (at line 2)\n" + 
1985
			"	Integer f = \'a\'; // Field declaration.\n" + 
1986
			"	            ^^^\n" + 
1987
			"Type mismatch: cannot convert from char to Integer\n" + 
1988
			"----------\n" + 
1989
			"2. ERROR in X.java (at line 4)\n" + 
1990
			"	Integer i = \'a\'; // local declaration with initialization.\n" + 
1991
			"	            ^^^\n" + 
1992
			"Type mismatch: cannot convert from char to Integer\n" + 
1993
			"----------\n" + 
1994
			"3. ERROR in X.java (at line 5)\n" + 
1995
			"	i = \'a\'; // assignment\n" + 
1996
			"	    ^^^\n" + 
1997
			"Type mismatch: cannot convert from char to Integer\n" + 
1998
			"----------\n" + 
1999
			"4. ERROR in X.java (at line 6)\n" + 
2000
			"	Integer [] ia = new Integer [] { \'a\' }; // array initializer.\n" + 
2001
			"	                                 ^^^\n" + 
2002
			"Type mismatch: cannot convert from char to Integer\n" + 
2003
			"----------\n" + 
2004
			"5. ERROR in X.java (at line 7)\n" + 
2005
			"	return \'a\'; // return statement.\n" + 
2006
			"	       ^^^\n" + 
2007
			"Type mismatch: cannot convert from char to Integer\n" + 
2008
			"----------\n" + 
2009
			"6. ERROR in X.java (at line 9)\n" + 
2010
			"	case \'a\' :   // case statement\n" + 
2011
			"	     ^^^\n" + 
2012
			"Type mismatch: cannot convert from char to Integer\n" + 
2013
			"----------\n");
2014
}
1932
public static Class testClass() {
2015
public static Class testClass() {
1933
	return AssignmentTest.class;
2016
	return AssignmentTest.class;
1934
}
2017
}
(-)a/org.eclipse.jdt.core.tests.compiler/src/org/eclipse/jdt/core/tests/compiler/regression/AutoBoxingTest.java (-18 / +92 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 2911-2917 Link Here
2911
2911
2912
	// https://bugs.eclipse.org/bugs/show_bug.cgi?id=85491
2912
	// https://bugs.eclipse.org/bugs/show_bug.cgi?id=85491
2913
	public void test101() {
2913
	public void test101() {
2914
		this.runConformTest(
2914
		this.runNegativeTest(
2915
			new String[] {
2915
			new String[] {
2916
				"X.java",
2916
				"X.java",
2917
				"public class X {\n" +
2917
				"public class X {\n" +
Lines 2924-2931 Link Here
2924
				"	}\n" +
2924
				"	}\n" +
2925
				"}\n",
2925
				"}\n",
2926
			},
2926
			},
2927
			"222"
2927
			"----------\n" + 
2928
		);
2928
			"1. ERROR in X.java (at line 5)\n" + 
2929
			"	new X().foo(1);\n" + 
2930
			"	        ^^^\n" + 
2931
			"The method foo(Object[]) is ambiguous for the type X\n" + 
2932
			"----------\n" + 
2933
			"2. ERROR in X.java (at line 6)\n" + 
2934
			"	new X().foo(new Integer(1));\n" + 
2935
			"	        ^^^\n" + 
2936
			"The method foo(Object[]) is ambiguous for the type X\n" + 
2937
			"----------\n" + 
2938
			"3. ERROR in X.java (at line 7)\n" + 
2939
			"	new X().foo(1, new Integer(1));\n" + 
2940
			"	        ^^^\n" + 
2941
			"The method foo(Object[]) is ambiguous for the type X\n" + 
2942
			"----------\n");
2929
		this.runNegativeTest(
2943
		this.runNegativeTest(
2930
			new String[] {
2944
			new String[] {
2931
				"X.java",
2945
				"X.java",
Lines 4859-4865 Link Here
4859
}
4873
}
4860
//https://bugs.eclipse.org/bugs/show_bug.cgi?id=231709
4874
//https://bugs.eclipse.org/bugs/show_bug.cgi?id=231709
4861
public void test165() {
4875
public void test165() {
4862
	this.runConformTest(
4876
	this.runNegativeTest(
4863
		new String[] {
4877
		new String[] {
4864
			"X.java",
4878
			"X.java",
4865
			"public class X {\n" + 
4879
			"public class X {\n" + 
Lines 4892-4898 Link Here
4892
			"    }     \n" + 
4906
			"    }     \n" + 
4893
			"}\n",
4907
			"}\n",
4894
		},
4908
		},
4895
		"");
4909
		"----------\n" + 
4910
		"1. WARNING in X.java (at line 3)\n" + 
4911
		"	Integer i1 = 10 ;\n" + 
4912
		"	             ^^\n" + 
4913
		"The expression of type int is boxed into Integer\n" + 
4914
		"----------\n" + 
4915
		"2. ERROR in X.java (at line 5)\n" + 
4916
		"	i1 = s;\n" + 
4917
		"	     ^\n" + 
4918
		"Type mismatch: cannot convert from short to Integer\n" + 
4919
		"----------\n" + 
4920
		"3. WARNING in X.java (at line 6)\n" + 
4921
		"	switch (i1)\n" + 
4922
		"	        ^^\n" + 
4923
		"The expression of type Integer is unboxed into int\n" + 
4924
		"----------\n" + 
4925
		"4. ERROR in X.java (at line 8)\n" + 
4926
		"	case s:\n" + 
4927
		"	     ^\n" + 
4928
		"Type mismatch: cannot convert from short to Integer\n" + 
4929
		"----------\n" + 
4930
		"5. WARNING in X.java (at line 12)\n" + 
4931
		"	Integer i2 = 10 ;\n" + 
4932
		"	             ^^\n" + 
4933
		"The expression of type int is boxed into Integer\n" + 
4934
		"----------\n" + 
4935
		"6. ERROR in X.java (at line 14)\n" + 
4936
		"	i2 = b;\n" + 
4937
		"	     ^\n" + 
4938
		"Type mismatch: cannot convert from byte to Integer\n" + 
4939
		"----------\n" + 
4940
		"7. WARNING in X.java (at line 15)\n" + 
4941
		"	switch (i2)\n" + 
4942
		"	        ^^\n" + 
4943
		"The expression of type Integer is unboxed into int\n" + 
4944
		"----------\n" + 
4945
		"8. ERROR in X.java (at line 17)\n" + 
4946
		"	case b:\n" + 
4947
		"	     ^\n" + 
4948
		"Type mismatch: cannot convert from byte to Integer\n" + 
4949
		"----------\n" + 
4950
		"9. WARNING in X.java (at line 21)\n" + 
4951
		"	Integer i3 = 10 ;\n" + 
4952
		"	             ^^\n" + 
4953
		"The expression of type int is boxed into Integer\n" + 
4954
		"----------\n" + 
4955
		"10. ERROR in X.java (at line 23)\n" + 
4956
		"	i3 = c;\n" + 
4957
		"	     ^\n" + 
4958
		"Type mismatch: cannot convert from char to Integer\n" + 
4959
		"----------\n" + 
4960
		"11. WARNING in X.java (at line 24)\n" + 
4961
		"	switch (i3)\n" + 
4962
		"	        ^^\n" + 
4963
		"The expression of type Integer is unboxed into int\n" + 
4964
		"----------\n" + 
4965
		"12. ERROR in X.java (at line 26)\n" + 
4966
		"	case c:\n" + 
4967
		"	     ^\n" + 
4968
		"Type mismatch: cannot convert from char to Integer\n" + 
4969
		"----------\n");
4896
}
4970
}
4897
4971
4898
//https://bugs.eclipse.org/bugs/show_bug.cgi?id=231709 - variation
4972
//https://bugs.eclipse.org/bugs/show_bug.cgi?id=231709 - variation
Lines 4947-4981 Link Here
4947
		"	             ^\n" + 
5021
		"	             ^\n" + 
4948
		"Type mismatch: cannot convert from char to Integer\n" + 
5022
		"Type mismatch: cannot convert from char to Integer\n" + 
4949
		"----------\n" + 
5023
		"----------\n" + 
4950
		"4. WARNING in X.java (at line 11)\n" + 
5024
		"4. ERROR in X.java (at line 11)\n" + 
4951
		"	Integer is = s;\n" + 
5025
		"	Integer is = s;\n" + 
4952
		"	             ^\n" + 
5026
		"	             ^\n" + 
4953
		"The expression of type short is boxed into Integer\n" + 
5027
		"Type mismatch: cannot convert from short to Integer\n" + 
4954
		"----------\n" + 
5028
		"----------\n" + 
4955
		"5. WARNING in X.java (at line 12)\n" + 
5029
		"5. ERROR in X.java (at line 12)\n" + 
4956
		"	Integer ib = b;\n" + 
5030
		"	Integer ib = b;\n" + 
4957
		"	             ^\n" + 
5031
		"	             ^\n" + 
4958
		"The expression of type byte is boxed into Integer\n" + 
5032
		"Type mismatch: cannot convert from byte to Integer\n" + 
4959
		"----------\n" + 
5033
		"----------\n" + 
4960
		"6. WARNING in X.java (at line 13)\n" + 
5034
		"6. ERROR in X.java (at line 13)\n" + 
4961
		"	Integer ic = c;	\n" + 
5035
		"	Integer ic = c;	\n" + 
4962
		"	             ^\n" + 
5036
		"	             ^\n" + 
4963
		"The expression of type char is boxed into Integer\n" + 
5037
		"Type mismatch: cannot convert from char to Integer\n" + 
4964
		"----------\n" + 
5038
		"----------\n" + 
4965
		"7. WARNING in X.java (at line 16)\n" + 
5039
		"7. ERROR in X.java (at line 16)\n" + 
4966
		"	Integer is = (short)0;\n" + 
5040
		"	Integer is = (short)0;\n" + 
4967
		"	             ^^^^^^^^\n" + 
5041
		"	             ^^^^^^^^\n" + 
4968
		"The expression of type short is boxed into Integer\n" + 
5042
		"Type mismatch: cannot convert from short to Integer\n" + 
4969
		"----------\n" + 
5043
		"----------\n" + 
4970
		"8. WARNING in X.java (at line 17)\n" + 
5044
		"8. ERROR in X.java (at line 17)\n" + 
4971
		"	Integer ib = (byte)0;\n" + 
5045
		"	Integer ib = (byte)0;\n" + 
4972
		"	             ^^^^^^^\n" + 
5046
		"	             ^^^^^^^\n" + 
4973
		"The expression of type byte is boxed into Integer\n" + 
5047
		"Type mismatch: cannot convert from byte to Integer\n" + 
4974
		"----------\n" + 
5048
		"----------\n" + 
4975
		"9. WARNING in X.java (at line 18)\n" + 
5049
		"9. ERROR in X.java (at line 18)\n" + 
4976
		"	Integer ic = (char)0;	\n" + 
5050
		"	Integer ic = (char)0;	\n" + 
4977
		"	             ^^^^^^^\n" + 
5051
		"	             ^^^^^^^\n" + 
4978
		"The expression of type char is boxed into Integer\n" + 
5052
		"Type mismatch: cannot convert from char to Integer\n" + 
4979
		"----------\n" + 
5053
		"----------\n" + 
4980
		"10. WARNING in X.java (at line 21)\n" + 
5054
		"10. WARNING in X.java (at line 21)\n" + 
4981
		"	Short si = 0;\n" + 
5055
		"	Short si = 0;\n" + 
(-)a/org.eclipse.jdt.core.tests.compiler/src/org/eclipse/jdt/core/tests/compiler/regression/BatchCompilerTest.java (-78 / +830 lines)
Lines 1-5 Link Here
1
/*******************************************************************************
1
/*******************************************************************************
2
 * Copyright (c) 2000, 2011 IBM Corporation and others.
2
 * Copyright (c) 2000, 2012 IBM Corporation and others.
3
 * All rights reserved. This program and the accompanying materials
3
 * All rights reserved. This program and the accompanying materials
4
 * are made available under the terms of the Eclipse Public License v1.0
4
 * are made available under the terms of the Eclipse Public License v1.0
5
 * which accompanies this distribution, and is available at
5
 * which accompanies this distribution, and is available at
Lines 8-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
16
 *     							bug 359721 - [options] add command line option for new warning token "resource"
17
 *     							bug 186342 - [compiler][null] Using annotations for null checking
18
 *								bug 365208 - [compiler][batch] command line options for annotation based null analysis
19
 *								bug 370639 - [compiler][resource] restore the default for resource leak warnings
14
 *******************************************************************************/
20
 *******************************************************************************/
15
package org.eclipse.jdt.core.tests.compiler.regression;
21
package org.eclipse.jdt.core.tests.compiler.regression;
16
22
Lines 47-54 Link Here
47
	static final String JRE_HOME_DIR = Util.getJREDirectory();
53
	static final String JRE_HOME_DIR = Util.getJREDirectory();
48
	private static final Main MAIN = new Main(null/*outWriter*/, null/*errWriter*/, false/*systemExit*/, null/*options*/, null/*progress*/);
54
	private static final Main MAIN = new Main(null/*outWriter*/, null/*errWriter*/, false/*systemExit*/, null/*options*/, null/*progress*/);
49
55
56
	private static final String NONNULL_BY_DEFAULT_ANNOTATION_CONTENT = "package org.eclipse.jdt.annotation;\n" +
57
			"import static java.lang.annotation.ElementType.*;\n" +
58
			"import java.lang.annotation.*;\n" +
59
			"@Documented\n" +
60
			"@Retention(RetentionPolicy.CLASS)\n" +
61
			"@Target({ PACKAGE, TYPE, METHOD, CONSTRUCTOR })\n" +
62
			"public @interface NonNullByDefault{\n" +
63
			"}";
64
	private static final String NULLABLE_ANNOTATION_CONTENT = "package org.eclipse.jdt.annotation;\n" +
65
			"import static java.lang.annotation.ElementType.*;\n" +
66
			"import java.lang.annotation.*;\n" +
67
			"@Documented\n" +
68
			"@Retention(RetentionPolicy.CLASS)\n" +
69
			"@Target({ METHOD, PARAMETER })\n" +
70
			"public @interface Nullable{\n" +
71
			"}\n";
72
	private static final String NONNULL_ANNOTATION_CONTENT = "package org.eclipse.jdt.annotation;\n" +
73
			"import static java.lang.annotation.ElementType.*;\n" +
74
			"import java.lang.annotation.*;\n" +
75
			"@Documented\n" +
76
			"@Retention(RetentionPolicy.CLASS)\n" +
77
			"@Target({ METHOD, PARAMETER })\n" +
78
			"public @interface NonNull{\n" +
79
			"}\n";
80
50
	static {
81
	static {
51
//		TESTS_NAMES = new String[] { "test295_warn_options" };
82
//		TESTS_NAMES = new String[] { "test31" };
52
//		TESTS_NUMBERS = new int[] { 306 };
83
//		TESTS_NUMBERS = new int[] { 306 };
53
//		TESTS_RANGE = new int[] { 298, -1 };
84
//		TESTS_RANGE = new int[] { 298, -1 };
54
	}
85
	}
Lines 1546-1551 Link Here
1546
        "    -deprecation     + deprecation outside deprecated code (equivalent to\n" +
1577
        "    -deprecation     + deprecation outside deprecated code (equivalent to\n" +
1547
        "                       -warn:+deprecation)\n" +
1578
        "                       -warn:+deprecation)\n" +
1548
        "    -nowarn -warn:none disable all warnings\n" +
1579
        "    -nowarn -warn:none disable all warnings\n" +
1580
        "    -nowarn:[<directories separated by " + File.pathSeparator+ ">]\n" +
1581
        "                       specify directories from which optional problems should\n" +
1582
        "                       be ignored\n" +
1549
        "    -?:warn -help:warn display advanced warning options\n" +
1583
        "    -?:warn -help:warn display advanced warning options\n" +
1550
        " \n" +
1584
        " \n" +
1551
        " Error options:\n" + 
1585
        " Error options:\n" + 
Lines 1610-1615 Link Here
1610
        "    -enableJavadoc     consider references in javadoc\n" +
1644
        "    -enableJavadoc     consider references in javadoc\n" +
1611
        "    -Xemacs            used to enable emacs-style output in the console.\n" +
1645
        "    -Xemacs            used to enable emacs-style output in the console.\n" +
1612
        "                       It does not affect the xml log output\n" +
1646
        "                       It does not affect the xml log output\n" +
1647
        "    -nonNullByDefault  for annotation based null analysis assume nonnull\n" + 
1648
        "                       as the global default\n" + 
1613
        " \n" +
1649
        " \n" +
1614
        "    -? -help           print this help message\n" +
1650
        "    -? -help           print this help message\n" +
1615
        "    -v -version        print compiler version\n" +
1651
        "    -v -version        print compiler version\n" +
Lines 1656-1669 Link Here
1656
        " Warning options:\n" + 
1692
        " Warning options:\n" + 
1657
        "    -deprecation         + deprecation outside deprecated code\n" + 
1693
        "    -deprecation         + deprecation outside deprecated code\n" + 
1658
        "    -nowarn -warn:none disable all warnings\n" + 
1694
        "    -nowarn -warn:none disable all warnings\n" + 
1695
        "    -nowarn:[<directories separated by " + File.pathSeparator+ ">]\n" +
1696
        "                       specify directories from which optional problems should\n" +
1697
        "                       be ignored\n" +
1659
        "    -warn:<warnings separated by ,>    enable exactly the listed warnings\n" + 
1698
        "    -warn:<warnings separated by ,>    enable exactly the listed warnings\n" + 
1660
        "    -warn:+<warnings separated by ,>   enable additional warnings\n" + 
1699
        "    -warn:+<warnings separated by ,>   enable additional warnings\n" + 
1661
        "    -warn:-<warnings separated by ,>   disable specific warnings\n" + 
1700
        "    -warn:-<warnings separated by ,>   disable specific warnings\n" + 
1701
        "      all                  enable all warnings\n" + 
1662
        "      allDeadCode          dead code including trivial if(DEBUG) check\n" + 
1702
        "      allDeadCode          dead code including trivial if(DEBUG) check\n" + 
1663
        "      allDeprecation       deprecation including inside deprecated code\n" + 
1703
        "      allDeprecation       deprecation including inside deprecated code\n" + 
1664
        "      allJavadoc           invalid or missing javadoc\n" + 
1704
        "      allJavadoc           invalid or missing javadoc\n" + 
1665
        "      allOver-ann          all missing @Override annotations\n" + 
1705
        "      allOver-ann          all missing @Override annotations\n" + 
1666
        "      all-static-method    all method can be declared as static warnings\n" +
1706
        "      all-static-method    all method can be declared as static warnings\n" + 
1667
        "      assertIdentifier   + ''assert'' used as identifier\n" + 
1707
        "      assertIdentifier   + ''assert'' used as identifier\n" + 
1668
        "      boxing               autoboxing conversion\n" + 
1708
        "      boxing               autoboxing conversion\n" + 
1669
        "      charConcat         + char[] in String concat\n" + 
1709
        "      charConcat         + char[] in String concat\n" + 
Lines 1697-1707 Link Here
1697
        "      nls                  string literal lacking non-nls tag //$NON-NLS-<n>$\n" + 
1737
        "      nls                  string literal lacking non-nls tag //$NON-NLS-<n>$\n" + 
1698
        "      noEffectAssign     + assignment without effect\n" + 
1738
        "      noEffectAssign     + assignment without effect\n" + 
1699
        "      null                 potential missing or redundant null check\n" + 
1739
        "      null                 potential missing or redundant null check\n" + 
1740
        "      nullAnnot(<annot. names separated by |>) + annotation based null analysis,\n" +
1741
        "                           nullable|nonnull|nonnullbydefault annotation types\n" +
1742
        "                           optionally specified using fully qualified names\n" +
1700
        "      nullDereference    + missing null check\n" + 
1743
        "      nullDereference    + missing null check\n" + 
1701
        "      over-ann             missing @Override annotation (superclass)\n" + 
1744
        "      over-ann             missing @Override annotation (superclass)\n" + 
1702
        "      paramAssign          assignment to a parameter\n" + 
1745
        "      paramAssign          assignment to a parameter\n" + 
1703
        "      pkgDefaultMethod   + attempt to override package-default method\n" + 
1746
        "      pkgDefaultMethod   + attempt to override package-default method\n" + 
1704
        "      raw                + usage of raw type\n" + 
1747
        "      raw                + usage of raw type\n" + 
1748
        "      resource           + (pot.) unsafe usage of resource of type Closeable\n" + 
1705
        "      semicolon            unnecessary semicolon, empty statement\n" + 
1749
        "      semicolon            unnecessary semicolon, empty statement\n" + 
1706
        "      serial             + missing serialVersionUID\n" + 
1750
        "      serial             + missing serialVersionUID\n" + 
1707
        "      specialParamHiding   constructor or setter parameter hiding a field\n" + 
1751
        "      specialParamHiding   constructor or setter parameter hiding a field\n" + 
Lines 1716-1722 Link Here
1716
        "      syntheticAccess      synthetic access for innerclass\n" + 
1760
        "      syntheticAccess      synthetic access for innerclass\n" + 
1717
        "      tasks(<tags separated by |>) tasks identified by tags inside comments\n" + 
1761
        "      tasks(<tags separated by |>) tasks identified by tags inside comments\n" + 
1718
        "      typeHiding         + type parameter hiding another type\n" + 
1762
        "      typeHiding         + type parameter hiding another type\n" + 
1719
        "      unavoidableGenericProblems + ignore unavoidable type safety problems\n" +
1763
        "      unavoidableGenericProblems + ignore unavoidable type safety problems\n" + 
1720
        "                                   due to raw APIs\n" + 
1764
        "                                   due to raw APIs\n" + 
1721
        "      unchecked          + unchecked type operation\n" + 
1765
        "      unchecked          + unchecked type operation\n" + 
1722
        "      unnecessaryElse      unnecessary else clause\n" + 
1766
        "      unnecessaryElse      unnecessary else clause\n" + 
Lines 1734-1740 Link Here
1734
        "      unusedTypeArgs     + unused type arguments for method and constructor\n" + 
1778
        "      unusedTypeArgs     + unused type arguments for method and constructor\n" + 
1735
        "      uselessTypeCheck     unnecessary cast/instanceof operation\n" + 
1779
        "      uselessTypeCheck     unnecessary cast/instanceof operation\n" + 
1736
        "      varargsCast        + varargs argument need explicit cast\n" + 
1780
        "      varargsCast        + varargs argument need explicit cast\n" + 
1737
        "      warningToken       + unsupported or unnecessary @SuppressWarnings\n" + 
1781
        "      warningToken       + unsupported or unnecessary @SuppressWarnings\n" +
1738
        "\n";
1782
        "\n";
1739
	String expandedExpectedOutput =
1783
	String expandedExpectedOutput =
1740
		MessageFormat.format(expectedOutput, new String[] {
1784
		MessageFormat.format(expectedOutput, new String[] {
Lines 1794-1799 Link Here
1794
			"		<argument value=\"---OUTPUT_DIR_PLACEHOLDER---\"/>\n" + 
1838
			"		<argument value=\"---OUTPUT_DIR_PLACEHOLDER---\"/>\n" + 
1795
			"	</command_line>\n" + 
1839
			"	</command_line>\n" + 
1796
			"	<options>\n" + 
1840
			"	<options>\n" + 
1841
			"		<option key=\"org.eclipse.jdt.core.compiler.annotation.nonnull\" value=\"org.eclipse.jdt.annotation.NonNull\"/>\n" + 
1842
			"		<option key=\"org.eclipse.jdt.core.compiler.annotation.nonnullbydefault\" value=\"org.eclipse.jdt.annotation.NonNullByDefault\"/>\n" + 
1843
			"		<option key=\"org.eclipse.jdt.core.compiler.annotation.nonnullisdefault\" value=\"disabled\"/>\n" + 
1844
			"		<option key=\"org.eclipse.jdt.core.compiler.annotation.nullable\" value=\"org.eclipse.jdt.annotation.Nullable\"/>\n" + 
1845
			"		<option key=\"org.eclipse.jdt.core.compiler.annotation.nullanalysis\" value=\"disabled\"/>\n" + 
1797
			"		<option key=\"org.eclipse.jdt.core.compiler.codegen.inlineJsrBytecode\" value=\"disabled\"/>\n" + 
1846
			"		<option key=\"org.eclipse.jdt.core.compiler.codegen.inlineJsrBytecode\" value=\"disabled\"/>\n" + 
1798
			"		<option key=\"org.eclipse.jdt.core.compiler.codegen.targetPlatform\" value=\"1.5\"/>\n" + 
1847
			"		<option key=\"org.eclipse.jdt.core.compiler.codegen.targetPlatform\" value=\"1.5\"/>\n" + 
1799
			"		<option key=\"org.eclipse.jdt.core.compiler.codegen.unusedLocal\" value=\"optimize out\"/>\n" + 
1848
			"		<option key=\"org.eclipse.jdt.core.compiler.codegen.unusedLocal\" value=\"optimize out\"/>\n" + 
Lines 1803-1809 Link Here
1803
			"		<option key=\"org.eclipse.jdt.core.compiler.debug.sourceFile\" value=\"generate\"/>\n" + 
1852
			"		<option key=\"org.eclipse.jdt.core.compiler.debug.sourceFile\" value=\"generate\"/>\n" + 
1804
			"		<option key=\"org.eclipse.jdt.core.compiler.doc.comment.support\" value=\"disabled\"/>\n" + 
1853
			"		<option key=\"org.eclipse.jdt.core.compiler.doc.comment.support\" value=\"disabled\"/>\n" + 
1805
			"		<option key=\"org.eclipse.jdt.core.compiler.generateClassFiles\" value=\"enabled\"/>\n" + 
1854
			"		<option key=\"org.eclipse.jdt.core.compiler.generateClassFiles\" value=\"enabled\"/>\n" + 
1806
			"		<option key=\"org.eclipse.jdt.core.compiler.maxProblemPerUnit\" value=\"100\"/>\n" +
1855
			"		<option key=\"org.eclipse.jdt.core.compiler.maxProblemPerUnit\" value=\"100\"/>\n" + 
1807
			"		<option key=\"org.eclipse.jdt.core.compiler.problem.annotationSuperInterface\" value=\"warning\"/>\n" + 
1856
			"		<option key=\"org.eclipse.jdt.core.compiler.problem.annotationSuperInterface\" value=\"warning\"/>\n" + 
1808
			"		<option key=\"org.eclipse.jdt.core.compiler.problem.assertIdentifier\" value=\"warning\"/>\n" + 
1857
			"		<option key=\"org.eclipse.jdt.core.compiler.problem.assertIdentifier\" value=\"warning\"/>\n" + 
1809
			"		<option key=\"org.eclipse.jdt.core.compiler.problem.autoboxing\" value=\"ignore\"/>\n" + 
1858
			"		<option key=\"org.eclipse.jdt.core.compiler.problem.autoboxing\" value=\"ignore\"/>\n" + 
Lines 1816-1821 Link Here
1816
			"		<option key=\"org.eclipse.jdt.core.compiler.problem.discouragedReference\" value=\"warning\"/>\n" + 
1865
			"		<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" + 
1866
			"		<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" + 
1867
			"		<option key=\"org.eclipse.jdt.core.compiler.problem.enumIdentifier\" value=\"warning\"/>\n" + 
1868
			"		<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" + 
1869
			"		<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" + 
1870
			"		<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" + 
1871
			"		<option key=\"org.eclipse.jdt.core.compiler.problem.fieldHiding\" value=\"ignore\"/>\n" + 
Lines 1852-1863 Link Here
1852
			"		<option key=\"org.eclipse.jdt.core.compiler.problem.noImplicitStringConversion\" value=\"warning\"/>\n" + 
1902
			"		<option key=\"org.eclipse.jdt.core.compiler.problem.noImplicitStringConversion\" value=\"warning\"/>\n" + 
1853
			"		<option key=\"org.eclipse.jdt.core.compiler.problem.nonExternalizedStringLiteral\" value=\"ignore\"/>\n" + 
1903
			"		<option key=\"org.eclipse.jdt.core.compiler.problem.nonExternalizedStringLiteral\" value=\"ignore\"/>\n" + 
1854
			"		<option key=\"org.eclipse.jdt.core.compiler.problem.nullReference\" value=\"warning\"/>\n" + 
1904
			"		<option key=\"org.eclipse.jdt.core.compiler.problem.nullReference\" value=\"warning\"/>\n" + 
1905
			"		<option key=\"org.eclipse.jdt.core.compiler.problem.nullSpecInsufficientInfo\" value=\"warning\"/>\n" + 
1906
			"		<option key=\"org.eclipse.jdt.core.compiler.problem.nullSpecViolation\" value=\"error\"/>\n" + 
1855
			"		<option key=\"org.eclipse.jdt.core.compiler.problem.overridingMethodWithoutSuperInvocation\" value=\"ignore\"/>\n" + 
1907
			"		<option key=\"org.eclipse.jdt.core.compiler.problem.overridingMethodWithoutSuperInvocation\" value=\"ignore\"/>\n" + 
1856
			"		<option key=\"org.eclipse.jdt.core.compiler.problem.overridingPackageDefaultMethod\" value=\"warning\"/>\n" + 
1908
			"		<option key=\"org.eclipse.jdt.core.compiler.problem.overridingPackageDefaultMethod\" value=\"warning\"/>\n" + 
1857
			"		<option key=\"org.eclipse.jdt.core.compiler.problem.parameterAssignment\" value=\"ignore\"/>\n" + 
1909
			"		<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" + 
1910
			"		<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" + 
1911
			"		<option key=\"org.eclipse.jdt.core.compiler.problem.potentialNullReference\" value=\"ignore\"/>\n" + 
1860
			"		<option key=\"org.eclipse.jdt.core.compiler.problem.rawTypeReference\" value=\"warning\"/>\n" +
1912
			"		<option key=\"org.eclipse.jdt.core.compiler.problem.potentialNullSpecViolation\" value=\"error\"/>\n" + 
1913
			"		<option key=\"org.eclipse.jdt.core.compiler.problem.potentiallyUnclosedCloseable\" value=\"ignore\"/>\n" + 
1914
			"		<option key=\"org.eclipse.jdt.core.compiler.problem.rawTypeReference\" value=\"warning\"/>\n" + 
1915
			"		<option key=\"org.eclipse.jdt.core.compiler.problem.redundantNullAnnotation\" value=\"warning\"/>\n" + 
1861
			"		<option key=\"org.eclipse.jdt.core.compiler.problem.redundantNullCheck\" value=\"ignore\"/>\n" + 
1916
			"		<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" + 
1917
			"		<option key=\"org.eclipse.jdt.core.compiler.problem.redundantSpecificationOfTypeArguments\" value=\"ignore\"/>\n" + 
1863
			"		<option key=\"org.eclipse.jdt.core.compiler.problem.redundantSuperinterface\" value=\"ignore\"/>\n" + 
1918
			"		<option key=\"org.eclipse.jdt.core.compiler.problem.redundantSuperinterface\" value=\"ignore\"/>\n" + 
Lines 1870-1877 Link Here
1870
			"		<option key=\"org.eclipse.jdt.core.compiler.problem.syntheticAccessEmulation\" value=\"ignore\"/>\n" + 
1925
			"		<option key=\"org.eclipse.jdt.core.compiler.problem.syntheticAccessEmulation\" value=\"ignore\"/>\n" + 
1871
			"		<option key=\"org.eclipse.jdt.core.compiler.problem.tasks\" value=\"warning\"/>\n" + 
1926
			"		<option key=\"org.eclipse.jdt.core.compiler.problem.tasks\" value=\"warning\"/>\n" + 
1872
			"		<option key=\"org.eclipse.jdt.core.compiler.problem.typeParameterHiding\" value=\"warning\"/>\n" + 
1927
			"		<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" +
1928
			"		<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" + 
1929
			"		<option key=\"org.eclipse.jdt.core.compiler.problem.uncheckedTypeOperation\" value=\"warning\"/>\n" + 
1930
			"		<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" + 
1931
			"		<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" + 
1932
			"		<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" + 
1933
			"		<option key=\"org.eclipse.jdt.core.compiler.problem.unnecessaryElse\" value=\"ignore\"/>\n" + 
Lines 1897-1903 Link Here
1897
			"		<option key=\"org.eclipse.jdt.core.compiler.source\" value=\"1.5\"/>\n" + 
1953
			"		<option key=\"org.eclipse.jdt.core.compiler.source\" value=\"1.5\"/>\n" + 
1898
			"		<option key=\"org.eclipse.jdt.core.compiler.taskCaseSensitive\" value=\"enabled\"/>\n" + 
1954
			"		<option key=\"org.eclipse.jdt.core.compiler.taskCaseSensitive\" value=\"enabled\"/>\n" + 
1899
			"		<option key=\"org.eclipse.jdt.core.compiler.taskPriorities\" value=\"\"/>\n" + 
1955
			"		<option key=\"org.eclipse.jdt.core.compiler.taskPriorities\" value=\"\"/>\n" + 
1900
			"		<option key=\"org.eclipse.jdt.core.compiler.taskTags\" value=\"\"/>\n" + 
1956
			"		<option key=\"org.eclipse.jdt.core.compiler.taskTags\" value=\"\"/>\n" +
1901
			"	</options>\n" + 
1957
			"	</options>\n" + 
1902
			"	<classpaths>NORMALIZED SECTION</classpaths>\n" + 
1958
			"	<classpaths>NORMALIZED SECTION</classpaths>\n" + 
1903
			"	<sources>\n" + 
1959
			"	<sources>\n" + 
Lines 6872-6878 Link Here
6872
		"3. WARNING in ---OUTPUT_DIR_PLACEHOLDER---/X.java (at line 13)\n" +
6928
		"3. WARNING in ---OUTPUT_DIR_PLACEHOLDER---/X.java (at line 13)\n" +
6873
		"	} catch (E1 e1) {\n" +
6929
		"	} catch (E1 e1) {\n" +
6874
		"	         ^^\n" +
6930
		"	         ^^\n" +
6875
		"Unreachable catch block for E1. Only more specific exceptions are thrown and handled by previous catch block(s).\n" +
6931
		"Unreachable catch block for E1. Only more specific exceptions are thrown and they are handled by previous catch block(s).\n" +
6876
		"----------\n" +
6932
		"----------\n" +
6877
		"3 problems (3 warnings)",
6933
		"3 problems (3 warnings)",
6878
		true);
6934
		true);
Lines 6940-6946 Link Here
6940
		"4. WARNING in ---OUTPUT_DIR_PLACEHOLDER---/X.java (at line 13)\n" +
6996
		"4. WARNING in ---OUTPUT_DIR_PLACEHOLDER---/X.java (at line 13)\n" +
6941
		"	} catch (E1 e1) {\n" +
6997
		"	} catch (E1 e1) {\n" +
6942
		"	         ^^\n" +
6998
		"	         ^^\n" +
6943
		"Unreachable catch block for E1. Only more specific exceptions are thrown and handled by previous catch block(s).\n" +
6999
		"Unreachable catch block for E1. Only more specific exceptions are thrown and they are handled by previous catch block(s).\n" +
6944
		"----------\n" +
7000
		"----------\n" +
6945
		"4 problems (4 warnings)",
7001
		"4 problems (4 warnings)",
6946
		true);
7002
		true);
Lines 7075-7081 Link Here
7075
		"1. WARNING in ---OUTPUT_DIR_PLACEHOLDER---/X.java (at line 13)\n" +
7131
		"1. WARNING in ---OUTPUT_DIR_PLACEHOLDER---/X.java (at line 13)\n" +
7076
		"	} catch (E1 e1) {\n" +
7132
		"	} catch (E1 e1) {\n" +
7077
		"	         ^^\n" +
7133
		"	         ^^\n" +
7078
		"Unreachable catch block for E1. Only more specific exceptions are thrown and handled by previous catch block(s).\n" +
7134
		"Unreachable catch block for E1. Only more specific exceptions are thrown and they are handled by previous catch block(s).\n" +
7079
		"----------\n" +
7135
		"----------\n" +
7080
		"1 problem (1 warning)",
7136
		"1 problem (1 warning)",
7081
		true);
7137
		true);
Lines 7175-7181 Link Here
7175
		"3. WARNING in ---OUTPUT_DIR_PLACEHOLDER---/X.java (at line 13)\n" +
7231
		"3. WARNING in ---OUTPUT_DIR_PLACEHOLDER---/X.java (at line 13)\n" +
7176
		"	} catch (E1 e1) {\n" +
7232
		"	} catch (E1 e1) {\n" +
7177
		"	         ^^\n" +
7233
		"	         ^^\n" +
7178
		"Unreachable catch block for E1. Only more specific exceptions are thrown and handled by previous catch block(s).\n" +
7234
		"Unreachable catch block for E1. Only more specific exceptions are thrown and they are handled by previous catch block(s).\n" +
7179
		"----------\n" +
7235
		"----------\n" +
7180
		"3 problems (3 warnings)",
7236
		"3 problems (3 warnings)",
7181
		true);
7237
		true);
Lines 7230-7236 Link Here
7230
		"3. WARNING in ---OUTPUT_DIR_PLACEHOLDER---/X.java (at line 13)\n" +
7286
		"3. WARNING in ---OUTPUT_DIR_PLACEHOLDER---/X.java (at line 13)\n" +
7231
		"	} catch (E1 e1) {\n" +
7287
		"	} catch (E1 e1) {\n" +
7232
		"	         ^^\n" +
7288
		"	         ^^\n" +
7233
		"Unreachable catch block for E1. Only more specific exceptions are thrown and handled by previous catch block(s).\n" +
7289
		"Unreachable catch block for E1. Only more specific exceptions are thrown and they are handled by previous catch block(s).\n" +
7234
		"----------\n" +
7290
		"----------\n" +
7235
		"3 problems (3 warnings)",
7291
		"3 problems (3 warnings)",
7236
		true);
7292
		true);
Lines 7340-7346 Link Here
7340
		"3. WARNING in ---OUTPUT_DIR_PLACEHOLDER---/X.java (at line 13)\n" +
7396
		"3. WARNING in ---OUTPUT_DIR_PLACEHOLDER---/X.java (at line 13)\n" +
7341
		"	} catch (E1 e1) {\n" +
7397
		"	} catch (E1 e1) {\n" +
7342
		"	         ^^\n" +
7398
		"	         ^^\n" +
7343
		"Unreachable catch block for E1. Only more specific exceptions are thrown and handled by previous catch block(s).\n" +
7399
		"Unreachable catch block for E1. Only more specific exceptions are thrown and they are handled by previous catch block(s).\n" +
7344
		"----------\n" +
7400
		"----------\n" +
7345
		"3 problems (3 warnings)",
7401
		"3 problems (3 warnings)",
7346
		true);
7402
		true);
Lines 8508-8555 Link Here
8508
		"The value of the parameter i is not used\n" +
8564
		"The value of the parameter i is not used\n" +
8509
		"----------\n" +
8565
		"----------\n" +
8510
		"1 problem (1 warning)",
8566
		"1 problem (1 warning)",
8511
		true);
8512
}
8513
// https://bugs.eclipse.org/bugs/show_bug.cgi?id=210518
8514
// variant
8515
public void test214_warn_options() {
8516
	// same source as 153, skip default checks
8517
	this.runNegativeTest(
8518
		new String[] {
8519
			"X.java",
8520
			"public class X {\n" +
8521
			"	public static void foo() {\n" +
8522
			"     String s = null;\n" +
8523
			"     s.toString();\n" +
8524
			"     String u;\n" +
8525
			"   }\n" +
8526
			"}",
8527
		},
8528
		"\"" + OUTPUT_DIR +  File.separator + "X.java\""
8529
		+ " -warn:null,-unused -proc:none -d \"" + OUTPUT_DIR + "\"",
8530
		"",
8531
		"usage of \'-\' for \'-unused\' is illegal there\n",
8532
		true);
8533
}
8534
// https://bugs.eclipse.org/bugs/show_bug.cgi?id=210518
8535
// variant
8536
public void test215_warn_options() {
8537
	// same source as 153, skip default checks
8538
	this.runNegativeTest(
8539
		new String[] {
8540
			"X.java",
8541
			"public class X {\n" +
8542
			"	public static void foo() {\n" +
8543
			"     String s = null;\n" +
8544
			"     s.toString();\n" +
8545
			"     String u;\n" +
8546
			"   }\n" +
8547
			"}",
8548
		},
8549
		"\"" + OUTPUT_DIR +  File.separator + "X.java\""
8550
		+ " -warn:null,+unused -proc:none -d \"" + OUTPUT_DIR + "\"",
8551
		"",
8552
		"usage of \'+\' for \'+unused\' is illegal there\n",
8553
		true);
8567
		true);
8554
}
8568
}
8555
// https://bugs.eclipse.org/bugs/show_bug.cgi?id=211588
8569
// https://bugs.eclipse.org/bugs/show_bug.cgi?id=211588
Lines 11398-11421 Link Here
11398
		true);
11412
		true);
11399
}
11413
}
11400
//https://bugs.eclipse.org/bugs/show_bug.cgi?id=280784
11414
//https://bugs.eclipse.org/bugs/show_bug.cgi?id=280784
11401
public void test295(){
11402
	this.runNegativeTest(
11403
		new String[] {
11404
			"src/X.java",
11405
			"public class X {\n" +
11406
			"}",
11407
		},
11408
		"\"" + OUTPUT_DIR +  File.separator + "src/X.java\""
11409
		+ " -cp \"" + LIB_DIR + "\""
11410
		+ " -sourcepath \"" + OUTPUT_DIR +  File.separator + "src\""
11411
		+ " -1.5 -g -preserveAllLocals"
11412
		+ " -proceedOnError -referenceInfo -err:raw,+discouraged"
11413
		+ " -d \"" + OUTPUT_DIR + File.separator + "bin\" ",
11414
		"",
11415
		"usage of \'+\' for \'+discouraged\' is illegal there\n",
11416
		true);
11417
}
11418
//https://bugs.eclipse.org/bugs/show_bug.cgi?id=280784
11419
public void test296(){
11415
public void test296(){
11420
	this.runNegativeTest(
11416
	this.runNegativeTest(
11421
		new String[] {
11417
		new String[] {
Lines 12295-12298 Link Here
12295
		"3 problems (1 error, 2 warnings)",
12291
		"3 problems (1 error, 2 warnings)",
12296
		true);
12292
		true);
12297
}
12293
}
12294
//-warn option - regression tests
12295
public void test0308_warn_options() {
12296
	// check the option introduced in bug 359721
12297
	this.runConformTest(
12298
		new String[] {
12299
			"X.java",
12300
			"import java.io.FileReader;\n" +
12301
			"public class X {\n" +
12302
			"  void foo() throws java.io.IOException {\n" +
12303
			"      FileReader r = new FileReader(\"f1\");\n" +
12304
			"      char[] cs = new char[1024];\n" +
12305
			"	   r.read(cs);\n" +
12306
			"  }\n" +
12307
			"}\n"
12308
		},
12309
		"\"" + OUTPUT_DIR +  File.separator + "X.java\""
12310
		+ " -warn:-resource -1.7 -d \"" + OUTPUT_DIR + "\"",
12311
		"",
12312
		"",
12313
		true);
12314
}
12315
//-warn option - regression tests
12316
public void test0309_warn_options() {
12317
	// check the option introduced in bug 359721
12318
	this.runConformTest(
12319
		new String[] {
12320
			"X.java",
12321
			"import java.io.FileReader;\n" +
12322
			"public class X {\n" +
12323
			"  void foo(boolean b) throws java.io.IOException {\n" +
12324
			"      FileReader r = new FileReader(\"f1\");\n" +
12325
			"      char[] cs = new char[1024];\n" +
12326
			"	   r.read(cs);\n" +
12327
			"      if (b) r.close();\n" +
12328
			"  }\n" +
12329
			"}\n"
12330
		},
12331
		"\"" + OUTPUT_DIR +  File.separator + "X.java\""
12332
		+ " -warn:+resource -1.7 -d \"" + OUTPUT_DIR + "\"",
12333
		"",
12334
		"----------\n" + 
12335
		"1. WARNING in ---OUTPUT_DIR_PLACEHOLDER---/X.java (at line 4)\n" + 
12336
		"	FileReader r = new FileReader(\"f1\");\n" + 
12337
		"	           ^\n" + 
12338
		"Potential resource leak: \'r\' may not be closed\n" + 
12339
		"----------\n" + 
12340
		"1 problem (1 warning)",
12341
		true);
12342
}
12343
12344
// https://bugs.eclipse.org/bugs/show_bug.cgi?id=366829
12345
// -warn option - regression test to check option syncOverride
12346
// Warning when when a class overrides a synchronized method without synchronizing it
12347
public void test310_warn_options() {
12348
	this.runConformTest(
12349
		new String[] {
12350
			"X.java",
12351
			"class X { synchronized void foo() {} }\n" +
12352
			"class Y extends X { @Override void foo() { } }"
12353
		},
12354
		"\"" + OUTPUT_DIR +  File.separator + "X.java\""
12355
		+ " -sourcepath \"" + OUTPUT_DIR + "\""
12356
		+ " -warn:syncOverride -1.5 -proc:none -d \"" + OUTPUT_DIR + "\"",
12357
		"",
12358
		"----------\n" + 
12359
		"1. WARNING in ---OUTPUT_DIR_PLACEHOLDER---/X.java (at line 2)\n" + 
12360
		"	class Y extends X { @Override void foo() { } }\n" +
12361
		"	                                   ^^^^^\n" +
12362
		"The method Y.foo() is overriding a synchronized method without being synchronized\n" +
12363
		"----------\n" +
12364
		"1 problem (1 warning)", 
12365
		true);
12366
}
12367
12368
// https://bugs.eclipse.org/bugs/show_bug.cgi?id=366829
12369
// -warn option - regression test to check option syncOverride
12370
// Warning when when a class overrides a synchronized method without synchronizing it
12371
public void test310b_warn_options() {
12372
	this.runConformTest(
12373
		new String[] {
12374
				"X.java",
12375
				"public class X {\n" + 
12376
				"  void bar() { new X() { @Override void foo() {} }; }\n"+
12377
				"  synchronized void foo() { }\n"+
12378
				"}"
12379
		},
12380
		"\"" + OUTPUT_DIR +  File.separator + "X.java\""
12381
		+ " -sourcepath \"" + OUTPUT_DIR + "\""
12382
		+ " -warn:syncOverride -1.5 -proc:none -d \"" + OUTPUT_DIR + "\"",
12383
		"",
12384
		"----------\n" + 
12385
		"1. WARNING in ---OUTPUT_DIR_PLACEHOLDER---/X.java (at line 2)\n" + 
12386
		"	void bar() { new X() { @Override void foo() {} }; }\n"+
12387
		"	                                      ^^^^^\n" +
12388
		"The method new X(){}.foo() is overriding a synchronized method without being synchronized\n" +
12389
		"----------\n" +
12390
		"1 problem (1 warning)", 
12391
		true);
12392
}
12393
12394
// https://bugs.eclipse.org/bugs/show_bug.cgi?id=325342
12395
// -warn option - regression tests to check option nullAnnot (with args)
12396
// Null warnings because of annotations - custom annotation types used - challenging various kinds of diagnostics
12397
public void test312_warn_options() {
12398
	this.runConformTest(
12399
		new String[] {
12400
				"p/X.java",
12401
				"package p;\n" +
12402
				"import static java.lang.annotation.ElementType.*;\n" +
12403
				"import java.lang.annotation.*;\n" +
12404
				"@SuppressWarnings(\"unused\")\n" +
12405
				"public class X {\n" +
12406
				"	public void test() { Object o = null; o.toString();}\n" +
12407
				"  @NonNull Object foo(@Nullable Object o, @NonNull Object o2) {\n" +
12408
				"    if (o.toString() == \"\"){ return null;}\n" +
12409
				"    if (o2 == null) {}\n" +
12410
				"    goo(null).toString();\n" +
12411
				"	 Object local = null;\n" +
12412
				"	 o.toString();\n" +
12413
				"	 return null;\n" +
12414
				"  }\n" +
12415
				"  @Nullable Object goo(@NonNull Object o2) {\n" +
12416
				"    return new Object();\n" +
12417
				"  }\n" +
12418
				"  @NonNullByDefault Object hoo(Object o2) {\n" +
12419
				"    if (o2 == null){}\n" +
12420
				"    if (o2 == null){\n" +
12421
				"	    return null;\n" +
12422
				"	 }\n" +
12423
				"	 return new Object();\n" +
12424
				"  }\n" +
12425
				"}\n" +
12426
				"@Documented\n" +
12427
				"@Retention(RetentionPolicy.CLASS)\n" +
12428
				"@Target({ METHOD, PARAMETER })\n" +
12429
				"@interface NonNull{\n" +
12430
				"}\n" +
12431
				"@Documented\n" +
12432
				"@Retention(RetentionPolicy.CLASS)\n" +
12433
				"@Target({ METHOD, PARAMETER })\n" +
12434
				"@interface Nullable{\n" +
12435
				"}\n" +
12436
				"@Documented\n" +
12437
				"@Retention(RetentionPolicy.CLASS)\n" +
12438
				"@Target({ PACKAGE, TYPE, METHOD, CONSTRUCTOR })\n" +
12439
				"@interface NonNullByDefault{\n" +
12440
				"}"
12441
		},
12442
		"\"" + OUTPUT_DIR +  File.separator + "p" + File.separator + "X.java\""
12443
//		+ " -sourcepath \"" + OUTPUT_DIR + "\""
12444
		+ " -1.5"
12445
		+ " -warn:+nullAnnot(p.Nullable|p.NonNull|p.NonNullByDefault) -warn:+null -proc:none -d \"" + OUTPUT_DIR + "\"",
12446
		"",
12447
		"----------\n" + 
12448
		"1. WARNING in ---OUTPUT_DIR_PLACEHOLDER---/p/X.java (at line 6)\n" + 
12449
		"	public void test() { Object o = null; o.toString();}\n" + 
12450
		"	                                      ^\n" + 
12451
		"Null pointer access: The variable o can only be null at this location\n" + 
12452
		"----------\n" + 
12453
		"2. WARNING in ---OUTPUT_DIR_PLACEHOLDER---/p/X.java (at line 8)\n" + 
12454
		"	if (o.toString() == \"\"){ return null;}\n" + 
12455
		"	    ^\n" + 
12456
		"Potential null pointer access: The variable o may be null at this location\n" + 
12457
		"----------\n" + 
12458
		"3. WARNING in ---OUTPUT_DIR_PLACEHOLDER---/p/X.java (at line 8)\n" + 
12459
		"	if (o.toString() == \"\"){ return null;}\n" + 
12460
		"	                                ^^^^\n" + 
12461
		"Type mismatch: required \'@NonNull Object\' but the provided value is null\n" + 
12462
		"----------\n" + 
12463
		"4. WARNING in ---OUTPUT_DIR_PLACEHOLDER---/p/X.java (at line 9)\n" + 
12464
		"	if (o2 == null) {}\n" + 
12465
		"	    ^^\n" + 
12466
		"Null comparison always yields false: The variable o2 cannot be null at this location\n" + 
12467
		"----------\n" + 
12468
		"5. WARNING in ---OUTPUT_DIR_PLACEHOLDER---/p/X.java (at line 10)\n" + 
12469
		"	goo(null).toString();\n" + 
12470
		"	^^^^^^^^^\n" + 
12471
		"Potential null pointer access: The method goo(Object) may return null\n" + 
12472
		"----------\n" + 
12473
		"6. WARNING in ---OUTPUT_DIR_PLACEHOLDER---/p/X.java (at line 10)\n" + 
12474
		"	goo(null).toString();\n" + 
12475
		"	    ^^^^\n" + 
12476
		"Type mismatch: required \'@NonNull Object\' but the provided value is null\n" + 
12477
		"----------\n" + 
12478
		"7. WARNING in ---OUTPUT_DIR_PLACEHOLDER---/p/X.java (at line 13)\n" + 
12479
		"	return null;\n" + 
12480
		"	       ^^^^\n" + 
12481
		"Type mismatch: required \'@NonNull Object\' but the provided value is null\n" + 
12482
		"----------\n" + 
12483
		"8. WARNING in ---OUTPUT_DIR_PLACEHOLDER---/p/X.java (at line 19)\n" + 
12484
		"	if (o2 == null){}\n" + 
12485
		"	    ^^\n" + 
12486
		"Null comparison always yields false: The variable o2 cannot be null at this location\n" + 
12487
		"----------\n" + 
12488
		"9. WARNING in ---OUTPUT_DIR_PLACEHOLDER---/p/X.java (at line 20)\n" + 
12489
		"	if (o2 == null){\n" + 
12490
		"	    ^^\n" + 
12491
		"Null comparison always yields false: The variable o2 cannot be null at this location\n" + 
12492
		"----------\n" + 
12493
		"9 problems (9 warnings)", 
12494
		true);
12495
}
12496
12497
// https://bugs.eclipse.org/bugs/show_bug.cgi?id=325342
12498
// -warn option - regression tests to check option nullAnnot (no args)
12499
// Null warnings because of annotations, null spec violations
12500
public void test313_warn_options() {
12501
	this.runConformTest(
12502
		new String[] {
12503
				"p/X.java",
12504
				"package p;\n" +
12505
				"import org.eclipse.jdt.annotation.*;\n" +
12506
				"public class X {\n" +
12507
				"  @NonNull Object foo(@Nullable Object o, @NonNull Object o2) {\n" +
12508
				"	 return this;\n" +
12509
				"  }\n" +
12510
				"}\n" +
12511
				"class Y extends X {\n" +
12512
				"    @Nullable Object foo(Object o, Object o2) { return null; }\n" +
12513
				"}\n",
12514
				"org/eclipse/jdt/annotation/NonNull.java",
12515
				NONNULL_ANNOTATION_CONTENT,
12516
				"org/eclipse/jdt/annotation/Nullable.java",
12517
				NULLABLE_ANNOTATION_CONTENT,
12518
				"org/eclipse/jdt/annotation/NonNullByDefault.java",				
12519
				NONNULL_BY_DEFAULT_ANNOTATION_CONTENT
12520
		},
12521
		"\"" + OUTPUT_DIR +  File.separator + "p" + File.separator + "X.java\""
12522
		+ " -sourcepath \"" + OUTPUT_DIR + "\""
12523
		+ " -1.5"
12524
		+ " -warn:+nullAnnot -warn:-null -proc:none -d \"" + OUTPUT_DIR + "\"",
12525
		"",
12526
		"----------\n" + 
12527
		"1. WARNING in ---OUTPUT_DIR_PLACEHOLDER---/p/X.java (at line 9)\n" + 
12528
		"	@Nullable Object foo(Object o, Object o2) { return null; }\n" + 
12529
		"	^^^^^^^^^^^^^^^^\n" + 
12530
		"The return type is incompatible with the @NonNull return from X.foo(Object, Object)\n" + 
12531
		"----------\n" + 
12532
		"2. WARNING in ---OUTPUT_DIR_PLACEHOLDER---/p/X.java (at line 9)\n" + 
12533
		"	@Nullable Object foo(Object o, Object o2) { return null; }\n" + 
12534
		"	                     ^^^^^^\n" + 
12535
		"Missing nullable annotation: inherited method from X declares this parameter as @Nullable\n" + 
12536
		"----------\n" + 
12537
		"3. WARNING in ---OUTPUT_DIR_PLACEHOLDER---/p/X.java (at line 9)\n" + 
12538
		"	@Nullable Object foo(Object o, Object o2) { return null; }\n" + 
12539
		"	                               ^^^^^^\n" + 
12540
		"Missing non-null annotation: inherited method from X declares this parameter as @NonNull\n" + 
12541
		"----------\n" + 
12542
		"3 problems (3 warnings)", 
12543
		true);
12544
}
12545
12546
// https://bugs.eclipse.org/bugs/show_bug.cgi?id=325342
12547
// -err option - regression tests to check option nullAnnot
12548
// Null warnings because of annotations, null spec violations configured as errors
12549
public void test314_warn_options() {
12550
	this.runNegativeTest(
12551
		new String[] {
12552
				"p/X.java",
12553
				"package p;\n" +
12554
				"import org.eclipse.jdt.annotation.*;\n" +
12555
				"public class X {\n" +
12556
				"  @NonNull Object foo(@Nullable Object o, @NonNull Object o2) {\n" +
12557
				"	 return this;\n" +
12558
				"  }\n" +
12559
				"}\n" +
12560
				"class Y extends X {\n" +
12561
				"    @Nullable Object foo(Object o, Object o2) { return null; }\n" +
12562
				"}\n",
12563
				"org/eclipse/jdt/annotation/NonNull.java",
12564
				NONNULL_ANNOTATION_CONTENT,
12565
				"org/eclipse/jdt/annotation/Nullable.java",
12566
				NULLABLE_ANNOTATION_CONTENT,
12567
				"org/eclipse/jdt/annotation/NonNullByDefault.java",				
12568
				NONNULL_BY_DEFAULT_ANNOTATION_CONTENT
12569
		},
12570
		"\"" + OUTPUT_DIR +  File.separator + "p" + File.separator + "X.java\""
12571
		+ " -sourcepath \"" + OUTPUT_DIR + "\""
12572
		+ " -1.5"
12573
		+ " -err:+nullAnnot -warn:-null -proc:none -d \"" + OUTPUT_DIR + "\"",
12574
		"",
12575
		"----------\n" + 
12576
		"1. ERROR in ---OUTPUT_DIR_PLACEHOLDER---/p/X.java (at line 9)\n" + 
12577
		"	@Nullable Object foo(Object o, Object o2) { return null; }\n" + 
12578
		"	^^^^^^^^^^^^^^^^\n" + 
12579
		"The return type is incompatible with the @NonNull return from X.foo(Object, Object)\n" + 
12580
		"----------\n" + 
12581
		"2. ERROR in ---OUTPUT_DIR_PLACEHOLDER---/p/X.java (at line 9)\n" + 
12582
		"	@Nullable Object foo(Object o, Object o2) { return null; }\n" + 
12583
		"	                     ^^^^^^\n" + 
12584
		"Missing nullable annotation: inherited method from X declares this parameter as @Nullable\n" + 
12585
		"----------\n" + 
12586
		"3. ERROR in ---OUTPUT_DIR_PLACEHOLDER---/p/X.java (at line 9)\n" + 
12587
		"	@Nullable Object foo(Object o, Object o2) { return null; }\n" + 
12588
		"	                               ^^^^^^\n" + 
12589
		"Missing non-null annotation: inherited method from X declares this parameter as @NonNull\n" + 
12590
		"----------\n" + 
12591
		"3 problems (3 errors)", 
12592
		true);
12593
}
12594
12595
// https://bugs.eclipse.org/bugs/show_bug.cgi?id=325342
12596
// -warn option - regression tests to check option nullAnnot
12597
// Null warnings because of annotations, global nonNullByDefault
12598
// DISABLED due to dysfunctional global default after Bug 366063 - Compiler should not add synthetic @NonNull annotations
12599
public void _test315_warn_options() {
12600
	this.runConformTest(
12601
		new String[] {
12602
				"p/X.java",
12603
				"package p;\n" +
12604
				"import org.eclipse.jdt.annotation.*;\n" +
12605
				"@SuppressWarnings(\"unused\")\n" +
12606
				"public class X {\n" +
12607
				"  Object foo(@Nullable Object o, Object o2) {\n" +
12608
				"    if (o.toString() == \"\"){ return null;}\n" +
12609
				"    if (o2 == null) {}\n" +
12610
				"    goo(null).toString();\n" +
12611
				"	 return null;\n" +
12612
				"  }\n" +
12613
				"  @Nullable Object goo(Object o2) {\n" +
12614
				"    return new Object();\n" +
12615
				"  }\n" +
12616
				"  @NonNullByDefault Object hoo(Object o2) {\n" + // redundant
12617
				"    if (o2 == null)\n" +
12618
				"	    return null;\n" +
12619
				"    return this;\n" +
12620
				"  }\n" +
12621
				"}\n",
12622
				"org/eclipse/jdt/annotation/NonNull.java",
12623
				NONNULL_ANNOTATION_CONTENT,
12624
				"org/eclipse/jdt/annotation/Nullable.java",
12625
				NULLABLE_ANNOTATION_CONTENT,
12626
				"org/eclipse/jdt/annotation/NonNullByDefault.java",				
12627
				NONNULL_BY_DEFAULT_ANNOTATION_CONTENT
12628
		},
12629
		"\"" + OUTPUT_DIR +  File.separator + "p" + File.separator + "X.java\""
12630
		+ " -sourcepath \"" + OUTPUT_DIR + "\""
12631
		+ " -1.5"
12632
		+ " -warn:+nullAnnot -warn:+null -nonNullByDefault -proc:none -d \"" + OUTPUT_DIR + "\"",
12633
		"",
12634
		"----------\n" + 
12635
		"1. WARNING in ---OUTPUT_DIR_PLACEHOLDER---/p/X.java (at line 6)\n" + 
12636
		"	if (o.toString() == \"\"){ return null;}\n" + 
12637
		"	    ^\n" + 
12638
		"Potential null pointer access: The variable o may be null at this location\n" + 
12639
		"----------\n" + 
12640
		"2. WARNING in ---OUTPUT_DIR_PLACEHOLDER---/p/X.java (at line 6)\n" + 
12641
		"	if (o.toString() == \"\"){ return null;}\n" + 
12642
		"	                                ^^^^\n" + 
12643
		"Type mismatch: required \'@NonNull Object\' but the provided value is null\n" + 
12644
		"----------\n" + 
12645
		"3. WARNING in ---OUTPUT_DIR_PLACEHOLDER---/p/X.java (at line 7)\n" + 
12646
		"	if (o2 == null) {}\n" + 
12647
		"	    ^^\n" + 
12648
		"Null comparison always yields false: The variable o2 cannot be null at this location\n" + 
12649
		"----------\n" + 
12650
		"4. WARNING in ---OUTPUT_DIR_PLACEHOLDER---/p/X.java (at line 8)\n" + 
12651
		"	goo(null).toString();\n" + 
12652
		"	^^^^^^^^^\n" + 
12653
		"Potential null pointer access: The method goo(Object) may return null\n" + 
12654
		"----------\n" + 
12655
		"5. WARNING in ---OUTPUT_DIR_PLACEHOLDER---/p/X.java (at line 8)\n" + 
12656
		"	goo(null).toString();\n" + 
12657
		"	    ^^^^\n" + 
12658
		"Type mismatch: required \'@NonNull Object\' but the provided value is null\n" + 
12659
		"----------\n" + 
12660
		"6. WARNING in ---OUTPUT_DIR_PLACEHOLDER---/p/X.java (at line 9)\n" + 
12661
		"	return null;\n" + 
12662
		"	       ^^^^\n" + 
12663
		"Type mismatch: required \'@NonNull Object\' but the provided value is null\n" + 
12664
		"----------\n" + 
12665
		"7. WARNING in ---OUTPUT_DIR_PLACEHOLDER---/p/X.java (at line 14)\n" + 
12666
		"	@NonNullByDefault Object hoo(Object o2) {\n" + 
12667
		"	^^^^^^^^^^^^^^^^^\n" + 
12668
		"Nullness default is redundant with the global default\n" + 
12669
		"----------\n" + 
12670
		"8. WARNING in ---OUTPUT_DIR_PLACEHOLDER---/p/X.java (at line 15)\n" + 
12671
		"	if (o2 == null)\n" + 
12672
		"	    ^^\n" + 
12673
		"Null comparison always yields false: The variable o2 cannot be null at this location\n" + 
12674
		"----------\n" + 
12675
		"8 problems (8 warnings)", 
12676
		true);
12677
}
12678
12679
// https://bugs.eclipse.org/bugs/show_bug.cgi?id=325342
12680
// -warn option - regression tests to check option nullAnnot
12681
// option syntax error
12682
public void test316_warn_options() {
12683
	this.runNegativeTest(
12684
		new String[] {
12685
				"p/X.java",
12686
				"package p;\n" +
12687
				"import org.eclipse.jdt.annotation.*;\n" +
12688
				"@SuppressWarnings(\"unused\")\n" +
12689
				"public class X {}\n",
12690
				"org/eclipse/jdt/annotation/NonNull.java",
12691
				NONNULL_ANNOTATION_CONTENT,
12692
				"org/eclipse/jdt/annotation/Nullable.java",
12693
				NULLABLE_ANNOTATION_CONTENT,
12694
				"org/eclipse/jdt/annotation/NonNullByDefault.java",				
12695
				NONNULL_BY_DEFAULT_ANNOTATION_CONTENT
12696
		},
12697
		"\"" + OUTPUT_DIR +  File.separator + "p" + File.separator + "X.java\""
12698
		+ " -sourcepath \"" + OUTPUT_DIR + "\""
12699
		+ " -1.5"
12700
		+ " -warn:+nullAnnot(foo|bar) -warn:+null -nonNullByDefault -proc:none -d \"" + OUTPUT_DIR + "\"",
12701
		"",
12702
		"Token nullAnnot(foo|bar) is not in the expected format \"nullAnnot(<non null annotation name> | <nullable annotation name> | <non-null by default annotation name>)\"\n", 
12703
		true);
12704
}
12705
12706
//https://bugs.eclipse.org/bugs/show_bug.cgi?id=220928
12707
//-nowarn option - regression tests
12708
//default
12709
public void test317_nowarn_options() {
12710
	this.runConformTest(
12711
		new String[] {
12712
				"src/X.java",
12713
				"public class X {\n" +
12714
				"  /**\n" +
12715
				"    @param\n" +
12716
				"  */\n" +
12717
				"  public void foo() {\n" +
12718
				"  }\n" +
12719
				"}",
12720
			},
12721
			"\"" + OUTPUT_DIR + File.separator + "src/X.java\""
12722
			+ " -warn:javadoc -nowarn:[\"" +
12723
			OUTPUT_DIR + File.separator + "src" + 
12724
			"\"] -proc:none -d \"" + OUTPUT_DIR + "\"",
12725
			"",
12726
			"",
12727
			true);
12728
}
12729
12730
//https://bugs.eclipse.org/bugs/show_bug.cgi?id=220928
12731
//-nowarn option - regression tests
12732
//two different source folders ignore only from one
12733
public void test318_nowarn_options() {
12734
	this.runConformTest(
12735
		new String[] {
12736
				"src/X.java",
12737
				"public class X {\n" +
12738
				"  /**\n" +
12739
				"    @param\n" +
12740
				"  */\n" +
12741
				"  public void foo() {\n" +
12742
				"  }\n" +
12743
				"}",
12744
				"src2/Y.java",
12745
				"public class Y {\n" +
12746
				"  /**\n" +
12747
				"    @param\n" +
12748
				"  */\n" +
12749
				"  public void foo() {\n" +
12750
				"  }\n" +
12751
				"}"
12752
			},
12753
			"\"" + OUTPUT_DIR + File.separator + "src/X.java\"" +
12754
			" \"" + OUTPUT_DIR + File.separator + "src2/Y.java\"" +
12755
			" -warn:javadoc -nowarn:[" +
12756
			"\"" + OUTPUT_DIR + File.separator + "src"
12757
			+ "\"] -proc:none -d \"" + OUTPUT_DIR + "\"",
12758
			"",
12759
			"----------\n" +
12760
			"1. WARNING in ---OUTPUT_DIR_PLACEHOLDER---/src2/Y.java (at line 3)\n" +
12761
			"	@param\n" +
12762
			"	 ^^^^^\n" +
12763
			"Javadoc: Missing parameter name\n" +
12764
			"----------\n" +
12765
			"1 problem (1 warning)",
12766
			true);
12767
}
12768
12769
//https://bugs.eclipse.org/bugs/show_bug.cgi?id=220928
12770
//-nowarn option - regression tests
12771
//two different source folders ignore from both
12772
public void test319_nowarn_options() {
12773
	this.runConformTest(
12774
		new String[] {
12775
				"src1/X.java",
12776
				"public class X {\n" +
12777
				"  /**\n" +
12778
				"    @param\n" +
12779
				"  */\n" +
12780
				"  public void foo() {\n" +
12781
				"  }\n" +
12782
				"}",
12783
				"src2/Y.java",
12784
				"public class Y {\n" +
12785
				"  /**\n" +
12786
				"    @param\n" +
12787
				"  */\n" +
12788
				"  public void foo() {\n" +
12789
				"  }\n" +
12790
				"}"
12791
			},
12792
			"\"" + OUTPUT_DIR + File.separator + "src1/X.java\"" +
12793
			" \"" + OUTPUT_DIR + File.separator + "src2/Y.java\"" +
12794
			" -warn:javadoc -nowarn:[" +
12795
			"\"" + OUTPUT_DIR + File.separator + "src1\"" + File.pathSeparator +
12796
			"\"" + OUTPUT_DIR + File.separator +
12797
			"src2\"] -proc:none -d \"" + OUTPUT_DIR + "\"",
12798
			"",
12799
			"",
12800
			true);
12801
}
12802
12803
//https://bugs.eclipse.org/bugs/show_bug.cgi?id=220928
12804
//-nowarn option - regression tests
12805
//two different source folders ignore from both using multiple -nowarn
12806
public void test320_nowarn_options() {
12807
	this.runConformTest(
12808
		new String[] {
12809
				"src1/X.java",
12810
				"public class X {\n" +
12811
				"  /**\n" +
12812
				"    @param\n" +
12813
				"  */\n" +
12814
				"  public void foo() {\n" +
12815
				"  }\n" +
12816
				"}",
12817
				"src2/Y.java",
12818
				"public class Y {\n" +
12819
				"  /**\n" +
12820
				"    @param\n" +
12821
				"  */\n" +
12822
				"  public void foo() {\n" +
12823
				"  }\n" +
12824
				"}"
12825
			},
12826
			"\"" + OUTPUT_DIR + File.separator + "src1/X.java\"" +
12827
			" \"" + OUTPUT_DIR + File.separator + "src2/Y.java\"" +
12828
			" -warn:javadoc -nowarn:[" +
12829
			"\"" + OUTPUT_DIR + File.separator + "src1\"] -nowarn:[" +
12830
			"\"" + OUTPUT_DIR + File.separator + "src2\"] " +
12831
			"-proc:none -d \"" + OUTPUT_DIR + "\"",
12832
			"",
12833
			"",
12834
			true);
12835
}
12836
12837
//https://bugs.eclipse.org/bugs/show_bug.cgi?id=220928
12838
//-nowarn option - regression tests
12839
//option syntax error -nowarn:
12840
public void test321_nowarn_options() {
12841
	this.runNegativeTest(
12842
		new String[] {
12843
				"src/X.java",
12844
				"public class X {\n" +
12845
				"  /**\n" +
12846
				"    @param\n" +
12847
				"  */\n" +
12848
				"  public void foo() {\n" +
12849
				"  }\n" +
12850
				"}",
12851
			},
12852
			"\"" + OUTPUT_DIR + File.separator + "src/X.java\""
12853
			+ " -warn:javadoc -nowarn: -proc:none -d \"" + OUTPUT_DIR + "\"",
12854
			"",
12855
			"invalid syntax for nowarn option: -nowarn:\n",
12856
			true);
12857
}
12858
12859
//https://bugs.eclipse.org/bugs/show_bug.cgi?id=220928
12860
//-nowarn option - regression tests
12861
//option syntax error -nowarn:[
12862
public void test322_nowarn_options() {
12863
	this.runNegativeTest(
12864
		new String[] {
12865
				"src/X.java",
12866
				"public class X {\n" +
12867
				"  /**\n" +
12868
				"    @param\n" +
12869
				"  */\n" +
12870
				"  public void foo() {\n" +
12871
				"  }\n" +
12872
				"}",
12873
			},
12874
			"\"" + OUTPUT_DIR + File.separator + "src/X.java\""
12875
			+ " -warn:javadoc -nowarn:[ -proc:none -d \"" + OUTPUT_DIR + "\"",
12876
			"",
12877
			"invalid syntax for nowarn option: -nowarn:[\n",
12878
			true);
12879
}
12880
12881
//https://bugs.eclipse.org/bugs/show_bug.cgi?id=220928
12882
//-nowarn option - regression tests
12883
//option syntax error -nowarn:[src
12884
public void test323_nowarn_options() {
12885
	this.runNegativeTest(
12886
		new String[] {
12887
				"src/X.java",
12888
				"public class X {\n" +
12889
				"  /**\n" +
12890
				"    @param\n" +
12891
				"  */\n" +
12892
				"  public void foo() {\n" +
12893
				"  }\n" +
12894
				"}",
12895
			},
12896
			"\"" + OUTPUT_DIR + File.separator + "src/X.java\""
12897
			+ " -warn:javadoc -nowarn:[src -proc:none -d \"" + OUTPUT_DIR + "\"",
12898
			"",
12899
			"invalid syntax for nowarn option: -nowarn:[src\n",
12900
			true);
12901
}
12902
12903
//https://bugs.eclipse.org/bugs/show_bug.cgi?id=220928
12904
//-nowarn option - regression tests
12905
//option syntax error -nowarn:src]
12906
public void test324_nowarn_options() {
12907
	this.runNegativeTest(
12908
		new String[] {
12909
				"src/X.java",
12910
				"public class X {\n" +
12911
				"  /**\n" +
12912
				"    @param\n" +
12913
				"  */\n" +
12914
				"  public void foo() {\n" +
12915
				"  }\n" +
12916
				"}",
12917
			},
12918
			"\"" + OUTPUT_DIR + File.separator + "src/X.java\""
12919
			+ " -warn:javadoc -nowarn:src] -proc:none -d \"" + OUTPUT_DIR + "\"",
12920
			"",
12921
			"invalid syntax for nowarn option: -nowarn:src]\n",
12922
			true);
12923
}
12924
12925
//https://bugs.eclipse.org/bugs/show_bug.cgi?id=220928
12926
//-nowarn option - regression tests
12927
//option syntax error -nowarn[src]
12928
public void test325_nowarn_options() {
12929
	this.runNegativeTest(
12930
		new String[] {
12931
				"src/X.java",
12932
				"public class X {\n" +
12933
				"  /**\n" +
12934
				"    @param\n" +
12935
				"  */\n" +
12936
				"  public void foo() {\n" +
12937
				"  }\n" +
12938
				"}",
12939
			},
12940
			"\"" + OUTPUT_DIR + File.separator + "src/X.java\""
12941
			+ " -warn:javadoc -nowarn[src] -proc:none -d \"" + OUTPUT_DIR + "\"",
12942
			"",
12943
			"invalid syntax for nowarn option: -nowarn[src]\n",
12944
			true);
12945
}
12946
12947
//https://bugs.eclipse.org/bugs/show_bug.cgi?id=220928
12948
//-nowarn option - regression tests
12949
//option syntax error -nowarn:[src1]src2
12950
public void test326_nowarn_options() {
12951
	this.runNegativeTest(
12952
		new String[] {
12953
				"src/X.java",
12954
				"public class X {\n" +
12955
				"  /**\n" +
12956
				"    @param\n" +
12957
				"  */\n" +
12958
				"  public void foo() {\n" +
12959
				"  }\n" +
12960
				"}",
12961
			},
12962
			"\"" + OUTPUT_DIR + File.separator + "src/X.java\""
12963
			+ " -warn:javadoc -nowarn:[src1]src2 -proc:none -d \"" + OUTPUT_DIR + "\"",
12964
			"",
12965
			"invalid syntax for nowarn option: -nowarn:[src1]src2\n",
12966
			true);
12967
}
12968
12969
//https://bugs.eclipse.org/bugs/show_bug.cgi?id=220928
12970
//-nowarn option - regression tests
12971
//option syntax error -nowarn:[]
12972
public void test327_nowarn_options() {
12973
	this.runNegativeTest(
12974
		new String[] {
12975
				"src/X.java",
12976
				"public class X {\n" +
12977
				"  /**\n" +
12978
				"    @param\n" +
12979
				"  */\n" +
12980
				"  public void foo() {\n" +
12981
				"  }\n" +
12982
				"}",
12983
			},
12984
			"\"" + OUTPUT_DIR + File.separator + "src/X.java\""
12985
			+ " -warn:javadoc -nowarn:[] -proc:none -d \"" + OUTPUT_DIR + "\"",
12986
			"",
12987
			"invalid syntax for nowarn option: -nowarn:[]\n",
12988
			true);
12989
}
12990
12991
//https://bugs.eclipse.org/bugs/show_bug.cgi?id=220928
12992
//-nowarn option - regression tests
12993
//non-optional errors cannot be ignored
12994
public void test328_nowarn_options() {
12995
	this.runNegativeTest(
12996
		new String[] {
12997
				"src/X.java",
12998
				"public class X {\n" +
12999
				"  /**\n" +
13000
				"    @param\n" +
13001
				"  */\n" +
13002
				"  public void foo() {\n" +
13003
				"    a++;\n" +
13004
				"  }\n" +
13005
				"}",
13006
			},
13007
			"\"" + OUTPUT_DIR + File.separator + "src/X.java\""
13008
			+ " -warn:javadoc -nowarn:[" +
13009
			"\"" + OUTPUT_DIR + File.separator + "src]\" -proc:none -d \"" + OUTPUT_DIR + "\"",
13010
			"",
13011
			"----------\n" +
13012
			"1. ERROR in ---OUTPUT_DIR_PLACEHOLDER---/src/X.java (at line 6)\n" +
13013
			"	a++;\n" +
13014
			"	^\n" +
13015
			"a cannot be resolved to a variable\n" +
13016
			"----------\n" +
13017
			"1 problem (1 error)",
13018
			true);
13019
}
13020
13021
//https://bugs.eclipse.org/bugs/show_bug.cgi?id=220928
13022
//-nowarn option - regression tests
13023
//task tags cannot be ignored
13024
public void test329_nowarn_options() {
13025
	this.runConformTest(
13026
		new String[] {
13027
				"src/X.java",
13028
				"public class X {\n" +
13029
				"  /**\n" +
13030
				"    @param\n" +
13031
				"  */\n" +
13032
				"  public void foo() {\n" +
13033
				"    // TODO nothing\n" +
13034
				"  }\n" +
13035
				"}",
13036
			},
13037
			"\"" + OUTPUT_DIR + File.separator + "src/X.java\""
13038
			+ " -warn:javadoc,tasks(TODO) -nowarn:[" +
13039
			"\"" + OUTPUT_DIR + File.separator + "src]\" -proc:none -d \"" + OUTPUT_DIR + "\"",
13040
			"",
13041
			"----------\n" +
13042
			"1. WARNING in ---OUTPUT_DIR_PLACEHOLDER---/src/X.java (at line 6)\n" +
13043
			"	// TODO nothing\n" +
13044
			"	   ^^^^^^^^^^^^\n" +
13045
			"TODO nothing\n" +
13046
			"----------\n" +
13047
			"1 problem (1 warning)",
13048
			true);
13049
}
12298
}
13050
}
(-)a/org.eclipse.jdt.core.tests.compiler/src/org/eclipse/jdt/core/tests/compiler/regression/BootstrapMethodAttributeTest.java (+74 lines)
Added Link Here
1
/*******************************************************************************
2
 * Copyright (c) 2011 IBM Corporation and others.
3
 * All rights reserved. This program and the accompanying materials
4
 * are made available under the terms of the Eclipse Public License v1.0
5
 * which accompanies this distribution, and is available at
6
 * http://www.eclipse.org/legal/epl-v10.html
7
 *
8
 * Contributors:
9
 *     IBM Corporation - initial API and implementation
10
 *******************************************************************************/
11
package org.eclipse.jdt.core.tests.compiler.regression;
12
13
import java.io.File;
14
15
import junit.framework.Test;
16
17
import org.eclipse.jdt.core.ToolFactory;
18
import org.eclipse.jdt.core.tests.util.Util;
19
import org.eclipse.jdt.core.util.ClassFileBytesDisassembler;
20
21
public class BootstrapMethodAttributeTest extends AbstractRegressionTest {
22
	public BootstrapMethodAttributeTest(String name) {
23
		super(name);
24
	}
25
26
	public static Class testClass() {
27
		return BootstrapMethodAttributeTest.class;
28
	}
29
30
	// Use this static initializer to specify subset for tests
31
	// All specified tests which does not belong to the class are skipped...
32
	static {
33
//		TESTS_PREFIX = "testBug95521";
34
//		TESTS_NAMES = new String[] { "testBug359495" };
35
//		TESTS_NUMBERS = new int[] { 53 };
36
//		TESTS_RANGE = new int[] { 23 -1,};
37
	}
38
	public static Test suite() {
39
		return buildMinimalComplianceTestSuite(testClass(), F_1_7);
40
	}
41
	public void test001() throws Exception {
42
43
			ClassFileBytesDisassembler disassembler = ToolFactory.createDefaultClassFileBytesDisassembler();
44
			String path = this.getCompilerTestsPluginDirectoryPath() + File.separator + "workspace" + File.separator + "TestBootstrapMethodAtt.class";
45
			byte[] classFileBytes = org.eclipse.jdt.internal.compiler.util.Util.getFileByteContent(new File(path));
46
			String actualOutput =
47
				disassembler.disassemble(
48
					classFileBytes,
49
					"\n",
50
					ClassFileBytesDisassembler.DETAILED);
51
52
			String expectedOutput =
53
					"//  (version 1.2 : 46.0, no super bit)\n" + 
54
					"public class test.G {\n" + 
55
					"  \n" + 
56
					"  // Method descriptor #2 ()V\n" + 
57
					"  // Stack: 0, Locals: 0\n" + 
58
					"  public static void call();\n" + 
59
					"    0  invokedynamic 0 dyn() : void [18]\n" + 
60
					"    5  return\n" + 
61
					"\n" + 
62
					"Bootstrap methods:\n" + 
63
					"  0 : # 17 arguments: {#1}\n" + 
64
					"}";
65
66
			int index = actualOutput.indexOf(expectedOutput);
67
			if (index == -1 || expectedOutput.length() == 0) {
68
				System.out.println(Util.displayString(actualOutput, 2));
69
			}
70
			if (index == -1) {
71
				assertEquals("Wrong contents", expectedOutput, actualOutput);
72
			}
73
	}
74
}
(-)a/org.eclipse.jdt.core.tests.compiler/src/org/eclipse/jdt/core/tests/compiler/regression/CastTest.java (+48 lines)
Lines 2374-2379 Link Here
2374
			"SUCCESS"
2374
			"SUCCESS"
2375
		);
2375
		);
2376
}
2376
}
2377
// https://bugs.eclipse.org/bugs/show_bug.cgi?id=359284
2378
// Verify that checkcast is emitted for a cast expression.
2379
public void test061b() throws Exception {
2380
	String source =
2381
		"public class X {\n" +
2382
	    "public X() {\n" +
2383
	    "    Object[] x = (Object[])null;\n" +
2384
	    "}\n" +
2385
	    "}\n";
2386
	this.runConformTest(
2387
			new String[] {
2388
				"X.java",
2389
				source
2390
			},
2391
			""
2392
		);
2393
	String expectedOutput = 
2394
			"public class X {\n" + 
2395
			"  \n" + 
2396
			"  // Method descriptor #6 ()V\n" + 
2397
			"  // Stack: 1, Locals: 2\n" + 
2398
			"  public X();\n" + 
2399
			"     0  aload_0 [this]\n" + 
2400
			"     1  invokespecial java.lang.Object() [8]\n" + 
2401
			"     4  aconst_null\n" + 
2402
			"     5  checkcast java.lang.Object[] [10]\n" + 
2403
			"     8  astore_1 [x]\n" + 
2404
			"     9  return\n" + 
2405
			"      Line numbers:\n" + 
2406
			"        [pc: 0, line: 2]\n" + 
2407
			"        [pc: 4, line: 3]\n" + 
2408
			"        [pc: 9, line: 4]\n" + 
2409
			"      Local variable table:\n" + 
2410
			"        [pc: 0, pc: 10] local: this index: 0 type: X\n" + 
2411
			"        [pc: 9, pc: 10] local: x index: 1 type: java.lang.Object[]\n" +
2412
			"}";
2413
	File f = new File(OUTPUT_DIR + File.separator + "X.class");
2414
	byte[] classFileBytes = org.eclipse.jdt.internal.compiler.util.Util.getFileByteContent(f);
2415
	ClassFileBytesDisassembler disassembler = ToolFactory.createDefaultClassFileBytesDisassembler();
2416
	String result = disassembler.disassemble(classFileBytes, "\n", ClassFileBytesDisassembler.DETAILED);
2417
	int index = result.indexOf(expectedOutput);
2418
	if (index == -1 || expectedOutput.length() == 0) {
2419
		System.out.println(Util.displayString(result, 3));
2420
	}
2421
	if (index == -1) {
2422
		assertEquals("Wrong contents", expectedOutput, result);
2423
	}
2424
}
2377
public static Class testClass() {
2425
public static Class testClass() {
2378
	return CastTest.class;
2426
	return CastTest.class;
2379
}
2427
}
(-)a/org.eclipse.jdt.core.tests.compiler/src/org/eclipse/jdt/core/tests/compiler/regression/CompilerInvocationTests.java (-2 / +58 lines)
Lines 1-5 Link Here
1
/*******************************************************************************
1
/*******************************************************************************
2
 * Copyright (c) 2006, 2011 IBM Corporation and others.
2
 * Copyright (c) 2006, 2012 IBM Corporation and others.
3
 * All rights reserved. This program and the accompanying materials
3
 * All rights reserved. This program and the accompanying materials
4
 * are made available under the terms of the Eclipse Public License v1.0
4
 * are made available under the terms of the Eclipse Public License v1.0
5
 * which accompanies this distribution, and is available at
5
 * which accompanies this distribution, and is available at
Lines 8-14 Link Here
8
 * Contributors:
8
 * Contributors:
9
 *     IBM Corporation - initial API and implementation
9
 *     IBM Corporation - initial API and implementation
10
 *     Benjamin Muskalla - Contribution for bug 239066
10
 *     Benjamin Muskalla - Contribution for bug 239066
11
 *     Stephan Herrmann  - Contribution for bug 236385
11
 *     Stephan Herrmann  - Contributions for 
12
 *     							bug 236385: [compiler] Warn for potential programming problem if an object is created but not used
13
 *     							bug 349326 - [1.7] new warning for missing try-with-resources
14
 *     							bug 186342 - [compiler][null] Using annotations for null checking
15
 *								bug 365662 - [compiler][null] warn on contradictory and redundant null annotations
12
 *******************************************************************************/
16
 *******************************************************************************/
13
package org.eclipse.jdt.core.tests.compiler.regression;
17
package org.eclipse.jdt.core.tests.compiler.regression;
14
18
Lines 378-383 Link Here
378
		expectedProblemAttributes.put("CannotDefineStaticInitializerInLocalType", new ProblemAttributes(CategorizedProblem.CAT_INTERNAL));
382
		expectedProblemAttributes.put("CannotDefineStaticInitializerInLocalType", new ProblemAttributes(CategorizedProblem.CAT_INTERNAL));
379
		expectedProblemAttributes.put("CannotExtendEnum", new ProblemAttributes(CategorizedProblem.CAT_TYPE));
383
		expectedProblemAttributes.put("CannotExtendEnum", new ProblemAttributes(CategorizedProblem.CAT_TYPE));
380
		expectedProblemAttributes.put("CannotHideAnInstanceMethodWithAStaticMethod", new ProblemAttributes(CategorizedProblem.CAT_MEMBER));
384
		expectedProblemAttributes.put("CannotHideAnInstanceMethodWithAStaticMethod", new ProblemAttributes(CategorizedProblem.CAT_MEMBER));
385
		expectedProblemAttributes.put("CannotImplementIncompatibleNullness", new ProblemAttributes(CategorizedProblem.CAT_POTENTIAL_PROGRAMMING_PROBLEM));
381
		expectedProblemAttributes.put("CannotImportPackage", new ProblemAttributes(CategorizedProblem.CAT_IMPORT));
386
		expectedProblemAttributes.put("CannotImportPackage", new ProblemAttributes(CategorizedProblem.CAT_IMPORT));
382
		expectedProblemAttributes.put("CannotInferElidedTypes", new ProblemAttributes(CategorizedProblem.CAT_TYPE));
387
		expectedProblemAttributes.put("CannotInferElidedTypes", new ProblemAttributes(CategorizedProblem.CAT_TYPE));
383
		expectedProblemAttributes.put("CannotInvokeSuperConstructorInEnum", new ProblemAttributes(CategorizedProblem.CAT_MEMBER));
388
		expectedProblemAttributes.put("CannotInvokeSuperConstructorInEnum", new ProblemAttributes(CategorizedProblem.CAT_MEMBER));
Lines 393-398 Link Here
393
		expectedProblemAttributes.put("CodeCannotBeReached", new ProblemAttributes(CategorizedProblem.CAT_INTERNAL));
398
		expectedProblemAttributes.put("CodeCannotBeReached", new ProblemAttributes(CategorizedProblem.CAT_INTERNAL));
394
		expectedProblemAttributes.put("CodeSnippetMissingClass", new ProblemAttributes(CategorizedProblem.CAT_INTERNAL));
399
		expectedProblemAttributes.put("CodeSnippetMissingClass", new ProblemAttributes(CategorizedProblem.CAT_INTERNAL));
395
		expectedProblemAttributes.put("CodeSnippetMissingMethod", new ProblemAttributes(CategorizedProblem.CAT_INTERNAL));
400
		expectedProblemAttributes.put("CodeSnippetMissingMethod", new ProblemAttributes(CategorizedProblem.CAT_INTERNAL));
401
		expectedProblemAttributes.put("ContradictoryNullAnnotations", new ProblemAttributes(CategorizedProblem.CAT_INTERNAL));
396
		expectedProblemAttributes.put("ComparingIdentical", new ProblemAttributes(CategorizedProblem.CAT_POTENTIAL_PROGRAMMING_PROBLEM));
402
		expectedProblemAttributes.put("ComparingIdentical", new ProblemAttributes(CategorizedProblem.CAT_POTENTIAL_PROGRAMMING_PROBLEM));
397
		expectedProblemAttributes.put("ConflictingImport", new ProblemAttributes(CategorizedProblem.CAT_IMPORT));
403
		expectedProblemAttributes.put("ConflictingImport", new ProblemAttributes(CategorizedProblem.CAT_IMPORT));
398
		expectedProblemAttributes.put("ConstructorVarargsArgumentNeedCast", new ProblemAttributes(CategorizedProblem.CAT_POTENTIAL_PROGRAMMING_PROBLEM));
404
		expectedProblemAttributes.put("ConstructorVarargsArgumentNeedCast", new ProblemAttributes(CategorizedProblem.CAT_POTENTIAL_PROGRAMMING_PROBLEM));
Lines 440-445 Link Here
440
		expectedProblemAttributes.put("ExceptionTypeInternalNameProvided", DEPRECATED);
446
		expectedProblemAttributes.put("ExceptionTypeInternalNameProvided", DEPRECATED);
441
		expectedProblemAttributes.put("ExceptionTypeNotFound", DEPRECATED);
447
		expectedProblemAttributes.put("ExceptionTypeNotFound", DEPRECATED);
442
		expectedProblemAttributes.put("ExceptionTypeNotVisible", DEPRECATED);
448
		expectedProblemAttributes.put("ExceptionTypeNotVisible", DEPRECATED);
449
		expectedProblemAttributes.put("ExplicitlyClosedAutoCloseable", new ProblemAttributes(CategorizedProblem.CAT_CODE_STYLE));
443
		expectedProblemAttributes.put("ExpressionShouldBeAVariable", new ProblemAttributes(CategorizedProblem.CAT_SYNTAX));
450
		expectedProblemAttributes.put("ExpressionShouldBeAVariable", new ProblemAttributes(CategorizedProblem.CAT_SYNTAX));
444
		expectedProblemAttributes.put("ExternalProblemFixable", new ProblemAttributes(CategorizedProblem.CAT_INTERNAL));
451
		expectedProblemAttributes.put("ExternalProblemFixable", new ProblemAttributes(CategorizedProblem.CAT_INTERNAL));
445
		expectedProblemAttributes.put("ExternalProblemNotFixable", new ProblemAttributes(CategorizedProblem.CAT_INTERNAL));
452
		expectedProblemAttributes.put("ExternalProblemNotFixable", new ProblemAttributes(CategorizedProblem.CAT_INTERNAL));
Lines 467-474 Link Here
467
		expectedProblemAttributes.put("HierarchyHasProblems", new ProblemAttributes(CategorizedProblem.CAT_TYPE));
474
		expectedProblemAttributes.put("HierarchyHasProblems", new ProblemAttributes(CategorizedProblem.CAT_TYPE));
468
		expectedProblemAttributes.put("IllegalAbstractModifierCombinationForMethod", new ProblemAttributes(CategorizedProblem.CAT_MEMBER));
475
		expectedProblemAttributes.put("IllegalAbstractModifierCombinationForMethod", new ProblemAttributes(CategorizedProblem.CAT_MEMBER));
469
		expectedProblemAttributes.put("IllegalAccessFromTypeVariable", new ProblemAttributes(CategorizedProblem.CAT_TYPE));
476
		expectedProblemAttributes.put("IllegalAccessFromTypeVariable", new ProblemAttributes(CategorizedProblem.CAT_TYPE));
477
		expectedProblemAttributes.put("IllegalAnnotationForBaseType", new ProblemAttributes(CategorizedProblem.CAT_TYPE));
470
		expectedProblemAttributes.put("IllegalCast", new ProblemAttributes(CategorizedProblem.CAT_TYPE));
478
		expectedProblemAttributes.put("IllegalCast", new ProblemAttributes(CategorizedProblem.CAT_TYPE));
471
		expectedProblemAttributes.put("IllegalClassLiteralForTypeVariable", new ProblemAttributes(CategorizedProblem.CAT_TYPE));
479
		expectedProblemAttributes.put("IllegalClassLiteralForTypeVariable", new ProblemAttributes(CategorizedProblem.CAT_TYPE));
480
		expectedProblemAttributes.put("IllegalDefinitionToNonNullParameter", new ProblemAttributes(CategorizedProblem.CAT_POTENTIAL_PROGRAMMING_PROBLEM));
472
		expectedProblemAttributes.put("IllegalDimension", new ProblemAttributes(CategorizedProblem.CAT_INTERNAL));
481
		expectedProblemAttributes.put("IllegalDimension", new ProblemAttributes(CategorizedProblem.CAT_INTERNAL));
473
		expectedProblemAttributes.put("IllegalEnclosingInstanceSpecification", new ProblemAttributes(CategorizedProblem.CAT_TYPE));
482
		expectedProblemAttributes.put("IllegalEnclosingInstanceSpecification", new ProblemAttributes(CategorizedProblem.CAT_TYPE));
474
		expectedProblemAttributes.put("IllegalExtendedDimensions", new ProblemAttributes(CategorizedProblem.CAT_MEMBER));
483
		expectedProblemAttributes.put("IllegalExtendedDimensions", new ProblemAttributes(CategorizedProblem.CAT_MEMBER));
Lines 503-508 Link Here
503
		expectedProblemAttributes.put("IllegalPrimitiveOrArrayTypeForEnclosingInstance", new ProblemAttributes(CategorizedProblem.CAT_TYPE));
512
		expectedProblemAttributes.put("IllegalPrimitiveOrArrayTypeForEnclosingInstance", new ProblemAttributes(CategorizedProblem.CAT_TYPE));
504
		expectedProblemAttributes.put("IllegalQualifiedEnumConstantLabel", new ProblemAttributes(CategorizedProblem.CAT_MEMBER));
513
		expectedProblemAttributes.put("IllegalQualifiedEnumConstantLabel", new ProblemAttributes(CategorizedProblem.CAT_MEMBER));
505
		expectedProblemAttributes.put("IllegalQualifiedParameterizedTypeAllocation", new ProblemAttributes(CategorizedProblem.CAT_TYPE));
514
		expectedProblemAttributes.put("IllegalQualifiedParameterizedTypeAllocation", new ProblemAttributes(CategorizedProblem.CAT_TYPE));
515
		expectedProblemAttributes.put("IllegalReturnNullityRedefinition", new ProblemAttributes(CategorizedProblem.CAT_POTENTIAL_PROGRAMMING_PROBLEM));
516
		expectedProblemAttributes.put("IllegalRedefinitionToNonNullParameter", new ProblemAttributes(CategorizedProblem.CAT_POTENTIAL_PROGRAMMING_PROBLEM));
506
		expectedProblemAttributes.put("IllegalStaticModifierForMemberType", new ProblemAttributes(CategorizedProblem.CAT_TYPE));
517
		expectedProblemAttributes.put("IllegalStaticModifierForMemberType", new ProblemAttributes(CategorizedProblem.CAT_TYPE));
507
		expectedProblemAttributes.put("IllegalTypeVariableSuperReference", new ProblemAttributes(CategorizedProblem.CAT_INTERNAL));
518
		expectedProblemAttributes.put("IllegalTypeVariableSuperReference", new ProblemAttributes(CategorizedProblem.CAT_INTERNAL));
508
		expectedProblemAttributes.put("IllegalUnderscorePosition", new ProblemAttributes(CategorizedProblem.CAT_SYNTAX));
519
		expectedProblemAttributes.put("IllegalUnderscorePosition", new ProblemAttributes(CategorizedProblem.CAT_SYNTAX));
Lines 742-747 Link Here
742
		expectedProblemAttributes.put("PackageCollidesWithType", new ProblemAttributes(CategorizedProblem.CAT_TYPE));
753
		expectedProblemAttributes.put("PackageCollidesWithType", new ProblemAttributes(CategorizedProblem.CAT_TYPE));
743
		expectedProblemAttributes.put("PackageIsNotExpectedPackage", new ProblemAttributes(CategorizedProblem.CAT_INTERNAL));
754
		expectedProblemAttributes.put("PackageIsNotExpectedPackage", new ProblemAttributes(CategorizedProblem.CAT_INTERNAL));
744
		expectedProblemAttributes.put("ParameterAssignment", new ProblemAttributes(CategorizedProblem.CAT_CODE_STYLE));
755
		expectedProblemAttributes.put("ParameterAssignment", new ProblemAttributes(CategorizedProblem.CAT_CODE_STYLE));
756
		expectedProblemAttributes.put("ParameterLackingNonNullAnnotation", new ProblemAttributes(CategorizedProblem.CAT_POTENTIAL_PROGRAMMING_PROBLEM));
757
		expectedProblemAttributes.put("ParameterLackingNullableAnnotation", new ProblemAttributes(CategorizedProblem.CAT_POTENTIAL_PROGRAMMING_PROBLEM));
745
		expectedProblemAttributes.put("ParameterMismatch", new ProblemAttributes(CategorizedProblem.CAT_MEMBER));
758
		expectedProblemAttributes.put("ParameterMismatch", new ProblemAttributes(CategorizedProblem.CAT_MEMBER));
746
		expectedProblemAttributes.put("ParameterizedConstructorArgumentTypeMismatch", new ProblemAttributes(CategorizedProblem.CAT_TYPE));
759
		expectedProblemAttributes.put("ParameterizedConstructorArgumentTypeMismatch", new ProblemAttributes(CategorizedProblem.CAT_TYPE));
747
		expectedProblemAttributes.put("ParameterizedMethodArgumentTypeMismatch", new ProblemAttributes(CategorizedProblem.CAT_TYPE));
760
		expectedProblemAttributes.put("ParameterizedMethodArgumentTypeMismatch", new ProblemAttributes(CategorizedProblem.CAT_TYPE));
Lines 765-771 Link Here
765
		expectedProblemAttributes.put("PolymorphicMethodNotBelow17", new ProblemAttributes(CategorizedProblem.CAT_MEMBER));
778
		expectedProblemAttributes.put("PolymorphicMethodNotBelow17", new ProblemAttributes(CategorizedProblem.CAT_MEMBER));
766
		expectedProblemAttributes.put("PossibleAccidentalBooleanAssignment", new ProblemAttributes(CategorizedProblem.CAT_POTENTIAL_PROGRAMMING_PROBLEM));
779
		expectedProblemAttributes.put("PossibleAccidentalBooleanAssignment", new ProblemAttributes(CategorizedProblem.CAT_POTENTIAL_PROGRAMMING_PROBLEM));
767
		expectedProblemAttributes.put("PotentialHeapPollutionFromVararg", new ProblemAttributes(CategorizedProblem.CAT_UNCHECKED_RAW));
780
		expectedProblemAttributes.put("PotentialHeapPollutionFromVararg", new ProblemAttributes(CategorizedProblem.CAT_UNCHECKED_RAW));
781
		expectedProblemAttributes.put("PotentiallyUnclosedCloseable", new ProblemAttributes(CategorizedProblem.CAT_POTENTIAL_PROGRAMMING_PROBLEM));
782
		expectedProblemAttributes.put("PotentiallyUnclosedCloseableAtExit", new ProblemAttributes(CategorizedProblem.CAT_POTENTIAL_PROGRAMMING_PROBLEM));
768
		expectedProblemAttributes.put("PotentialNullLocalVariableReference", new ProblemAttributes(CategorizedProblem.CAT_POTENTIAL_PROGRAMMING_PROBLEM));
783
		expectedProblemAttributes.put("PotentialNullLocalVariableReference", new ProblemAttributes(CategorizedProblem.CAT_POTENTIAL_PROGRAMMING_PROBLEM));
784
		expectedProblemAttributes.put("PotentialNullMessageSendReference", new ProblemAttributes(CategorizedProblem.CAT_POTENTIAL_PROGRAMMING_PROBLEM));
769
		expectedProblemAttributes.put("PublicClassMustMatchFileName", new ProblemAttributes(CategorizedProblem.CAT_TYPE));
785
		expectedProblemAttributes.put("PublicClassMustMatchFileName", new ProblemAttributes(CategorizedProblem.CAT_TYPE));
770
		expectedProblemAttributes.put("RawMemberTypeCannotBeParameterized", new ProblemAttributes(CategorizedProblem.CAT_TYPE));
786
		expectedProblemAttributes.put("RawMemberTypeCannotBeParameterized", new ProblemAttributes(CategorizedProblem.CAT_TYPE));
771
		expectedProblemAttributes.put("RawTypeReference", new ProblemAttributes(CategorizedProblem.CAT_UNCHECKED_RAW));
787
		expectedProblemAttributes.put("RawTypeReference", new ProblemAttributes(CategorizedProblem.CAT_UNCHECKED_RAW));
Lines 774-783 Link Here
774
		expectedProblemAttributes.put("RedefinedLocal", new ProblemAttributes(CategorizedProblem.CAT_INTERNAL));
790
		expectedProblemAttributes.put("RedefinedLocal", new ProblemAttributes(CategorizedProblem.CAT_INTERNAL));
775
		expectedProblemAttributes.put("RedundantSpecificationOfTypeArguments", new ProblemAttributes(CategorizedProblem.CAT_UNNECESSARY_CODE));
791
		expectedProblemAttributes.put("RedundantSpecificationOfTypeArguments", new ProblemAttributes(CategorizedProblem.CAT_UNNECESSARY_CODE));
776
		expectedProblemAttributes.put("RedundantLocalVariableNullAssignment", new ProblemAttributes(CategorizedProblem.CAT_POTENTIAL_PROGRAMMING_PROBLEM));
792
		expectedProblemAttributes.put("RedundantLocalVariableNullAssignment", new ProblemAttributes(CategorizedProblem.CAT_POTENTIAL_PROGRAMMING_PROBLEM));
793
		expectedProblemAttributes.put("RedundantNullAnnotation", new ProblemAttributes(CategorizedProblem.CAT_UNNECESSARY_CODE));
777
		expectedProblemAttributes.put("RedundantNullCheckOnNonNullLocalVariable", new ProblemAttributes(CategorizedProblem.CAT_POTENTIAL_PROGRAMMING_PROBLEM));
794
		expectedProblemAttributes.put("RedundantNullCheckOnNonNullLocalVariable", new ProblemAttributes(CategorizedProblem.CAT_POTENTIAL_PROGRAMMING_PROBLEM));
795
		expectedProblemAttributes.put("RedundantNullCheckOnNonNullMessageSend", new ProblemAttributes(CategorizedProblem.CAT_POTENTIAL_PROGRAMMING_PROBLEM));
778
		expectedProblemAttributes.put("RedundantNullCheckOnNullLocalVariable", new ProblemAttributes(CategorizedProblem.CAT_POTENTIAL_PROGRAMMING_PROBLEM));
796
		expectedProblemAttributes.put("RedundantNullCheckOnNullLocalVariable", new ProblemAttributes(CategorizedProblem.CAT_POTENTIAL_PROGRAMMING_PROBLEM));
797
		expectedProblemAttributes.put("RedundantNullDefaultAnnotation", new ProblemAttributes(CategorizedProblem.CAT_UNNECESSARY_CODE));
798
		expectedProblemAttributes.put("RedundantNullDefaultAnnotationPackage", new ProblemAttributes(CategorizedProblem.CAT_UNNECESSARY_CODE));
799
		expectedProblemAttributes.put("RedundantNullDefaultAnnotationType", new ProblemAttributes(CategorizedProblem.CAT_UNNECESSARY_CODE));
800
		expectedProblemAttributes.put("RedundantNullDefaultAnnotationMethod", new ProblemAttributes(CategorizedProblem.CAT_UNNECESSARY_CODE));
779
		expectedProblemAttributes.put("RedundantSuperinterface", new ProblemAttributes(CategorizedProblem.CAT_UNNECESSARY_CODE));
801
		expectedProblemAttributes.put("RedundantSuperinterface", new ProblemAttributes(CategorizedProblem.CAT_UNNECESSARY_CODE));
780
		expectedProblemAttributes.put("ReferenceToForwardField", new ProblemAttributes(CategorizedProblem.CAT_MEMBER));
802
		expectedProblemAttributes.put("ReferenceToForwardField", new ProblemAttributes(CategorizedProblem.CAT_MEMBER));
803
		expectedProblemAttributes.put("RequiredNonNullButProvidedNull", new ProblemAttributes(CategorizedProblem.CAT_POTENTIAL_PROGRAMMING_PROBLEM));
804
		expectedProblemAttributes.put("RequiredNonNullButProvidedPotentialNull", new ProblemAttributes(CategorizedProblem.CAT_POTENTIAL_PROGRAMMING_PROBLEM));
805
		expectedProblemAttributes.put("RequiredNonNullButProvidedUnknown", new ProblemAttributes(CategorizedProblem.CAT_POTENTIAL_PROGRAMMING_PROBLEM));
781
		expectedProblemAttributes.put("ReferenceToForwardTypeVariable", new ProblemAttributes(CategorizedProblem.CAT_TYPE));
806
		expectedProblemAttributes.put("ReferenceToForwardTypeVariable", new ProblemAttributes(CategorizedProblem.CAT_TYPE));
782
		expectedProblemAttributes.put("ResourceHasToImplementAutoCloseable", new ProblemAttributes(CategorizedProblem.CAT_TYPE));
807
		expectedProblemAttributes.put("ResourceHasToImplementAutoCloseable", new ProblemAttributes(CategorizedProblem.CAT_TYPE));
783
		expectedProblemAttributes.put("ReturnTypeAmbiguous", DEPRECATED);
808
		expectedProblemAttributes.put("ReturnTypeAmbiguous", DEPRECATED);
Lines 804-809 Link Here
804
		expectedProblemAttributes.put("SuperclassNotFound", DEPRECATED);
829
		expectedProblemAttributes.put("SuperclassNotFound", DEPRECATED);
805
		expectedProblemAttributes.put("SuperclassNotVisible", DEPRECATED);
830
		expectedProblemAttributes.put("SuperclassNotVisible", DEPRECATED);
806
		expectedProblemAttributes.put("SuperfluousSemicolon", new ProblemAttributes(CategorizedProblem.CAT_POTENTIAL_PROGRAMMING_PROBLEM));
831
		expectedProblemAttributes.put("SuperfluousSemicolon", new ProblemAttributes(CategorizedProblem.CAT_POTENTIAL_PROGRAMMING_PROBLEM));
832
		expectedProblemAttributes.put("SwitchOnEnumNotBelow15", new ProblemAttributes(CategorizedProblem.CAT_TYPE));
807
		expectedProblemAttributes.put("SwitchOnStringsNotBelow17", new ProblemAttributes(CategorizedProblem.CAT_TYPE));
833
		expectedProblemAttributes.put("SwitchOnStringsNotBelow17", new ProblemAttributes(CategorizedProblem.CAT_TYPE));
808
		expectedProblemAttributes.put("Task", new ProblemAttributes(CategorizedProblem.CAT_INTERNAL));
834
		expectedProblemAttributes.put("Task", new ProblemAttributes(CategorizedProblem.CAT_INTERNAL));
809
		expectedProblemAttributes.put("ThisInStaticContext", new ProblemAttributes(CategorizedProblem.CAT_INTERNAL));
835
		expectedProblemAttributes.put("ThisInStaticContext", new ProblemAttributes(CategorizedProblem.CAT_INTERNAL));
Lines 828-833 Link Here
828
		expectedProblemAttributes.put("TypeMissingDeprecatedAnnotation", new ProblemAttributes(CategorizedProblem.CAT_CODE_STYLE));
854
		expectedProblemAttributes.put("TypeMissingDeprecatedAnnotation", new ProblemAttributes(CategorizedProblem.CAT_CODE_STYLE));
829
		expectedProblemAttributes.put("TypeParameterHidingType", new ProblemAttributes(CategorizedProblem.CAT_NAME_SHADOWING_CONFLICT));
855
		expectedProblemAttributes.put("TypeParameterHidingType", new ProblemAttributes(CategorizedProblem.CAT_NAME_SHADOWING_CONFLICT));
830
		expectedProblemAttributes.put("UnboxingConversion", new ProblemAttributes(CategorizedProblem.CAT_CODE_STYLE));
856
		expectedProblemAttributes.put("UnboxingConversion", new ProblemAttributes(CategorizedProblem.CAT_CODE_STYLE));
857
		expectedProblemAttributes.put("UnclosedCloseable", new ProblemAttributes(CategorizedProblem.CAT_POTENTIAL_PROGRAMMING_PROBLEM));
858
		expectedProblemAttributes.put("UnclosedCloseableAtExit", new ProblemAttributes(CategorizedProblem.CAT_POTENTIAL_PROGRAMMING_PROBLEM));
831
		expectedProblemAttributes.put("UndefinedAnnotationMember", new ProblemAttributes(CategorizedProblem.CAT_MEMBER));
859
		expectedProblemAttributes.put("UndefinedAnnotationMember", new ProblemAttributes(CategorizedProblem.CAT_MEMBER));
832
		expectedProblemAttributes.put("UndefinedConstructor", new ProblemAttributes(CategorizedProblem.CAT_MEMBER));
860
		expectedProblemAttributes.put("UndefinedConstructor", new ProblemAttributes(CategorizedProblem.CAT_MEMBER));
833
		expectedProblemAttributes.put("UndefinedConstructorInDefaultConstructor", new ProblemAttributes(CategorizedProblem.CAT_MEMBER));
861
		expectedProblemAttributes.put("UndefinedConstructorInDefaultConstructor", new ProblemAttributes(CategorizedProblem.CAT_MEMBER));
Lines 887-892 Link Here
887
		expectedProblemAttributes.put("UsingDeprecatedField", new ProblemAttributes(CategorizedProblem.CAT_DEPRECATION));
915
		expectedProblemAttributes.put("UsingDeprecatedField", new ProblemAttributes(CategorizedProblem.CAT_DEPRECATION));
888
		expectedProblemAttributes.put("UsingDeprecatedMethod", new ProblemAttributes(CategorizedProblem.CAT_DEPRECATION));
916
		expectedProblemAttributes.put("UsingDeprecatedMethod", new ProblemAttributes(CategorizedProblem.CAT_DEPRECATION));
889
		expectedProblemAttributes.put("UsingDeprecatedType", new ProblemAttributes(CategorizedProblem.CAT_DEPRECATION));
917
		expectedProblemAttributes.put("UsingDeprecatedType", new ProblemAttributes(CategorizedProblem.CAT_DEPRECATION));
918
		expectedProblemAttributes.put("VarargsElementTypeNotVisible", new ProblemAttributes(CategorizedProblem.CAT_MEMBER));
919
		expectedProblemAttributes.put("VarargsElementTypeNotVisibleForConstructor", new ProblemAttributes(CategorizedProblem.CAT_MEMBER));
890
		expectedProblemAttributes.put("VarargsConflict", new ProblemAttributes(CategorizedProblem.CAT_MEMBER));
920
		expectedProblemAttributes.put("VarargsConflict", new ProblemAttributes(CategorizedProblem.CAT_MEMBER));
891
		expectedProblemAttributes.put("VariableTypeCannotBeVoid", new ProblemAttributes(CategorizedProblem.CAT_INTERNAL));
921
		expectedProblemAttributes.put("VariableTypeCannotBeVoid", new ProblemAttributes(CategorizedProblem.CAT_INTERNAL));
892
		expectedProblemAttributes.put("VariableTypeCannotBeVoidArray", DEPRECATED);
922
		expectedProblemAttributes.put("VariableTypeCannotBeVoidArray", DEPRECATED);
Lines 1047-1052 Link Here
1047
		expectedProblemAttributes.put("CannotExtendEnum", SKIP);
1077
		expectedProblemAttributes.put("CannotExtendEnum", SKIP);
1048
		expectedProblemAttributes.put("CannotHideAnInstanceMethodWithAStaticMethod", SKIP);
1078
		expectedProblemAttributes.put("CannotHideAnInstanceMethodWithAStaticMethod", SKIP);
1049
		expectedProblemAttributes.put("CannotImportPackage", SKIP);
1079
		expectedProblemAttributes.put("CannotImportPackage", SKIP);
1080
		expectedProblemAttributes.put("CannotImplementIncompatibleNullness", new ProblemAttributes(JavaCore.COMPILER_PB_NULL_SPECIFICATION_VIOLATION));
1050
		expectedProblemAttributes.put("CannotInferElidedTypes", SKIP);
1081
		expectedProblemAttributes.put("CannotInferElidedTypes", SKIP);
1051
		expectedProblemAttributes.put("CannotInvokeSuperConstructorInEnum", SKIP);
1082
		expectedProblemAttributes.put("CannotInvokeSuperConstructorInEnum", SKIP);
1052
		expectedProblemAttributes.put("CannotOverrideAStaticMethodWithAnInstanceMethod", SKIP);
1083
		expectedProblemAttributes.put("CannotOverrideAStaticMethodWithAnInstanceMethod", SKIP);
Lines 1063-1068 Link Here
1063
		expectedProblemAttributes.put("CodeSnippetMissingMethod", SKIP);
1094
		expectedProblemAttributes.put("CodeSnippetMissingMethod", SKIP);
1064
		expectedProblemAttributes.put("ComparingIdentical", new ProblemAttributes(JavaCore.COMPILER_PB_COMPARING_IDENTICAL));
1095
		expectedProblemAttributes.put("ComparingIdentical", new ProblemAttributes(JavaCore.COMPILER_PB_COMPARING_IDENTICAL));
1065
		expectedProblemAttributes.put("ConflictingImport", SKIP);
1096
		expectedProblemAttributes.put("ConflictingImport", SKIP);
1097
		expectedProblemAttributes.put("ContradictoryNullAnnotations", SKIP);
1066
		expectedProblemAttributes.put("ConstructorVarargsArgumentNeedCast", new ProblemAttributes(JavaCore.COMPILER_PB_VARARGS_ARGUMENT_NEED_CAST));
1098
		expectedProblemAttributes.put("ConstructorVarargsArgumentNeedCast", new ProblemAttributes(JavaCore.COMPILER_PB_VARARGS_ARGUMENT_NEED_CAST));
1067
		expectedProblemAttributes.put("CorruptedSignature", SKIP);
1099
		expectedProblemAttributes.put("CorruptedSignature", SKIP);
1068
		expectedProblemAttributes.put("DeadCode", new ProblemAttributes(JavaCore.COMPILER_PB_DEAD_CODE));
1100
		expectedProblemAttributes.put("DeadCode", new ProblemAttributes(JavaCore.COMPILER_PB_DEAD_CODE));
Lines 1108-1113 Link Here
1108
		expectedProblemAttributes.put("ExceptionTypeInternalNameProvided", SKIP);
1140
		expectedProblemAttributes.put("ExceptionTypeInternalNameProvided", SKIP);
1109
		expectedProblemAttributes.put("ExceptionTypeNotFound", SKIP);
1141
		expectedProblemAttributes.put("ExceptionTypeNotFound", SKIP);
1110
		expectedProblemAttributes.put("ExceptionTypeNotVisible", SKIP);
1142
		expectedProblemAttributes.put("ExceptionTypeNotVisible", SKIP);
1143
		expectedProblemAttributes.put("ExplicitlyClosedAutoCloseable", new ProblemAttributes(JavaCore.COMPILER_PB_EXPLICITLY_CLOSED_AUTOCLOSEABLE));
1111
		expectedProblemAttributes.put("ExpressionShouldBeAVariable", SKIP);
1144
		expectedProblemAttributes.put("ExpressionShouldBeAVariable", SKIP);
1112
		expectedProblemAttributes.put("ExternalProblemFixable", SKIP);
1145
		expectedProblemAttributes.put("ExternalProblemFixable", SKIP);
1113
		expectedProblemAttributes.put("ExternalProblemNotFixable", SKIP);
1146
		expectedProblemAttributes.put("ExternalProblemNotFixable", SKIP);
Lines 1135-1142 Link Here
1135
		expectedProblemAttributes.put("HierarchyHasProblems", SKIP);
1168
		expectedProblemAttributes.put("HierarchyHasProblems", SKIP);
1136
		expectedProblemAttributes.put("IllegalAbstractModifierCombinationForMethod", SKIP);
1169
		expectedProblemAttributes.put("IllegalAbstractModifierCombinationForMethod", SKIP);
1137
		expectedProblemAttributes.put("IllegalAccessFromTypeVariable", SKIP);
1170
		expectedProblemAttributes.put("IllegalAccessFromTypeVariable", SKIP);
1171
		expectedProblemAttributes.put("IllegalAnnotationForBaseType", SKIP);
1138
		expectedProblemAttributes.put("IllegalCast", SKIP);
1172
		expectedProblemAttributes.put("IllegalCast", SKIP);
1139
		expectedProblemAttributes.put("IllegalClassLiteralForTypeVariable", SKIP);
1173
		expectedProblemAttributes.put("IllegalClassLiteralForTypeVariable", SKIP);
1174
		expectedProblemAttributes.put("IllegalDefinitionToNonNullParameter", new ProblemAttributes(JavaCore.COMPILER_PB_NULL_SPECIFICATION_VIOLATION));
1140
		expectedProblemAttributes.put("IllegalDimension", SKIP);
1175
		expectedProblemAttributes.put("IllegalDimension", SKIP);
1141
		expectedProblemAttributes.put("IllegalEnclosingInstanceSpecification", SKIP);
1176
		expectedProblemAttributes.put("IllegalEnclosingInstanceSpecification", SKIP);
1142
		expectedProblemAttributes.put("IllegalExtendedDimensions", SKIP);
1177
		expectedProblemAttributes.put("IllegalExtendedDimensions", SKIP);
Lines 1171-1176 Link Here
1171
		expectedProblemAttributes.put("IllegalPrimitiveOrArrayTypeForEnclosingInstance", SKIP);
1206
		expectedProblemAttributes.put("IllegalPrimitiveOrArrayTypeForEnclosingInstance", SKIP);
1172
		expectedProblemAttributes.put("IllegalQualifiedEnumConstantLabel", SKIP);
1207
		expectedProblemAttributes.put("IllegalQualifiedEnumConstantLabel", SKIP);
1173
		expectedProblemAttributes.put("IllegalQualifiedParameterizedTypeAllocation", SKIP);
1208
		expectedProblemAttributes.put("IllegalQualifiedParameterizedTypeAllocation", SKIP);
1209
		expectedProblemAttributes.put("IllegalRedefinitionToNonNullParameter", new ProblemAttributes(JavaCore.COMPILER_PB_NULL_SPECIFICATION_VIOLATION));
1210
		expectedProblemAttributes.put("IllegalReturnNullityRedefinition", new ProblemAttributes(JavaCore.COMPILER_PB_NULL_SPECIFICATION_VIOLATION));
1174
		expectedProblemAttributes.put("IllegalStaticModifierForMemberType", SKIP);
1211
		expectedProblemAttributes.put("IllegalStaticModifierForMemberType", SKIP);
1175
		expectedProblemAttributes.put("IllegalTypeVariableSuperReference", SKIP);
1212
		expectedProblemAttributes.put("IllegalTypeVariableSuperReference", SKIP);
1176
		expectedProblemAttributes.put("IllegalUnderscorePosition", SKIP);
1213
		expectedProblemAttributes.put("IllegalUnderscorePosition", SKIP);
Lines 1410-1415 Link Here
1410
		expectedProblemAttributes.put("PackageCollidesWithType", SKIP);
1447
		expectedProblemAttributes.put("PackageCollidesWithType", SKIP);
1411
		expectedProblemAttributes.put("PackageIsNotExpectedPackage", SKIP);
1448
		expectedProblemAttributes.put("PackageIsNotExpectedPackage", SKIP);
1412
		expectedProblemAttributes.put("ParameterAssignment", new ProblemAttributes(JavaCore.COMPILER_PB_PARAMETER_ASSIGNMENT));
1449
		expectedProblemAttributes.put("ParameterAssignment", new ProblemAttributes(JavaCore.COMPILER_PB_PARAMETER_ASSIGNMENT));
1450
		expectedProblemAttributes.put("ParameterLackingNonNullAnnotation", new ProblemAttributes(JavaCore.COMPILER_PB_NULL_SPECIFICATION_VIOLATION));
1451
		expectedProblemAttributes.put("ParameterLackingNullableAnnotation", new ProblemAttributes(JavaCore.COMPILER_PB_NULL_SPECIFICATION_VIOLATION));
1413
		expectedProblemAttributes.put("ParameterMismatch", SKIP);
1452
		expectedProblemAttributes.put("ParameterMismatch", SKIP);
1414
		expectedProblemAttributes.put("ParameterizedConstructorArgumentTypeMismatch", SKIP);
1453
		expectedProblemAttributes.put("ParameterizedConstructorArgumentTypeMismatch", SKIP);
1415
		expectedProblemAttributes.put("ParameterizedMethodArgumentTypeMismatch", SKIP);
1454
		expectedProblemAttributes.put("ParameterizedMethodArgumentTypeMismatch", SKIP);
Lines 1433-1439 Link Here
1433
		expectedProblemAttributes.put("PolymorphicMethodNotBelow17", SKIP);
1472
		expectedProblemAttributes.put("PolymorphicMethodNotBelow17", SKIP);
1434
		expectedProblemAttributes.put("PossibleAccidentalBooleanAssignment", new ProblemAttributes(JavaCore.COMPILER_PB_POSSIBLE_ACCIDENTAL_BOOLEAN_ASSIGNMENT));
1473
		expectedProblemAttributes.put("PossibleAccidentalBooleanAssignment", new ProblemAttributes(JavaCore.COMPILER_PB_POSSIBLE_ACCIDENTAL_BOOLEAN_ASSIGNMENT));
1435
		expectedProblemAttributes.put("PotentialHeapPollutionFromVararg", new ProblemAttributes(JavaCore.COMPILER_PB_UNCHECKED_TYPE_OPERATION));
1474
		expectedProblemAttributes.put("PotentialHeapPollutionFromVararg", new ProblemAttributes(JavaCore.COMPILER_PB_UNCHECKED_TYPE_OPERATION));
1475
		expectedProblemAttributes.put("PotentiallyUnclosedCloseable", new ProblemAttributes(JavaCore.COMPILER_PB_POTENTIALLY_UNCLOSED_CLOSEABLE));
1476
		expectedProblemAttributes.put("PotentiallyUnclosedCloseableAtExit", new ProblemAttributes(JavaCore.COMPILER_PB_POTENTIALLY_UNCLOSED_CLOSEABLE));
1436
		expectedProblemAttributes.put("PotentialNullLocalVariableReference", new ProblemAttributes(JavaCore.COMPILER_PB_POTENTIAL_NULL_REFERENCE));
1477
		expectedProblemAttributes.put("PotentialNullLocalVariableReference", new ProblemAttributes(JavaCore.COMPILER_PB_POTENTIAL_NULL_REFERENCE));
1478
		expectedProblemAttributes.put("PotentialNullMessageSendReference", new ProblemAttributes(JavaCore.COMPILER_PB_POTENTIAL_NULL_REFERENCE));
1437
		expectedProblemAttributes.put("PublicClassMustMatchFileName", SKIP);
1479
		expectedProblemAttributes.put("PublicClassMustMatchFileName", SKIP);
1438
		expectedProblemAttributes.put("RawMemberTypeCannotBeParameterized", SKIP);
1480
		expectedProblemAttributes.put("RawMemberTypeCannotBeParameterized", SKIP);
1439
		expectedProblemAttributes.put("RawTypeReference", new ProblemAttributes(JavaCore.COMPILER_PB_RAW_TYPE_REFERENCE));
1481
		expectedProblemAttributes.put("RawTypeReference", new ProblemAttributes(JavaCore.COMPILER_PB_RAW_TYPE_REFERENCE));
Lines 1442-1452 Link Here
1442
		expectedProblemAttributes.put("RedefinedLocal", SKIP);
1484
		expectedProblemAttributes.put("RedefinedLocal", SKIP);
1443
		expectedProblemAttributes.put("RedundantSpecificationOfTypeArguments", new ProblemAttributes(JavaCore.COMPILER_PB_REDUNDANT_TYPE_ARGUMENTS));
1485
		expectedProblemAttributes.put("RedundantSpecificationOfTypeArguments", new ProblemAttributes(JavaCore.COMPILER_PB_REDUNDANT_TYPE_ARGUMENTS));
1444
		expectedProblemAttributes.put("RedundantLocalVariableNullAssignment", new ProblemAttributes(JavaCore.COMPILER_PB_REDUNDANT_NULL_CHECK));
1486
		expectedProblemAttributes.put("RedundantLocalVariableNullAssignment", new ProblemAttributes(JavaCore.COMPILER_PB_REDUNDANT_NULL_CHECK));
1487
		expectedProblemAttributes.put("RedundantNullAnnotation", new ProblemAttributes(JavaCore.COMPILER_PB_REDUNDANT_NULL_ANNOTATION));
1445
		expectedProblemAttributes.put("RedundantNullCheckOnNonNullLocalVariable", new ProblemAttributes(JavaCore.COMPILER_PB_REDUNDANT_NULL_CHECK));
1488
		expectedProblemAttributes.put("RedundantNullCheckOnNonNullLocalVariable", new ProblemAttributes(JavaCore.COMPILER_PB_REDUNDANT_NULL_CHECK));
1489
		expectedProblemAttributes.put("RedundantNullCheckOnNonNullMessageSend", new ProblemAttributes(JavaCore.COMPILER_PB_REDUNDANT_NULL_CHECK));
1446
		expectedProblemAttributes.put("RedundantNullCheckOnNullLocalVariable", new ProblemAttributes(JavaCore.COMPILER_PB_REDUNDANT_NULL_CHECK));
1490
		expectedProblemAttributes.put("RedundantNullCheckOnNullLocalVariable", new ProblemAttributes(JavaCore.COMPILER_PB_REDUNDANT_NULL_CHECK));
1491
		expectedProblemAttributes.put("RedundantNullDefaultAnnotation", new ProblemAttributes(JavaCore.COMPILER_PB_REDUNDANT_NULL_ANNOTATION));
1492
		expectedProblemAttributes.put("RedundantNullDefaultAnnotationPackage", new ProblemAttributes(JavaCore.COMPILER_PB_REDUNDANT_NULL_ANNOTATION));
1493
		expectedProblemAttributes.put("RedundantNullDefaultAnnotationType", new ProblemAttributes(JavaCore.COMPILER_PB_REDUNDANT_NULL_ANNOTATION));
1494
		expectedProblemAttributes.put("RedundantNullDefaultAnnotationMethod", new ProblemAttributes(JavaCore.COMPILER_PB_REDUNDANT_NULL_ANNOTATION));
1447
		expectedProblemAttributes.put("RedundantSuperinterface", new ProblemAttributes(JavaCore.COMPILER_PB_REDUNDANT_SUPERINTERFACE));
1495
		expectedProblemAttributes.put("RedundantSuperinterface", new ProblemAttributes(JavaCore.COMPILER_PB_REDUNDANT_SUPERINTERFACE));
1448
		expectedProblemAttributes.put("ReferenceToForwardField", SKIP);
1496
		expectedProblemAttributes.put("ReferenceToForwardField", SKIP);
1449
		expectedProblemAttributes.put("ReferenceToForwardTypeVariable", SKIP);
1497
		expectedProblemAttributes.put("ReferenceToForwardTypeVariable", SKIP);
1498
		expectedProblemAttributes.put("RequiredNonNullButProvidedNull", new ProblemAttributes(JavaCore.COMPILER_PB_NULL_SPECIFICATION_VIOLATION));
1499
		expectedProblemAttributes.put("RequiredNonNullButProvidedPotentialNull", new ProblemAttributes(JavaCore.COMPILER_PB_POTENTIAL_NULL_SPECIFICATION_VIOLATION));
1500
		expectedProblemAttributes.put("RequiredNonNullButProvidedUnknown", new ProblemAttributes(JavaCore.COMPILER_PB_NULL_SPECIFICATION_INSUFFICIENT_INFO));
1450
		expectedProblemAttributes.put("ResourceHasToImplementAutoCloseable", SKIP);
1501
		expectedProblemAttributes.put("ResourceHasToImplementAutoCloseable", SKIP);
1451
		expectedProblemAttributes.put("ReturnTypeAmbiguous", SKIP);
1502
		expectedProblemAttributes.put("ReturnTypeAmbiguous", SKIP);
1452
		expectedProblemAttributes.put("ReturnTypeCannotBeVoidArray", SKIP);
1503
		expectedProblemAttributes.put("ReturnTypeCannotBeVoidArray", SKIP);
Lines 1472-1477 Link Here
1472
		expectedProblemAttributes.put("SuperclassNotFound", SKIP);
1523
		expectedProblemAttributes.put("SuperclassNotFound", SKIP);
1473
		expectedProblemAttributes.put("SuperclassNotVisible", new ProblemAttributes(JavaCore.COMPILER_PB_REDUNDANT_SUPERINTERFACE));
1524
		expectedProblemAttributes.put("SuperclassNotVisible", new ProblemAttributes(JavaCore.COMPILER_PB_REDUNDANT_SUPERINTERFACE));
1474
		expectedProblemAttributes.put("SuperfluousSemicolon", new ProblemAttributes(JavaCore.COMPILER_PB_EMPTY_STATEMENT));
1525
		expectedProblemAttributes.put("SuperfluousSemicolon", new ProblemAttributes(JavaCore.COMPILER_PB_EMPTY_STATEMENT));
1526
		expectedProblemAttributes.put("SwitchOnEnumNotBelow15", SKIP);
1475
		expectedProblemAttributes.put("SwitchOnStringsNotBelow17", SKIP);
1527
		expectedProblemAttributes.put("SwitchOnStringsNotBelow17", SKIP);
1476
		expectedProblemAttributes.put("Task", SKIP);
1528
		expectedProblemAttributes.put("Task", SKIP);
1477
		expectedProblemAttributes.put("ThisInStaticContext", SKIP);
1529
		expectedProblemAttributes.put("ThisInStaticContext", SKIP);
Lines 1496-1501 Link Here
1496
		expectedProblemAttributes.put("TypeMissingDeprecatedAnnotation", new ProblemAttributes(JavaCore.COMPILER_PB_MISSING_DEPRECATED_ANNOTATION));
1548
		expectedProblemAttributes.put("TypeMissingDeprecatedAnnotation", new ProblemAttributes(JavaCore.COMPILER_PB_MISSING_DEPRECATED_ANNOTATION));
1497
		expectedProblemAttributes.put("TypeParameterHidingType", new ProblemAttributes(JavaCore.COMPILER_PB_TYPE_PARAMETER_HIDING));
1549
		expectedProblemAttributes.put("TypeParameterHidingType", new ProblemAttributes(JavaCore.COMPILER_PB_TYPE_PARAMETER_HIDING));
1498
		expectedProblemAttributes.put("UnboxingConversion", new ProblemAttributes(JavaCore.COMPILER_PB_AUTOBOXING));
1550
		expectedProblemAttributes.put("UnboxingConversion", new ProblemAttributes(JavaCore.COMPILER_PB_AUTOBOXING));
1551
		expectedProblemAttributes.put("UnclosedCloseable", new ProblemAttributes(JavaCore.COMPILER_PB_UNCLOSED_CLOSEABLE));
1552
		expectedProblemAttributes.put("UnclosedCloseableAtExit", new ProblemAttributes(JavaCore.COMPILER_PB_UNCLOSED_CLOSEABLE));
1499
		expectedProblemAttributes.put("UndefinedAnnotationMember", SKIP);
1553
		expectedProblemAttributes.put("UndefinedAnnotationMember", SKIP);
1500
		expectedProblemAttributes.put("UndefinedConstructor", SKIP);
1554
		expectedProblemAttributes.put("UndefinedConstructor", SKIP);
1501
		expectedProblemAttributes.put("UndefinedConstructorInDefaultConstructor", SKIP);
1555
		expectedProblemAttributes.put("UndefinedConstructorInDefaultConstructor", SKIP);
Lines 1556-1561 Link Here
1556
		expectedProblemAttributes.put("UsingDeprecatedMethod", new ProblemAttributes(JavaCore.COMPILER_PB_DEPRECATION));
1610
		expectedProblemAttributes.put("UsingDeprecatedMethod", new ProblemAttributes(JavaCore.COMPILER_PB_DEPRECATION));
1557
		expectedProblemAttributes.put("UsingDeprecatedType", new ProblemAttributes(JavaCore.COMPILER_PB_DEPRECATION));
1611
		expectedProblemAttributes.put("UsingDeprecatedType", new ProblemAttributes(JavaCore.COMPILER_PB_DEPRECATION));
1558
		expectedProblemAttributes.put("VarargsConflict", SKIP);
1612
		expectedProblemAttributes.put("VarargsConflict", SKIP);
1613
		expectedProblemAttributes.put("VarargsElementTypeNotVisible", SKIP);
1614
		expectedProblemAttributes.put("VarargsElementTypeNotVisibleForConstructor", SKIP);
1559
		expectedProblemAttributes.put("VariableTypeCannotBeVoid", SKIP);
1615
		expectedProblemAttributes.put("VariableTypeCannotBeVoid", SKIP);
1560
		expectedProblemAttributes.put("VariableTypeCannotBeVoidArray", SKIP);
1616
		expectedProblemAttributes.put("VariableTypeCannotBeVoidArray", SKIP);
1561
		expectedProblemAttributes.put("VoidMethodReturnsValue", SKIP);
1617
		expectedProblemAttributes.put("VoidMethodReturnsValue", SKIP);
(-)a/org.eclipse.jdt.core.tests.compiler/src/org/eclipse/jdt/core/tests/compiler/regression/ConstantTest.java (-1 / +1 lines)
Lines 1119-1125 Link Here
1119
		"1. ERROR in X.java (at line 4)\n" +
1119
		"1. ERROR in X.java (at line 4)\n" +
1120
		"	static final String notAConstant = null;\n" +
1120
		"	static final String notAConstant = null;\n" +
1121
		"	                    ^^^^^^^^^^^^\n" +
1121
		"	                    ^^^^^^^^^^^^\n" +
1122
		"The field notAConstant cannot be declared static; static fields can only be declared in static or top level types\n" +
1122
		"The field notAConstant cannot be declared static in a non-static inner type, unless initialized with a constant expression\n" +
1123
		"----------\n");
1123
		"----------\n");
1124
}
1124
}
1125
public void testAllConstants() {
1125
public void testAllConstants() {
(-)a/org.eclipse.jdt.core.tests.compiler/src/org/eclipse/jdt/core/tests/compiler/regression/EnumTest.java (-3 / +65 lines)
Lines 1-12 Link Here
1
/*******************************************************************************
1
/*******************************************************************************
2
 * Copyright (c) 2000, 2011 IBM Corporation and others.
2
 * Copyright (c) 2000, 2012 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
6
 * http://www.eclipse.org/legal/epl-v10.html
6
 * http://www.eclipse.org/legal/epl-v10.html
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 365519 - editorial cleanup after bug 186342 and bug 365387
10
 *******************************************************************************/
11
 *******************************************************************************/
11
package org.eclipse.jdt.core.tests.compiler.regression;
12
package org.eclipse.jdt.core.tests.compiler.regression;
12
13
Lines 15-20 Link Here
15
16
16
import junit.framework.Test;
17
import junit.framework.Test;
17
18
19
import org.eclipse.jdt.core.JavaCore;
18
import org.eclipse.jdt.core.ToolFactory;
20
import org.eclipse.jdt.core.ToolFactory;
19
import org.eclipse.jdt.core.tests.util.Util;
21
import org.eclipse.jdt.core.tests.util.Util;
20
import org.eclipse.jdt.core.util.ClassFileBytesDisassembler;
22
import org.eclipse.jdt.core.util.ClassFileBytesDisassembler;
Lines 3761-3767 Link Here
3761
		"1. ERROR in X.java (at line 3)\n" +
3763
		"1. ERROR in X.java (at line 3)\n" +
3762
		"	static int bar;\n" +
3764
		"	static int bar;\n" +
3763
		"	           ^^^\n" +
3765
		"	           ^^^\n" +
3764
		"The field bar cannot be declared static; static fields can only be declared in static or top level types\n" +
3766
		"The field bar cannot be declared static in a non-static inner type, unless initialized with a constant expression\n" +
3765
		"----------\n");
3767
		"----------\n");
3766
}
3768
}
3767
//https://bugs.eclipse.org/bugs/show_bug.cgi?id=99428 and https://bugs.eclipse.org/bugs/show_bug.cgi?id=99655
3769
//https://bugs.eclipse.org/bugs/show_bug.cgi?id=99428 and https://bugs.eclipse.org/bugs/show_bug.cgi?id=99655
Lines 6517-6522 Link Here
6517
		"",
6519
		"",
6518
		null);
6520
		null);
6519
}
6521
}
6522
// https://bugs.eclipse.org/bugs/show_bug.cgi?id=289892
6523
// in interaction with null annotations
6524
// see https://bugs.eclipse.org/bugs/show_bug.cgi?id=365519#c4 item (6) 
6525
public void test180a() {
6526
	Map options = getCompilerOptions();
6527
	options.put(JavaCore.COMPILER_ANNOTATION_NULL_ANALYSIS, JavaCore.ENABLED);
6528
	this.runConformTest(
6529
		new String[] {
6530
			"p/package-info.java",
6531
			"@p.Annot(state=p.MyEnum.BROKEN)\n" + 
6532
			"package p;",
6533
			"p/Annot.java",
6534
			"package p;\n" + 
6535
			"@Annot(state=MyEnum.KO)\n" + 
6536
			"public @interface Annot {\n" + 
6537
			"	MyEnum state() default MyEnum.KO;\n" + 
6538
			"}",
6539
			"p/MyEnum.java",
6540
			"package p;\n" + 
6541
			"@Annot(state=MyEnum.KO)\n" + 
6542
			"public enum MyEnum {\n" + 
6543
			"	WORKS, OK, KO, BROKEN, ;\n" + 
6544
			"}",
6545
			"test180/package-info.java",
6546
			"@p.Annot(state=p.MyEnum.OK)\n" + 
6547
			"package test180;",
6548
			"test180/Test.java",
6549
			"package test180;\n" +
6550
			"import p.MyEnum;\n" + 
6551
			"import p.Annot;\n" + 
6552
			"@Annot(state=MyEnum.OK)\n" + 
6553
			"public class Test {}",
6554
		},
6555
		"",
6556
		null,
6557
		true,
6558
		null,
6559
		options,
6560
		null
6561
	);
6562
	options = getCompilerOptions();
6563
	options.put(CompilerOptions.OPTION_Process_Annotations, CompilerOptions.ENABLED);
6564
	this.runConformTest(
6565
		false,
6566
		new String[] {
6567
			"X.java",
6568
			"import test180.Test;\n" +
6569
			"public class X {\n" + 
6570
			"	public static void main(String[] args) {\n" + 
6571
			"		System.out.println(Test.class);\n" + 
6572
			"	}\n" + 
6573
			"}"
6574
		},
6575
		null,
6576
		options,
6577
		"",
6578
		"class test180.Test",
6579
		"",
6580
		null);
6581
}
6520
//https://bugs.eclipse.org/bugs/show_bug.cgi?id=300133
6582
//https://bugs.eclipse.org/bugs/show_bug.cgi?id=300133
6521
public void test181() {
6583
public void test181() {
6522
	this.runConformTest(
6584
	this.runConformTest(
(-)a/org.eclipse.jdt.core.tests.compiler/src/org/eclipse/jdt/core/tests/compiler/regression/FlowAnalysisTest.java (-1 / +137 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 236385
10
 *     Stephan Herrmann - Contributions for
11
 *     							bug 236385 - [compiler] Warn for potential programming problem if an object is created but not used
12
 *      						bug 349326 - [1.7] new warning for missing try-with-resources
13
 *      						bug 360328 - [compiler][null] detect null problems in nested code (local class inside a loop)
11
 *******************************************************************************/
14
 *******************************************************************************/
12
package org.eclipse.jdt.core.tests.compiler.regression;
15
package org.eclipse.jdt.core.tests.compiler.regression;
13
16
Lines 28-33 Link Here
28
31
29
public class FlowAnalysisTest extends AbstractRegressionTest {
32
public class FlowAnalysisTest extends AbstractRegressionTest {
30
static {
33
static {
34
//	TESTS_NAMES = new String[] { "testLocalClassInInitializer1" };
31
//	TESTS_NUMBERS = new int[] { 69 };
35
//	TESTS_NUMBERS = new int[] { 69 };
32
}
36
}
33
public FlowAnalysisTest(String name) {
37
public FlowAnalysisTest(String name) {
Lines 2360-2365 Link Here
2360
		"The local variable i may not have been initialized\n" + 
2364
		"The local variable i may not have been initialized\n" + 
2361
		"----------\n");
2365
		"----------\n");
2362
}
2366
}
2367
// Bug 349326 - [1.7] new warning for missing try-with-resources
2368
// variant < 1.7 using Closeable: not closed
2369
public void testCloseable1() {
2370
	Map options = getCompilerOptions();
2371
	options.put(CompilerOptions.OPTION_ReportUnclosedCloseable, CompilerOptions.WARNING);
2372
	this.runNegativeTest(
2373
			new String[] {
2374
				"X.java",
2375
				"import java.io.File;\n" + 
2376
				"import java.io.FileReader;\n" + 
2377
				"import java.io.IOException;\n" + 
2378
				"public class X {\n" +
2379
				"    void foo() throws IOException {\n" +
2380
				"        File file = new File(\"somefile\");\n" + 
2381
				"        FileReader fileReader = new FileReader(file); // not closed\n" + 
2382
				"        char[] in = new char[50];\n" + 
2383
				"        fileReader.read(in);\n" + 
2384
				"    }\n" + 
2385
				"}\n"
2386
			}, 
2387
			"----------\n" + 
2388
			"1. WARNING in X.java (at line 7)\n" + 
2389
			"	FileReader fileReader = new FileReader(file); // not closed\n" + 
2390
			"	           ^^^^^^^^^^\n" + 
2391
			"Resource leak: 'fileReader' is never closed\n" + 
2392
			"----------\n",
2393
			null, true, options);	
2394
}
2395
// Bug 349326 - [1.7] new warning for missing try-with-resources
2396
// variant < 1.7 using Closeable: resource is closed, cannot suggest try-with-resources < 1.7
2397
public void testCloseable2() {
2398
	Map options = getCompilerOptions();
2399
	options.put(CompilerOptions.OPTION_ReportUnclosedCloseable, CompilerOptions.WARNING);
2400
	this.runConformTest(
2401
			new String[] {
2402
				"X.java",
2403
				"import java.io.File;\n" + 
2404
				"import java.io.FileReader;\n" + 
2405
				"import java.io.IOException;\n" + 
2406
				"public class X {\n" +
2407
				"    void foo() throws IOException {\n" +
2408
				"        File file = new File(\"somefile\");\n" + 
2409
				"        FileReader fileReader = new FileReader(file); // not closed\n" + 
2410
				"        char[] in = new char[50];\n" + 
2411
				"        fileReader.read(in);\n" +
2412
				"        fileReader.close();\n" + 
2413
				"    }\n" + 
2414
				"}\n"
2415
			}, 
2416
			"",
2417
			null, true, null, options, null);	
2418
}
2419
// Bug 360328 - [compiler][null] detect null problems in nested code (local class inside a loop)
2420
// return/break/continue inside anonymous class inside try-catch inside initializer
2421
public void testLocalClassInInitializer1() {
2422
	this.runConformTest(
2423
			new String[] {
2424
				"X.java",
2425
				"public class X {\n" +
2426
				"    static {\n" +
2427
				"        final int i=4;\n" +
2428
				"        try {\n" +
2429
				"            Runnable runner = new Runnable() {\n" +
2430
				"                public void run() {\n" +
2431
				"                    switch (i) {" +
2432
				"                        case 4: break;\n" +
2433
				"                    }\n" +
2434
				"                    int j = i;\n" +
2435
				"                    while (j++ < 10) {\n" +
2436
				"                        if (j == 2) continue;\n" +
2437
				"                        if (j == 4) break;\n" +
2438
				"                        if (j == 6) return;\n" +
2439
				"                    }\n" +
2440
				"                }\n" +
2441
				"            };\n" +
2442
				"        } catch (RuntimeException re) {}\n" +
2443
				"    }\n" +
2444
				"}\n"
2445
			}, 
2446
			"");
2447
}
2448
// Bug 360328 - [compiler][null] detect null problems in nested code (local class inside a loop)
2449
// break/continue illegally inside anonymous class inside loop (loop is out of scope for break/continue)
2450
public void testLocalClassInInitializer2() {
2451
	this.runNegativeTest(
2452
			new String[] {
2453
				"X.java",
2454
				"public class X {\n" +
2455
				"    void f () {\n" +
2456
				"        while (true) {\n" +
2457
				"            class Inner1 {\n" +
2458
				"                { if (true) break; }\n" +
2459
				"            }\n" +
2460
				"            new Inner1();\n" +
2461
				"        }\n" +
2462
				"    } \n" +
2463
				"    void g () {\n" +
2464
				"        outer: for (int i=1;true;i++) {\n" +
2465
				"            class Inner2 {\n" +
2466
				"                int j = 3;\n" +
2467
				"                void foo () {\n" +
2468
				"                  if (2 == j) continue outer;\n" +
2469
				"                  else continue;\n" +
2470
				"                }\n" +
2471
				"            }\n" +
2472
				"            new Inner2().foo();\n" +
2473
				"        }\n" +
2474
				"    } \n" +
2475
				"}\n"
2476
			}, 
2477
			"----------\n" + 
2478
			"1. ERROR in X.java (at line 5)\n" + 
2479
			"	{ if (true) break; }\n" + 
2480
			"	            ^^^^^^\n" + 
2481
			"break cannot be used outside of a loop or a switch\n" + 
2482
			"----------\n" + 
2483
			"2. WARNING in X.java (at line 11)\n" + 
2484
			"	outer: for (int i=1;true;i++) {\n" + 
2485
			"	^^^^^\n" + 
2486
			"The label outer is never explicitly referenced\n" + 
2487
			"----------\n" + 
2488
			"3. ERROR in X.java (at line 15)\n" + 
2489
			"	if (2 == j) continue outer;\n" + 
2490
			"	            ^^^^^^^^^^^^^^^\n" + 
2491
			"The label outer is missing\n" + 
2492
			"----------\n" + 
2493
			"4. ERROR in X.java (at line 16)\n" + 
2494
			"	else continue;\n" + 
2495
			"	     ^^^^^^^^^\n" + 
2496
			"continue cannot be used outside of a loop\n" + 
2497
			"----------\n");
2498
}
2363
public static Class testClass() {
2499
public static Class testClass() {
2364
	return FlowAnalysisTest.class;
2500
	return FlowAnalysisTest.class;
2365
}
2501
}
(-)a/org.eclipse.jdt.core.tests.compiler/src/org/eclipse/jdt/core/tests/compiler/regression/GenericsRegressionTest.java (-1 / +85 lines)
Lines 1-5 Link Here
1
/*******************************************************************************
1
/*******************************************************************************
2
 * Copyright (c) 2000, 2011 IBM Corporation and others.
2
 * Copyright (c) 2000, 2012 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 2465-2468 Link Here
2465
		"\'<>\' operator is not allowed for source level below 1.7\n" + 
2465
		"\'<>\' operator is not allowed for source level below 1.7\n" + 
2466
		"----------\n");
2466
		"----------\n");
2467
}
2467
}
2468
// https://bugs.eclipse.org/bugs/show_bug.cgi?id=366131
2469
public void test366131() {
2470
	this.runConformTest(
2471
		new String[] {
2472
			"X.java",
2473
			"public class X {\n" +
2474
			"    public static void main(String [] args) {\n" +
2475
			"        System.out.println(\"SUCCESS\");\n" +
2476
			"    }\n" +
2477
			"}\n" +
2478
			"class Range<T extends Comparable<? super T>> {\n" +
2479
			"    public boolean containsNC(T value) {\n" +
2480
			"        return false;\n" +
2481
			"    }\n" +
2482
			"}\n" +
2483
			"class NumberRange<T extends Number & Comparable<? super T>> extends Range<T> {\n" +
2484
			"    public boolean contains(Comparable<?> value) {\n" +
2485
			"        return castTo((Class) null).containsNC((Comparable) null);\n" +
2486
			"    }\n" +
2487
			"    public <N extends Number & Comparable<? super N>> NumberRange<N>\n" +
2488
			"castTo(Class<N> type) {\n" +
2489
			"        return null;\n" +
2490
			"    }\n" +
2491
			"}\n",
2492
		},
2493
		"SUCCESS");
2494
}
2495
// https://bugs.eclipse.org/bugs/show_bug.cgi?id=366131
2496
public void test366131b() {
2497
	this.runNegativeTest(
2498
		new String[] {
2499
			"X.java",
2500
			"public class X {\n" +
2501
			"    public static void main(String [] args) {\n" +
2502
			"        Zork z;\n" +
2503
			"    }\n" +
2504
			"}\n" +
2505
			"class Range<T extends Comparable<? super T>> {\n" +
2506
			"    public boolean containsNC(T value) {\n" +
2507
			"        return false;\n" +
2508
			"    }\n" +
2509
			"}\n" +
2510
			"class NumberRange<T extends Number & Comparable<? super T>> extends Range<T> {\n" +
2511
			"    public boolean contains(Comparable<?> value) {\n" +
2512
			"        return castTo((Class) null).containsNC((Comparable) null);\n" +
2513
			"    }\n" +
2514
			"    public <N extends Number & Comparable<? super N>> NumberRange<N>\n" +
2515
			"castTo(Class<N> type) {\n" +
2516
			"        return null;\n" +
2517
			"    }\n" +
2518
			"}\n",
2519
		},
2520
		"----------\n" + 
2521
		"1. ERROR in X.java (at line 3)\n" + 
2522
		"	Zork z;\n" + 
2523
		"	^^^^\n" + 
2524
		"Zork cannot be resolved to a type\n" + 
2525
		"----------\n" + 
2526
		"2. WARNING in X.java (at line 13)\n" + 
2527
		"	return castTo((Class) null).containsNC((Comparable) null);\n" + 
2528
		"	       ^^^^^^^^^^^^^^^^^^^^\n" + 
2529
		"Type safety: Unchecked invocation castTo(Class) of the generic method castTo(Class<N>) of type NumberRange<T>\n" + 
2530
		"----------\n" + 
2531
		"3. WARNING in X.java (at line 13)\n" + 
2532
		"	return castTo((Class) null).containsNC((Comparable) null);\n" + 
2533
		"	       ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^\n" + 
2534
		"Type safety: The method containsNC(Comparable) belongs to the raw type Range. References to generic type Range<T> should be parameterized\n" + 
2535
		"----------\n" + 
2536
		"4. WARNING in X.java (at line 13)\n" + 
2537
		"	return castTo((Class) null).containsNC((Comparable) null);\n" + 
2538
		"	              ^^^^^^^^^^^^\n" + 
2539
		"Type safety: The expression of type Class needs unchecked conversion to conform to Class<Number&Comparable<? super Number&Comparable<? super N>>>\n" + 
2540
		"----------\n" + 
2541
		"5. WARNING in X.java (at line 13)\n" + 
2542
		"	return castTo((Class) null).containsNC((Comparable) null);\n" + 
2543
		"	               ^^^^^\n" + 
2544
		"Class is a raw type. References to generic type Class<T> should be parameterized\n" + 
2545
		"----------\n" + 
2546
		"6. WARNING in X.java (at line 13)\n" + 
2547
		"	return castTo((Class) null).containsNC((Comparable) null);\n" + 
2548
		"	                                        ^^^^^^^^^^\n" + 
2549
		"Comparable is a raw type. References to generic type Comparable<T> should be parameterized\n" + 
2550
		"----------\n");
2551
}
2468
}
2552
}
(-)a/org.eclipse.jdt.core.tests.compiler/src/org/eclipse/jdt/core/tests/compiler/regression/GenericsRegressionTest_1_7.java (+22 lines)
Lines 2302-2307 Link Here
2302
		false,
2302
		false,
2303
		customOptions);
2303
		customOptions);
2304
}
2304
}
2305
// https://bugs.eclipse.org/bugs/show_bug.cgi?id=361441
2306
public void test0061() {
2307
	this.runNegativeTest(
2308
		new String[] {
2309
			"X.java",
2310
			"import java.net.URI;" +
2311
			"import java.nio.file.FileSystems;" +
2312
			"import java.util.Collections;\n" +
2313
			"public class X {\n" +
2314
			"	 public static void foo() {\n" +
2315
			"    	URI uri = URI.create(\"http://www.eclipse.org\");\n" +
2316
			"		FileSystems.<String, Object>newFileSystem(uri, Collections.emptyMap());\n" +
2317
			"	 }\n" +
2318
			"}\n"
2319
		},
2320
		"----------\n" + 
2321
		"1. ERROR in X.java (at line 5)\n" + 
2322
		"	FileSystems.<String, Object>newFileSystem(uri, Collections.emptyMap());\n" + 
2323
		"	                            ^^^^^^^^^^^^^\n" + 
2324
		"The method newFileSystem(URI, Map<String,?>) in the type FileSystems is not applicable for the arguments (URI, Map<Object,Object>)\n" + 
2325
		"----------\n");
2326
}
2305
public static Class testClass() {
2327
public static Class testClass() {
2306
	return GenericsRegressionTest_1_7.class;
2328
	return GenericsRegressionTest_1_7.class;
2307
}
2329
}
(-)a/org.eclipse.jdt.core.tests.compiler/src/org/eclipse/jdt/core/tests/compiler/regression/LookupTest.java (-1 / +31 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 3459-3464 Link Here
3459
		"The value of the field A.C.x is not used\n" + 
3459
		"The value of the field A.C.x is not used\n" + 
3460
		"----------\n");
3460
		"----------\n");
3461
}
3461
}
3462
// https://bugs.eclipse.org/bugs/show_bug.cgi?id=350738
3463
public void test106() {
3464
	if (this.complianceLevel < ClassFileConstants.JDK1_5)
3465
		return;
3466
	this.runNegativeTest(
3467
		new String[] {
3468
			"X.java",//------------------------------
3469
			"import java.util.List;\n" +
3470
			"import java.util.Set;\n" +
3471
			"public class X {\n" +
3472
			"	private static List<Object> foo1(Set<Object> set) {\n" +
3473
			"	    return foo1(set);\n" +
3474
			"	}\n" +
3475
			"	private static <T> List<T> foo3(Set<T> set) {\n" +
3476
			"	    return foo3(set);\n" +
3477
			"	}\n" +
3478
			"}\n",
3479
		},
3480
		"----------\n" + 
3481
		"1. WARNING in X.java (at line 4)\n" + 
3482
		"	private static List<Object> foo1(Set<Object> set) {\n" + 
3483
		"	                            ^^^^^^^^^^^^^^^^^^^^^\n" + 
3484
		"The method foo1(Set<Object>) from the type X is never used locally\n" + 
3485
		"----------\n" + 
3486
		"2. WARNING in X.java (at line 7)\n" + 
3487
		"	private static <T> List<T> foo3(Set<T> set) {\n" + 
3488
		"	                           ^^^^^^^^^^^^^^^^\n" + 
3489
		"The method foo3(Set<T>) from the type X is never used locally\n" + 
3490
		"----------\n");
3491
}
3462
public static Class testClass() {	return LookupTest.class;
3492
public static Class testClass() {	return LookupTest.class;
3463
}
3493
}
3464
}
3494
}
(-)a/org.eclipse.jdt.core.tests.compiler/src/org/eclipse/jdt/core/tests/compiler/regression/MethodVerifyTest.java (-40 / +338 lines)
Lines 1-5 Link Here
1
/*******************************************************************************
1
/*******************************************************************************
2
 * Copyright (c) 2000, 2011 IBM Corporation and others.
2
 * Copyright (c) 2000, 2012 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 2330-2347 Link Here
2330
	// https://bugs.eclipse.org/bugs/show_bug.cgi?id=83162
2330
	// https://bugs.eclipse.org/bugs/show_bug.cgi?id=83162
2331
	public void test036d() { // 2 interface cases
2331
	public void test036d() { // 2 interface cases
2332
		// in these cases, bridge methods are needed once abstract/concrete methods are defiined (either in the abstract class or a concrete subclass)
2332
		// in these cases, bridge methods are needed once abstract/concrete methods are defiined (either in the abstract class or a concrete subclass)
2333
		this.runConformTest(
2333
		if (this.complianceLevel < ClassFileConstants.JDK1_7) {
2334
			new String[] {
2334
			this.runConformTest(
2335
				"Y.java",
2335
					new String[] {
2336
				"abstract class Y implements Equivalent<String>, EqualityComparable<Integer> {\n" +
2336
							"Y.java",
2337
				"	public abstract boolean equalTo(Number other);\n" +
2337
							"abstract class Y implements Equivalent<String>, EqualityComparable<Integer> {\n" +
2338
				"}\n" +
2338
									"	public abstract boolean equalTo(Number other);\n" +
2339
				"interface Equivalent<T> { boolean equalTo(T other); }\n" +
2339
									"}\n" +
2340
				"interface EqualityComparable<T> { boolean equalTo(T other); }\n"
2340
									"interface Equivalent<T> { boolean equalTo(T other); }\n" +
2341
			},
2341
									"interface EqualityComparable<T> { boolean equalTo(T other); }\n"
2342
			""
2342
					},
2343
			// no bridge methods are created here since Y does not define an equalTo(?) method which equals an inherited equalTo method
2343
					""
2344
		);
2344
					// no bridge methods are created here since Y does not define an equalTo(?) method which equals an inherited equalTo method
2345
					);
2346
		} else {
2347
			this.runNegativeTest(
2348
					new String[] {
2349
							"Y.java",
2350
							"abstract class Y implements Equivalent<String>, EqualityComparable<Integer> {\n" +
2351
									"	public abstract boolean equalTo(Number other);\n" +
2352
									"}\n" +
2353
									"interface Equivalent<T> { boolean equalTo(T other); }\n" +
2354
									"interface EqualityComparable<T> { boolean equalTo(T other); }\n"
2355
					},
2356
					"----------\n" + 
2357
					"1. ERROR in Y.java (at line 1)\n" + 
2358
					"	abstract class Y implements Equivalent<String>, EqualityComparable<Integer> {\n" + 
2359
					"	               ^\n" + 
2360
					"Name clash: The method equalTo(T) of type Equivalent<T> has the same erasure as equalTo(T) of type EqualityComparable<T> but does not override it\n" + 
2361
					"----------\n");
2362
		}
2345
	}
2363
	}
2346
	// https://bugs.eclipse.org/bugs/show_bug.cgi?id=83162
2364
	// https://bugs.eclipse.org/bugs/show_bug.cgi?id=83162
2347
	public void test036e() { // 2 interface cases
2365
	public void test036e() { // 2 interface cases
Lines 2354-2359 Link Here
2354
				"interface Equivalent<T> { boolean equalTo(T other); }\n" +
2372
				"interface Equivalent<T> { boolean equalTo(T other); }\n" +
2355
				"interface EqualityComparable<T> { boolean equalTo(T other); }\n"
2373
				"interface EqualityComparable<T> { boolean equalTo(T other); }\n"
2356
			},
2374
			},
2375
			this.complianceLevel < ClassFileConstants.JDK1_7 ?
2357
			"----------\n" +
2376
			"----------\n" +
2358
			"1. ERROR in Y.java (at line 2)\n" +
2377
			"1. ERROR in Y.java (at line 2)\n" +
2359
			"	public abstract boolean equalTo(Object other);\n" +
2378
			"	public abstract boolean equalTo(Object other);\n" +
Lines 2364-2371 Link Here
2364
			"	public abstract boolean equalTo(Object other);\n" +
2383
			"	public abstract boolean equalTo(Object other);\n" +
2365
			"	                        ^^^^^^^^^^^^^^^^^^^^^\n" +
2384
			"	                        ^^^^^^^^^^^^^^^^^^^^^\n" +
2366
			"Name clash: The method equalTo(Object) of type Y has the same erasure as equalTo(T) of type EqualityComparable<T> but does not override it\n" +
2385
			"Name clash: The method equalTo(Object) of type Y has the same erasure as equalTo(T) of type EqualityComparable<T> but does not override it\n" +
2367
			"----------\n"
2386
			"----------\n" :
2368
			// name clash: equalTo(java.lang.Object) in Y and equalTo(T) in Equivalent<java.lang.String> have the same erasure, yet neither overrides the other
2387
			// name clash: equalTo(java.lang.Object) in Y and equalTo(T) in Equivalent<java.lang.String> have the same erasure, yet neither overrides the other
2388
			"----------\n" + 
2389
			"1. ERROR in Y.java (at line 1)\n" + 
2390
			"	abstract class Y implements Equivalent<String>, EqualityComparable<Integer> {\n" + 
2391
			"	               ^\n" + 
2392
			"Name clash: The method equalTo(T) of type Equivalent<T> has the same erasure as equalTo(T) of type EqualityComparable<T> but does not override it\n" + 
2393
			"----------\n" + 
2394
			"2. ERROR in Y.java (at line 2)\n" + 
2395
			"	public abstract boolean equalTo(Object other);\n" + 
2396
			"	                        ^^^^^^^^^^^^^^^^^^^^^\n" + 
2397
			"Name clash: The method equalTo(Object) of type Y has the same erasure as equalTo(T) of type Equivalent<T> but does not override it\n" + 
2398
			"----------\n" + 
2399
			"3. ERROR in Y.java (at line 2)\n" + 
2400
			"	public abstract boolean equalTo(Object other);\n" + 
2401
			"	                        ^^^^^^^^^^^^^^^^^^^^^\n" + 
2402
			"Name clash: The method equalTo(Object) of type Y has the same erasure as equalTo(T) of type EqualityComparable<T> but does not override it\n" + 
2403
			"----------\n"
2369
		);
2404
		);
2370
	}
2405
	}
2371
	// https://bugs.eclipse.org/bugs/show_bug.cgi?id=83162
2406
	// https://bugs.eclipse.org/bugs/show_bug.cgi?id=83162
Lines 2428-2433 Link Here
2428
				"interface K extends I { void foo(A<String> a); }\n" +
2463
				"interface K extends I { void foo(A<String> a); }\n" +
2429
				"class A<T> {}"
2464
				"class A<T> {}"
2430
			},
2465
			},
2466
			this.complianceLevel < ClassFileConstants.JDK1_7 ? 
2431
			"----------\n" + 
2467
			"----------\n" + 
2432
			"1. WARNING in X.java (at line 4)\n" + 
2468
			"1. WARNING in X.java (at line 4)\n" + 
2433
			"	class YYY implements J, I { public void foo(A a) {} }\n" + 
2469
			"	class YYY implements J, I { public void foo(A a) {} }\n" + 
Lines 2453-2459 Link Here
2453
			"	interface K extends I { void foo(A<String> a); }\n" + 
2489
			"	interface K extends I { void foo(A<String> a); }\n" + 
2454
			"	                             ^^^^^^^^^^^^^^^^\n" + 
2490
			"	                             ^^^^^^^^^^^^^^^^\n" + 
2455
			"Name clash: The method foo(A<String>) of type K has the same erasure as foo(A) of type I but does not override it\n" + 
2491
			"Name clash: The method foo(A<String>) of type K has the same erasure as foo(A) of type I but does not override it\n" + 
2456
			"----------\n");
2492
			"----------\n" : 
2493
				"----------\n" + 
2494
				"1. ERROR in X.java (at line 2)\n" + 
2495
				"	abstract class Y implements J, I { }\n" + 
2496
				"	               ^\n" + 
2497
				"Name clash: The method foo(A<String>) of type J has the same erasure as foo(A) of type I but does not override it\n" + 
2498
				"----------\n" + 
2499
				"2. WARNING in X.java (at line 4)\n" + 
2500
				"	class YYY implements J, I { public void foo(A a) {} }\n" + 
2501
				"	                                            ^\n" + 
2502
				"A is a raw type. References to generic type A<T> should be parameterized\n" + 
2503
				"----------\n" + 
2504
				"3. WARNING in X.java (at line 5)\n" + 
2505
				"	class XXX implements I, J { public void foo(A a) {} }\n" + 
2506
				"	                                            ^\n" + 
2507
				"A is a raw type. References to generic type A<T> should be parameterized\n" + 
2508
				"----------\n" + 
2509
				"4. WARNING in X.java (at line 6)\n" + 
2510
				"	class ZZZ implements K { public void foo(A a) {} }\n" + 
2511
				"	                                         ^\n" + 
2512
				"A is a raw type. References to generic type A<T> should be parameterized\n" + 
2513
				"----------\n" + 
2514
				"5. WARNING in X.java (at line 7)\n" + 
2515
				"	interface I { void foo(A a); }\n" + 
2516
				"	                       ^\n" + 
2517
				"A is a raw type. References to generic type A<T> should be parameterized\n" + 
2518
				"----------\n" + 
2519
				"6. ERROR in X.java (at line 9)\n" + 
2520
				"	interface K extends I { void foo(A<String> a); }\n" + 
2521
				"	                             ^^^^^^^^^^^^^^^^\n" + 
2522
				"Name clash: The method foo(A<String>) of type K has the same erasure as foo(A) of type I but does not override it\n" + 
2523
				"----------\n");
2457
	}
2524
	}
2458
	public void test037a() { // test inheritance scenarios
2525
	public void test037a() { // test inheritance scenarios
2459
		this.runNegativeTest(
2526
		this.runNegativeTest(
Lines 11238-11262 Link Here
11238
}
11305
}
11239
//https://bugs.eclipse.org/bugs/show_bug.cgi?id=285088
11306
//https://bugs.eclipse.org/bugs/show_bug.cgi?id=285088
11240
public void test200() {
11307
public void test200() {
11241
	Map options = getCompilerOptions();
11308
	String errorMessage =
11242
	String compliance = (String) options.get(JavaCore.COMPILER_COMPLIANCE);
11243
	String errorMessage = compliance == JavaCore.VERSION_1_6 ?
11244
			"----------\n" + 
11245
			"1. WARNING in X.java (at line 3)\n" + 
11246
			"	int foo(Collection bar) { return 0; }\n" + 
11247
			"	    ^^^^^^^^^^^^^^^^^^^\n" + 
11248
			"Method foo(Collection) has the same erasure foo(Collection<E>) as another method in type X\n" + 
11249
			"----------\n" + 
11250
			"2. WARNING in X.java (at line 3)\n" + 
11251
			"	int foo(Collection bar) { return 0; }\n" + 
11252
			"	        ^^^^^^^^^^\n" + 
11253
			"Collection is a raw type. References to generic type Collection<E> should be parameterized\n" + 
11254
			"----------\n" + 
11255
			"3. WARNING in X.java (at line 4)\n" + 
11256
			"	double foo(Collection<String> bar) {return 0; }\n" + 
11257
			"	       ^^^^^^^^^^^^^^^^^^^^^^^^^^^\n" + 
11258
			"Method foo(Collection<String>) has the same erasure foo(Collection<E>) as another method in type X\n" + 
11259
			"----------\n" :
11260
				"----------\n" + 
11309
				"----------\n" + 
11261
				"1. ERROR in X.java (at line 3)\n" + 
11310
				"1. ERROR in X.java (at line 3)\n" + 
11262
				"	int foo(Collection bar) { return 0; }\n" + 
11311
				"	int foo(Collection bar) { return 0; }\n" + 
Lines 13439-13445 Link Here
13439
	String output = this.complianceLevel == ClassFileConstants.JDK1_6 ?
13488
	String output = this.complianceLevel == ClassFileConstants.JDK1_6 ?
13440
			"----------\n" + 
13489
			"----------\n" + 
13441
			"1. WARNING in Test.java (at line 3)\n" + 
13490
			"1. WARNING in Test.java (at line 3)\n" + 
13442
			"	public class Test<Key, Value> extends LinkedHashMap<Key, Collection<Value>> {\n" + 
13491
			"	public class Test<Key, Value> extends HashMap<Key, Collection<Value>> {\n" + 
13443
			"	             ^^^^\n" + 
13492
			"	             ^^^^\n" + 
13444
			"The serializable class Test does not declare a static final serialVersionUID field of type long\n" + 
13493
			"The serializable class Test does not declare a static final serialVersionUID field of type long\n" + 
13445
			"----------\n" + 
13494
			"----------\n" + 
Lines 13451-13457 Link Here
13451
			"3. WARNING in Test.java (at line 5)\n" + 
13500
			"3. WARNING in Test.java (at line 5)\n" + 
13452
			"	public Collection<Value> get(Key k) { return null; }\n" + 
13501
			"	public Collection<Value> get(Key k) { return null; }\n" + 
13453
			"	                         ^^^^^^^^^^\n" + 
13502
			"	                         ^^^^^^^^^^\n" + 
13454
			"Name clash: The method get(Key) of type Test<Key,Value> has the same erasure as get(Object) of type LinkedHashMap<K,V> but does not override it\n" + 
13503
			"Name clash: The method get(Key) of type Test<Key,Value> has the same erasure as get(Object) of type HashMap<K,V> but does not override it\n" + 
13455
			"----------\n" + 
13504
			"----------\n" + 
13456
			"4. ERROR in Test.java (at line 6)\n" + 
13505
			"4. ERROR in Test.java (at line 6)\n" + 
13457
			"	Zork z;\n" + 
13506
			"	Zork z;\n" + 
Lines 13460-13466 Link Here
13460
			"----------\n":
13509
			"----------\n":
13461
				"----------\n" + 
13510
				"----------\n" + 
13462
				"1. WARNING in Test.java (at line 3)\n" + 
13511
				"1. WARNING in Test.java (at line 3)\n" + 
13463
				"	public class Test<Key, Value> extends LinkedHashMap<Key, Collection<Value>> {\n" + 
13512
				"	public class Test<Key, Value> extends HashMap<Key, Collection<Value>> {\n" + 
13464
				"	             ^^^^\n" + 
13513
				"	             ^^^^\n" + 
13465
				"The serializable class Test does not declare a static final serialVersionUID field of type long\n" + 
13514
				"The serializable class Test does not declare a static final serialVersionUID field of type long\n" + 
13466
				"----------\n" + 
13515
				"----------\n" + 
Lines 13472-13478 Link Here
13472
				"3. ERROR in Test.java (at line 5)\n" + 
13521
				"3. ERROR in Test.java (at line 5)\n" + 
13473
				"	public Collection<Value> get(Key k) { return null; }\n" + 
13522
				"	public Collection<Value> get(Key k) { return null; }\n" + 
13474
				"	                         ^^^^^^^^^^\n" + 
13523
				"	                         ^^^^^^^^^^\n" + 
13475
				"Name clash: The method get(Key) of type Test<Key,Value> has the same erasure as get(Object) of type LinkedHashMap<K,V> but does not override it\n" + 
13524
				"Name clash: The method get(Key) of type Test<Key,Value> has the same erasure as get(Object) of type HashMap<K,V> but does not override it\n" + 
13476
				"----------\n" + 
13525
				"----------\n" + 
13477
				"4. ERROR in Test.java (at line 6)\n" + 
13526
				"4. ERROR in Test.java (at line 6)\n" + 
13478
				"	Zork z;\n" + 
13527
				"	Zork z;\n" + 
Lines 13483-13490 Link Here
13483
		new String[] {
13532
		new String[] {
13484
			"Test.java",
13533
			"Test.java",
13485
			"import java.util.Collection;\n" +
13534
			"import java.util.Collection;\n" +
13486
			"import java.util.LinkedHashMap;\n" +
13535
			"import java.util.HashMap;\n" +
13487
			"public class Test<Key, Value> extends LinkedHashMap<Key, Collection<Value>> {\n" +
13536
			"public class Test<Key, Value> extends HashMap<Key, Collection<Value>> {\n" +
13488
			"    public Collection<Value> put(Key k, Value v) { return null; }\n" +
13537
			"    public Collection<Value> put(Key k, Value v) { return null; }\n" +
13489
			"	 public Collection<Value> get(Key k) { return null; }\n" +
13538
			"	 public Collection<Value> get(Key k) { return null; }\n" +
13490
			"	 Zork z;\n" +
13539
			"	 Zork z;\n" +
Lines 13512-13515 Link Here
13512
		"Name clash: The method foo(A<Integer>) of type Sub has the same erasure as foo(A<Number>) of type Super but does not hide it\n" + 
13561
		"Name clash: The method foo(A<Integer>) of type Sub has the same erasure as foo(A<Number>) of type Super but does not hide it\n" + 
13513
		"----------\n");
13562
		"----------\n");
13514
}
13563
}
13564
// https://bugs.eclipse.org/bugs/show_bug.cgi?id=355838
13565
public void testBug355838() throws Exception {
13566
	String output = 		
13567
			"----------\n" + 
13568
			"1. ERROR in ErasureBug.java (at line 4)\n" + 
13569
			"	public String output(List<String> integers) {\n" + 
13570
			"	              ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^\n" + 
13571
			"Method output(List<String>) has the same erasure output(List<E>) as another method in type ErasureBug\n" + 
13572
			"----------\n" + 
13573
			"2. ERROR in ErasureBug.java (at line 7)\n" + 
13574
			"	public String output(List doubles) {\n" + 
13575
			"	              ^^^^^^^^^^^^^^^^^^^^\n" + 
13576
			"Method output(List) has the same erasure output(List<E>) as another method in type ErasureBug\n" + 
13577
			"----------\n" + 
13578
			"3. WARNING in ErasureBug.java (at line 7)\n" + 
13579
			"	public String output(List doubles) {\n" + 
13580
			"	                     ^^^^\n" + 
13581
			"List is a raw type. References to generic type List<E> should be parameterized\n" + 
13582
			"----------\n" + 
13583
			"4. WARNING in ErasureBug.java (at line 10)\n" + 
13584
			"	public static void main(String[] args) { new ErasureBug().output(new ArrayList()); }\n" + 
13585
			"	                                                                 ^^^^^^^^^^^^^^^\n" + 
13586
			"Type safety: The expression of type ArrayList needs unchecked conversion to conform to List<String>\n" + 
13587
			"----------\n" + 
13588
			"5. WARNING in ErasureBug.java (at line 10)\n" + 
13589
			"	public static void main(String[] args) { new ErasureBug().output(new ArrayList()); }\n" + 
13590
			"	                                                                     ^^^^^^^^^\n" + 
13591
			"ArrayList is a raw type. References to generic type ArrayList<E> should be parameterized\n" + 
13592
			"----------\n";
13593
	this.runNegativeTest(
13594
		new String[] {
13595
			"ErasureBug.java",
13596
			"import java.util.ArrayList;\n" +
13597
			"import java.util.List;\n" +
13598
			"public class ErasureBug {\n" +
13599
			"    public String output(List<String> integers) {\n" +
13600
			"		return \"1\";\n" +
13601
			"	 }\n" +
13602
			"    public String output(List doubles) {\n" +
13603
			"		return \"2\";\n" +
13604
			"	 }\n" +
13605
			"	 public static void main(String[] args) { new ErasureBug().output(new ArrayList()); }\n" +
13606
			"}\n"
13607
		},
13608
		output);
13609
}
13610
// https://bugs.eclipse.org/bugs/show_bug.cgi?id=288658, make sure a bridge method
13611
// is generated when a public method is inherited from a non-public class into a
13612
// public class if the non public class happens to be defined in a named package.
13613
public void test288658() {
13614
	this.runConformTest(
13615
		new String[] {
13616
			"pkg/Test.java",
13617
			"package pkg;\n" +
13618
			"import java.lang.annotation.Annotation;\n"+ 
13619
			"import java.lang.annotation.Retention;\n"+ 
13620
			"import java.lang.annotation.RetentionPolicy;\n"+ 
13621
			"import java.lang.reflect.Method;\n"+ 
13622
			"\n"+ 
13623
			"public class Test extends Super {\n"+ 
13624
			"    public static void main(String[] args) {\n"+ 
13625
			"        try {\n"+ 
13626
			"            Method m = Test.class.getMethod(\"setFoo\", String.class);\n"+
13627
			"            Annotation a = m.getAnnotation(Anno.class);\n"+ 
13628
			"            System.out.println(\"Annotation was \" + (a == null ? \"not \" : \"\") +\n"+ 
13629
			"\"found\");\n"+ 
13630
			"        } catch (Exception e) {\n"+ 
13631
			"            e.printStackTrace();\n"+ 
13632
			"        }\n"+ 
13633
			"    }\n"+ 
13634
			"}\n"+ 
13635
			"\n"+ 
13636
			"class Super {\n"+ 
13637
			"    @Anno\n"+ 
13638
			"    public void setFoo(String foo) {}\n"+ 
13639
			"}\n"+ 
13640
			"\n"+ 
13641
			"@Retention(RetentionPolicy.RUNTIME)\n"+ 
13642
			"@interface Anno {\n"+ 
13643
			"\n"+ 
13644
			"}\n"
13645
		},
13646
		this.complianceLevel <= ClassFileConstants.JDK1_5 ? "Annotation was found" : "Annotation was not found");
13647
}
13648
// https://bugs.eclipse.org/bugs/show_bug.cgi?id=288658, make sure a bridge method
13649
// is generated when a public method is inherited from a non-public class into a
13650
// public class if the non public class happens to be defined in a named package.
13651
public void test288658a() {
13652
	this.runConformTest(
13653
		new String[] {
13654
			"pkg/Test.java",
13655
			"package pkg;\n" +
13656
			"import java.lang.annotation.Annotation;\n"+ 
13657
			"import java.lang.annotation.Retention;\n"+ 
13658
			"import java.lang.annotation.RetentionPolicy;\n"+ 
13659
			"import java.lang.reflect.Method;\n"+ 
13660
			"\n"+ 
13661
			"public class Test extends Super {\n"+
13662
			"    public void setFoo() {}\n" +
13663
			"    public static void main(String[] args) {\n"+ 
13664
			"        try {\n"+ 
13665
			"            Method m = Test.class.getMethod(\"setFoo\", String.class);\n"+
13666
			"            Annotation a = m.getAnnotation(Anno.class);\n"+ 
13667
			"            System.out.println(\"Annotation was \" + (a == null ? \"not \" : \"\") +\n"+ 
13668
			"\"found\");\n"+ 
13669
			"        } catch (Exception e) {\n"+ 
13670
			"            e.printStackTrace();\n"+ 
13671
			"        }\n"+ 
13672
			"    }\n"+ 
13673
			"}\n"+ 
13674
			"\n"+ 
13675
			"class Super {\n"+ 
13676
			"    @Anno\n"+ 
13677
			"    public void setFoo(String foo) {}\n"+ 
13678
			"}\n"+ 
13679
			"\n"+ 
13680
			"@Retention(RetentionPolicy.RUNTIME)\n"+ 
13681
			"@interface Anno {\n"+ 
13682
			"\n"+ 
13683
			"}\n"
13684
		},
13685
		this.complianceLevel <= ClassFileConstants.JDK1_5 ? "Annotation was found" : "Annotation was not found");
13686
}
13687
// https://bugs.eclipse.org/bugs/show_bug.cgi?id=354229
13688
public void test354229() {
13689
	this.runNegativeTest(
13690
		new String[] {
13691
			"X.java",
13692
			"import java.util.*;\n" +
13693
			"interface A {\n" +
13694
			"int get(List<String> l);\n" +
13695
			"}\n" +
13696
			"interface B  {\n" +
13697
			"int get(List<Integer> l);\n" +
13698
			"}\n" +
13699
			"interface C  extends A, B { \n" +
13700
			"//int get(List l);      // name clash error here\n" +
13701
			"    Zork z;\n" +
13702
			"}\n"
13703
		},
13704
		this.complianceLevel <= ClassFileConstants.JDK1_6 ?
13705
				"----------\n" + 
13706
				"1. ERROR in X.java (at line 10)\n" + 
13707
				"	Zork z;\n" + 
13708
				"	^^^^\n" + 
13709
				"Zork cannot be resolved to a type\n" + 
13710
				"----------\n" :
13711
					"----------\n" + 
13712
					"1. ERROR in X.java (at line 8)\n" + 
13713
					"	interface C  extends A, B { \n" + 
13714
					"	          ^\n" + 
13715
					"Name clash: The method get(List<String>) of type A has the same erasure as get(List<Integer>) of type B but does not override it\n" + 
13716
					"----------\n" + 
13717
					"2. ERROR in X.java (at line 10)\n" + 
13718
					"	Zork z;\n" + 
13719
					"	^^^^\n" + 
13720
					"Zork cannot be resolved to a type\n" + 
13721
					"----------\n");
13722
}
13723
// https://bugs.eclipse.org/bugs/show_bug.cgi?id=354229
13724
public void test354229b() {
13725
	this.runNegativeTest(
13726
		new String[] {
13727
			"X.java",
13728
			"import java.util.*;\n" +
13729
			"interface A {\n" +
13730
			"int get(List<String> l);\n" +
13731
			"}\n" +
13732
			"interface B  {\n" +
13733
			"int get(List<Integer> l);\n" +
13734
			"}\n" +
13735
			"interface C  extends A, B { \n" +
13736
			"    int get(List l);      // name clash error here\n" +
13737
			"    Zork z;\n" +
13738
			"}\n"
13739
		},
13740
		"----------\n" + 
13741
		"1. WARNING in X.java (at line 9)\n" + 
13742
		"	int get(List l);      // name clash error here\n" + 
13743
		"	        ^^^^\n" + 
13744
		"List is a raw type. References to generic type List<E> should be parameterized\n" + 
13745
		"----------\n" + 
13746
		"2. ERROR in X.java (at line 10)\n" + 
13747
		"	Zork z;\n" + 
13748
		"	^^^^\n" + 
13749
		"Zork cannot be resolved to a type\n" + 
13750
		"----------\n");
13751
}
13752
// https://bugs.eclipse.org/bugs/show_bug.cgi?id=354229
13753
public void test354229c() {
13754
	this.runNegativeTest(
13755
		new String[] {
13756
			"X.java",
13757
			"interface X {\n" +
13758
			"    <T> T e(Action<T> p);\n" +
13759
			"}\n" +
13760
			"interface Y {\n" +
13761
			"    <S, T> S e(Action<S> t);\n" +
13762
			"}\n" +
13763
			"interface E extends X, Y {\n" +
13764
			"}\n" +
13765
			"class Action<T> {\n" +
13766
			"    Zork z;\n" +
13767
			"}\n"
13768
13769
		},
13770
		this.complianceLevel < ClassFileConstants.JDK1_7 ? 
13771
				"----------\n" + 
13772
				"1. ERROR in X.java (at line 10)\n" + 
13773
				"	Zork z;\n" + 
13774
				"	^^^^\n" + 
13775
				"Zork cannot be resolved to a type\n" + 
13776
				"----------\n" : 
13777
					"----------\n" + 
13778
					"1. ERROR in X.java (at line 7)\n" + 
13779
					"	interface E extends X, Y {\n" + 
13780
					"	          ^\n" + 
13781
					"Name clash: The method e(Action<T>) of type X has the same erasure as e(Action<S>) of type Y but does not override it\n" + 
13782
					"----------\n" + 
13783
					"2. ERROR in X.java (at line 10)\n" + 
13784
					"	Zork z;\n" + 
13785
					"	^^^^\n" + 
13786
					"Zork cannot be resolved to a type\n" + 
13787
					"----------\n");
13788
}
13789
// https://bugs.eclipse.org/bugs/show_bug.cgi?id=354229
13790
public void test354229d() {
13791
	this.runNegativeTest(
13792
		new String[] {
13793
			"X.java",
13794
			"interface X {\n" +
13795
			"    <T> T e(Action<T> p);\n" +
13796
			"    <S, T> S e(Action<S> t);\n" +
13797
			"}\n" +
13798
			"class Action<T> {\n" +
13799
			"}\n"
13800
		},
13801
		"----------\n" + 
13802
		"1. ERROR in X.java (at line 2)\n" + 
13803
		"	<T> T e(Action<T> p);\n" + 
13804
		"	      ^^^^^^^^^^^^^^\n" + 
13805
		"Method e(Action<T>) has the same erasure e(Action<T>) as another method in type X\n" + 
13806
		"----------\n" + 
13807
		"2. ERROR in X.java (at line 3)\n" + 
13808
		"	<S, T> S e(Action<S> t);\n" + 
13809
		"	         ^^^^^^^^^^^^^^\n" + 
13810
		"Method e(Action<S>) has the same erasure e(Action<T>) as another method in type X\n" + 
13811
		"----------\n");
13812
}
13515
}
13813
}
(-)a/org.eclipse.jdt.core.tests.compiler/src/org/eclipse/jdt/core/tests/compiler/regression/NonFatalErrorTest.java (-2 / +40 lines)
Lines 1-5 Link Here
1
/*******************************************************************************
1
/*******************************************************************************
2
 * Copyright (c) 2000, 2011 IBM Corporation and others.
2
 * Copyright (c) 2000, 2012 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 12-17 Link Here
12
12
13
import java.util.Map;
13
import java.util.Map;
14
14
15
import org.eclipse.jdt.internal.compiler.classfmt.ClassFileConstants;
15
import org.eclipse.jdt.internal.compiler.impl.CompilerOptions;
16
import org.eclipse.jdt.internal.compiler.impl.CompilerOptions;
16
17
17
import junit.framework.Test;
18
import junit.framework.Test;
Lines 24-30 Link Here
24
	// All specified tests which does not belong to the class are skipped...
25
	// All specified tests which does not belong to the class are skipped...
25
	static {
26
	static {
26
//		TESTS_NAMES = new String[] { "test127" };
27
//		TESTS_NAMES = new String[] { "test127" };
27
//		TESTS_NUMBERS = new int[] { 5 };
28
//		TESTS_NUMBERS = new int[] { 7 };
28
//		TESTS_RANGE = new int[] { 169, 180 };
29
//		TESTS_RANGE = new int[] { 169, 180 };
29
	}
30
	}
30
31
Lines 258-261 Link Here
258
			// javac options
259
			// javac options
259
			JavacTestOptions.Excuse.EclipseWarningConfiguredAsError /* javac test options */);
260
			JavacTestOptions.Excuse.EclipseWarningConfiguredAsError /* javac test options */);
260
	}
261
	}
262
	public void test007() {
263
		if (this.complianceLevel < ClassFileConstants.JDK1_5) {
264
			return;
265
		}
266
		Map customOptions = getCompilerOptions();
267
		customOptions.put(CompilerOptions.OPTION_FatalOptionalError,
268
				CompilerOptions.ENABLED);
269
		customOptions.put(CompilerOptions.OPTION_ReportUnusedLocal,
270
				CompilerOptions.ERROR);
271
		customOptions.put(CompilerOptions.OPTION_SuppressWarnings,
272
				CompilerOptions.ENABLED);
273
		customOptions.put(CompilerOptions.OPTION_SuppressOptionalErrors,
274
				CompilerOptions.ENABLED);
275
		customOptions.put(CompilerOptions.OPTION_ReportUnusedWarningToken,
276
				CompilerOptions.ERROR);
277
		runConformTest(
278
				new String[] { /* test files */
279
						"X.java",
280
						"public class X {\n" +
281
								"        @SuppressWarnings(\"unused\")\n" +
282
								"        static void foo() {\n" +
283
								"            String s = null;\n" +
284
								"            System.out.println(\"SUCCESS\");\n" +
285
								"        }\n" +
286
								"        public static void main(String argv[]) {\n" +
287
								"            foo();\n" +
288
								"        }\n" +
289
								"}"
290
				},
291
				"SUCCESS" /* expected output string */,
292
				null /* no class libraries */,
293
				true,
294
				null,
295
				customOptions /* custom options */,
296
				// compiler results
297
				null /* do not check error string */);
298
	}
261
}
299
}
(-)a/org.eclipse.jdt.core.tests.compiler/src/org/eclipse/jdt/core/tests/compiler/regression/NullAnnotationTest.java (+3477 lines)
Added Link Here
1
/*******************************************************************************
2
 * Copyright (c) 2010, 2011 GK Software AG and others.
3
 * All rights reserved. This program and the accompanying materials
4
 * are made available under the terms of the Eclipse Public License v1.0
5
 * which accompanies this distribution, and is available at
6
 * http://www.eclipse.org/legal/epl-v10.html
7
 *
8
 * Contributors:
9
 *     Stephan Herrmann - initial API and implementation
10
 *******************************************************************************/
11
package org.eclipse.jdt.core.tests.compiler.regression;
12
13
14
import java.io.File;
15
import java.util.Map;
16
17
import junit.framework.Test;
18
19
import org.eclipse.core.runtime.FileLocator;
20
import org.eclipse.core.runtime.Platform;
21
import org.eclipse.jdt.core.JavaCore;
22
import org.eclipse.jdt.internal.compiler.classfmt.ClassFileConstants;
23
24
// see bug 186342 - [compiler][null] Using annotations for null checking
25
public class NullAnnotationTest extends AbstractComparableTest {
26
27
// class libraries including our default null annotation types:
28
String[] LIBS;
29
30
// names and content of custom annotations used in a few tests:
31
private static final String CUSTOM_NONNULL_NAME = "org/foo/NonNull.java";
32
private static final String CUSTOM_NONNULL_CONTENT =
33
	"package org.foo;\n" +
34
	"import static java.lang.annotation.ElementType.*;\n" +
35
	"import java.lang.annotation.*;\n" +
36
	"@Retention(RetentionPolicy.CLASS)\n" +
37
	"@Target({METHOD,PARAMETER,LOCAL_VARIABLE})\n" +
38
	"public @interface NonNull {\n" +
39
	"}\n";
40
private static final String CUSTOM_NULLABLE_NAME = "org/foo/Nullable.java";
41
private static final String CUSTOM_NULLABLE_CONTENT = "package org.foo;\n" +
42
	"import static java.lang.annotation.ElementType.*;\n" +
43
	"import java.lang.annotation.*;\n" +
44
	"@Retention(RetentionPolicy.CLASS)\n" +
45
	"@Target({METHOD,PARAMETER,LOCAL_VARIABLE})\n" +
46
	"public @interface Nullable {\n" +
47
	"}\n";
48
49
public NullAnnotationTest(String name) {
50
	super(name);
51
}
52
53
// Static initializer to specify tests subset using TESTS_* static variables
54
// All specified tests which do not belong to the class are skipped...
55
static {
56
//		TESTS_NAMES = new String[] { "test_message_send_in_control_structure_02" };
57
//		TESTS_NUMBERS = new int[] { 561 };
58
//		TESTS_RANGE = new int[] { 1, 2049 };
59
}
60
61
public static Test suite() {
62
	return buildComparableTestSuite(testClass());
63
}
64
65
public static Class testClass() {
66
	return NullAnnotationTest.class;
67
}
68
69
protected void setUp() throws Exception {
70
	super.setUp();
71
	if (this.LIBS == null) {
72
		String[] defaultLibs = getDefaultClassPaths();
73
		int len = defaultLibs.length;
74
		this.LIBS = new String[len+1];
75
		System.arraycopy(defaultLibs, 0, this.LIBS, 0, len);
76
		File bundleFile = FileLocator.getBundleFile(Platform.getBundle("org.eclipse.jdt.annotation"));
77
		if (bundleFile.isDirectory())
78
			this.LIBS[len] = bundleFile.getPath()+"/bin";
79
		else
80
			this.LIBS[len] = bundleFile.getPath();
81
	}
82
}
83
// Conditionally augment problem detection settings
84
static boolean setNullRelatedOptions = true;
85
protected Map getCompilerOptions() {
86
    Map defaultOptions = super.getCompilerOptions();
87
    if (setNullRelatedOptions) {
88
    	defaultOptions.put(JavaCore.COMPILER_PB_NULL_REFERENCE, JavaCore.ERROR);
89
	    defaultOptions.put(JavaCore.COMPILER_PB_POTENTIAL_NULL_REFERENCE, JavaCore.ERROR);
90
	    defaultOptions.put(JavaCore.COMPILER_PB_REDUNDANT_NULL_CHECK, JavaCore.ERROR);
91
		defaultOptions.put(JavaCore.COMPILER_PB_INCLUDE_ASSERTS_IN_NULL_ANALYSIS, JavaCore.ENABLED);
92
93
		defaultOptions.put(JavaCore.COMPILER_PB_MISSING_OVERRIDE_ANNOTATION_FOR_INTERFACE_METHOD_IMPLEMENTATION, JavaCore.DISABLED);
94
95
		// enable null annotations:
96
		defaultOptions.put(JavaCore.COMPILER_ANNOTATION_NULL_ANALYSIS, JavaCore.ENABLED);
97
		// leave other new options at these defaults:
98
//		defaultOptions.put(CompilerOptions.OPTION_ReportNullContractViolation, JavaCore.ERROR);
99
//		defaultOptions.put(CompilerOptions.OPTION_ReportPotentialNullContractViolation, JavaCore.ERROR);
100
//		defaultOptions.put(CompilerOptions.OPTION_ReportNullContractInsufficientInfo, CompilerOptions.WARNING);
101
102
//		defaultOptions.put(CompilerOptions.OPTION_NullableAnnotationName, "org.eclipse.jdt.annotation.Nullable");
103
//		defaultOptions.put(CompilerOptions.OPTION_NonNullAnnotationName, "org.eclipse.jdt.annotation.NonNull");
104
    }
105
    return defaultOptions;
106
}
107
void runNegativeTestWithLibs(String[] testFiles, String expectedErrorLog) {
108
	runNegativeTest(
109
			testFiles,
110
			expectedErrorLog,
111
			this.LIBS,
112
			false /*shouldFlush*/);
113
}
114
void runNegativeTestWithLibs(boolean shouldFlushOutputDirectory, String[] testFiles, Map customOptions, String expectedErrorLog) {
115
	runNegativeTest(
116
			shouldFlushOutputDirectory,
117
			testFiles,
118
			this.LIBS,
119
			customOptions,
120
			expectedErrorLog,
121
			// runtime options
122
		    JavacTestOptions.Excuse.EclipseWarningConfiguredAsError);
123
}
124
void runNegativeTestWithLibs(String[] testFiles, Map customOptions, String expectedErrorLog) {
125
	runNegativeTestWithLibs(false /* flush output directory */,	testFiles, customOptions, expectedErrorLog);
126
}
127
void runConformTestWithLibs(String[] testFiles, Map customOptions, String expectedCompilerLog) {
128
	runConformTestWithLibs(false /* flush output directory */, testFiles, customOptions, expectedCompilerLog);
129
}
130
void runConformTestWithLibs(boolean shouldFlushOutputDirectory, String[] testFiles, Map customOptions, String expectedCompilerLog) {
131
	runConformTest(
132
			shouldFlushOutputDirectory,
133
			testFiles,
134
			this.LIBS,
135
			customOptions,
136
			expectedCompilerLog,
137
			"",/* expected output */
138
			"",/* expected error */
139
		    JavacTestOptions.Excuse.EclipseWarningConfiguredAsError);
140
}
141
void runConformTest(String[] testFiles, Map customOptions, String expectedOutputString) {
142
	runConformTest(
143
			testFiles,
144
			expectedOutputString,
145
			null /*classLibraries*/,
146
			true /*shouldFlushOutputDirectory*/,
147
			null /*vmArguments*/,
148
			customOptions,
149
			null /*customRequestor*/);
150
151
}
152
// a nullable argument is dereferenced without a check
153
public void test_nullable_paramter_001() {
154
	runNegativeTest(
155
		new String[] {
156
			"X.java",
157
			  "import org.eclipse.jdt.annotation.*;\n" +
158
			  "public class X {\n" +
159
			  "    void foo(@Nullable Object o) {\n" +
160
			  "        System.out.print(o.toString());\n" +
161
			  "    }\n" +
162
			  "}\n"},
163
	    "----------\n" +
164
		"1. ERROR in X.java (at line 4)\n" +
165
		"	System.out.print(o.toString());\n" +
166
		"	                 ^\n" +
167
		"Potential null pointer access: The variable o may be null at this location\n" +
168
		"----------\n",
169
		this.LIBS,
170
		true /* shouldFlush*/);
171
}
172
173
// a null value is passed to a nullable argument
174
public void test_nullable_paramter_002() {
175
	runConformTest(
176
		new String[] {
177
			"X.java",
178
			  "import org.eclipse.jdt.annotation.*;\n" +
179
			  "public class X {\n" +
180
			  "    void foo(@Nullable Object o) {\n" +
181
			  "        // nop\n" +
182
			  "    }\n" +
183
			  "    void bar() {\n" +
184
			  "        foo(null);\n" +
185
			  "    }\n" +
186
			  "}\n"},
187
	    "",
188
	    this.LIBS,
189
	    false/*shouldFlush*/,
190
	    null/*vmArgs*/);
191
}
192
193
// a non-null argument is checked for null
194
public void test_nonnull_parameter_001() {
195
	runNegativeTest(
196
		new String[] {
197
			"X.java",
198
			  "import org.eclipse.jdt.annotation.*;\n" +
199
			  "public class X {\n" +
200
			  "    void foo(@NonNull Object o) {\n" +
201
			  "        if (o != null)\n" +
202
			  "              System.out.print(o.toString());\n" +
203
			  "    }\n" +
204
			  "}\n"},
205
	    "----------\n" +
206
		"1. ERROR in X.java (at line 4)\n" +
207
		"	if (o != null)\n" +
208
		"	    ^\n" +
209
		"Redundant null check: The variable o cannot be null at this location\n" +
210
		"----------\n",
211
		this.LIBS,
212
		true /* shouldFlush*/);
213
}
214
// a non-null argument is dereferenced without a check
215
public void test_nonnull_parameter_002() {
216
	runConformTest(
217
		new String[] {
218
			"X.java",
219
			  "import org.eclipse.jdt.annotation.*;\n" +
220
			  "public class X {\n" +
221
			  "    void foo(@NonNull Object o) {\n" +
222
			  "        System.out.print(o.toString());\n" +
223
			  "    }\n" +
224
			  "    public static void main(String... args) {\n" +
225
			  "        new X().foo(\"OK\");\n" +
226
			  "    }\n" +
227
			  "}\n"},
228
	    "OK",
229
	    this.LIBS,
230
	    false/*shouldFlush*/,
231
	    null/*vmArgs*/);
232
}
233
// passing null to nonnull parameter - many fields in enclosing class
234
public void test_nonnull_parameter_003() {
235
	runNegativeTest(
236
		new String[] {
237
			"X.java",
238
			  "import org.eclipse.jdt.annotation.*;\n" +
239
			  "public class X {\n" +
240
			  "    int i00, i01, i02, i03, i04, i05, i06, i07, i08, i09;" +
241
			  "    int i10, i11, i12, i13, i14, i15, i16, i17, i18, i19;" +
242
			  "    int i20, i21, i22, i23, i24, i25, i26, i27, i28, i29;" +
243
			  "    int i30, i31, i32, i33, i34, i35, i36, i37, i38, i39;" +
244
			  "    int i40, i41, i42, i43, i44, i45, i46, i47, i48, i49;" +
245
			  "    int i50, i51, i52, i53, i54, i55, i56, i57, i58, i59;" +
246
			  "    int i60, i61, i62, i63, i64, i65, i66, i67, i68, i69;" +
247
			  "    void foo(@NonNull Object o) {\n" +
248
			  "        System.out.print(o.toString());\n" +
249
			  "    }\n" +
250
			  "    void bar() {\n" +
251
			  "        foo(null);\n" +
252
			  "    }\n" +
253
			  "}\n"},
254
		"----------\n" +
255
		"1. ERROR in X.java (at line 7)\n" +
256
		"	foo(null);\n" +
257
		"	    ^^^^\n" +
258
		"Type mismatch: required \'@NonNull Object\' but the provided value is null\n" +
259
		"----------\n",
260
		this.LIBS,
261
		true /* shouldFlush*/);
262
}
263
// passing potential null to nonnull parameter - target method is consumed from .class
264
public void test_nonnull_parameter_004() {
265
	runConformTestWithLibs(
266
			new String[] {
267
				"Lib.java",
268
					"import org.eclipse.jdt.annotation.*;\n" +
269
				"public class Lib {\n" +
270
				"    void setObject(@NonNull Object o) { }\n" +
271
				"}\n"
272
			},
273
			null /*customOptions*/,
274
			"");
275
	runNegativeTestWithLibs(
276
		false, // don't flush
277
		new String[] {
278
			"X.java",
279
			  "public class X {\n" +
280
			  "    void bar(Lib l, boolean b) {\n" +
281
			  "        Object o = null;\n" +
282
			  "        if (b) o = new Object();\n" +
283
			  "        l.setObject(o);\n" +
284
			  "    }\n" +
285
			  "}\n"},
286
		null /*customOptions*/,
287
		"----------\n" +
288
		"1. ERROR in X.java (at line 5)\n" +
289
		"	l.setObject(o);\n" +
290
		"	            ^\n" +
291
		"Type mismatch: required \'@NonNull Object\' but the provided value can be null\n" +
292
		"----------\n");
293
}
294
// passing unknown value to nonnull parameter  - target method is consumed from .class
295
public void test_nonnull_parameter_005() {
296
	runConformTestWithLibs(
297
			new String[] {
298
				"Lib.java",
299
				"import org.eclipse.jdt.annotation.*;\n" +
300
				"public class Lib {\n" +
301
				"    void setObject(@NonNull Object o) { }\n" +
302
				"}\n"
303
			},
304
			null /*customOptions*/,
305
			"");
306
	runConformTestWithLibs(
307
		false, // don't flush
308
		new String[] {
309
			"X.java",
310
			  "public class X {\n" +
311
			  "    void bar(Lib l, Object o) {\n" +
312
			  "        l.setObject(o);\n" +
313
			  "    }\n" +
314
			  "}\n"},
315
		null /* options */,
316
		"----------\n" +
317
		"1. WARNING in X.java (at line 3)\n" +
318
		"	l.setObject(o);\n" +
319
		"	            ^\n" +
320
		"Potential type mismatch: required \'@NonNull Object\' but nullness of the provided value is unknown\n" +
321
		"----------\n");
322
}
323
// a ternary non-null expression is passed to a nonnull parameter
324
public void test_nonnull_parameter_006() {
325
	Map customOptions = getCompilerOptions();
326
	customOptions.put(JavaCore.COMPILER_PB_NULL_SPECIFICATION_INSUFFICIENT_INFO, JavaCore.ERROR);
327
	runConformTestWithLibs(
328
		new String[] {
329
			"X.java",
330
			  "import org.eclipse.jdt.annotation.*;\n" +
331
			  "public class X {\n" +
332
			  "    	void m1(@NonNull String a) {}\n" +
333
			  "		void m2(@Nullable String b) {\n" +
334
			  "			m1(b == null ? \"\" : b);\n" +
335
			  "		}\n" +
336
			  "}\n"},
337
		customOptions,
338
		""  /* compiler output */);
339
}
340
// nullable value passed to a non-null parameter in a super-call
341
public void test_nonnull_parameter_007() {
342
	Map customOptions = getCompilerOptions();
343
	customOptions.put(JavaCore.COMPILER_PB_NULL_SPECIFICATION_INSUFFICIENT_INFO, JavaCore.ERROR);
344
	runNegativeTestWithLibs(
345
		new String[] {
346
			"XSub.java",
347
			  "import org.eclipse.jdt.annotation.*;\n" +
348
			  "public class XSub extends XSuper {\n" +
349
			  "    	XSub(@Nullable String b) {\n" +
350
			  "			super(b);\n" +
351
			  "		}\n" +
352
			  "}\n",
353
			"XSuper.java",
354
			  "import org.eclipse.jdt.annotation.*;\n" +
355
			  "public class XSuper {\n" +
356
			  "    	XSuper(@NonNull String b) {\n" +
357
			  "		}\n" +
358
			  "}\n"
359
		},
360
		customOptions,
361
		"----------\n" +
362
		"1. ERROR in XSub.java (at line 4)\n" +
363
		"	super(b);\n" +
364
		"	      ^\n" +
365
		"Type mismatch: required \'@NonNull String\' but the provided value can be null\n" +
366
		"----------\n");
367
}
368
// a nullable value is passed to a non-null parameter in an allocation expression
369
public void test_nonnull_parameter_008() {
370
	Map customOptions = getCompilerOptions();
371
	customOptions.put(JavaCore.COMPILER_PB_NULL_SPECIFICATION_INSUFFICIENT_INFO, JavaCore.ERROR);
372
	runNegativeTestWithLibs(
373
		new String[] {
374
			"X.java",
375
			  "import org.eclipse.jdt.annotation.*;\n" +
376
			  "public class X {\n" +
377
			  "    	X(@NonNull String a) {}\n" +
378
			  "		static X create(@Nullable String b) {\n" +
379
			  "			return new X(b);\n" +
380
			  "		}\n" +
381
			  "}\n"},
382
		customOptions,
383
		"----------\n" +
384
		"1. ERROR in X.java (at line 5)\n" +
385
		"	return new X(b);\n" +
386
		"	             ^\n" +
387
		"Type mismatch: required \'@NonNull String\' but the provided value can be null\n" +
388
		"----------\n"  /* compiler output */);
389
}
390
// a nullable value is passed to a non-null parameter in a qualified allocation expression
391
public void test_nonnull_parameter_009() {
392
	Map customOptions = getCompilerOptions();
393
	customOptions.put(JavaCore.COMPILER_PB_NULL_SPECIFICATION_INSUFFICIENT_INFO, JavaCore.ERROR);
394
	runNegativeTestWithLibs(
395
		new String[] {
396
			"X.java",
397
			  "import org.eclipse.jdt.annotation.*;\n" +
398
			  "public class X {\n" +
399
			  "    class Local {\n" +
400
			  "    	   Local(@NonNull String a) {}\n" +
401
			  "    }\n" +
402
			  "	   Local create(@Nullable String b) {\n" +
403
			  "	       return this.new Local(b);\n" +
404
			  "    }\n" +
405
			  "}\n"},
406
		customOptions,
407
		"----------\n" +
408
		"1. ERROR in X.java (at line 7)\n" +
409
		"	return this.new Local(b);\n" +
410
		"	                      ^\n" +
411
		"Type mismatch: required \'@NonNull String\' but the provided value can be null\n" +
412
		"----------\n"  /* compiler output */);
413
}
414
// null is passed to a non-null parameter in a qualified allocation expression, across CUs
415
public void test_nonnull_parameter_010() {
416
	Map customOptions = getCompilerOptions();
417
	customOptions.put(JavaCore.COMPILER_PB_NULL_SPECIFICATION_INSUFFICIENT_INFO, JavaCore.ERROR);
418
	runNegativeTestWithLibs(
419
		new String[] {
420
			"ContainingInner2.java",
421
			"public class ContainingInner2 {\n" + 
422
			"    public ContainingInner2 (@org.eclipse.jdt.annotation.NonNull Object o) {\n" + 
423
			"    }\n" + 
424
			"    public class Inner {\n" + 
425
			"        public Inner (@org.eclipse.jdt.annotation.NonNull Object o) {\n" + 
426
			"        }\n" + 
427
			"    }\n" + 
428
			"}\n",
429
			"X.java",
430
			"public class X {\n" +
431
			"	 void create() {\n" +
432
			"          ContainingInner2 container = new ContainingInner2(null);\n" +
433
			"	       ContainingInner2.Inner inner = container.new Inner(null);\n" +
434
			"    }\n" +
435
		  	"}\n"},
436
		customOptions,
437
		"----------\n" + 
438
		"1. ERROR in X.java (at line 3)\n" + 
439
		"	ContainingInner2 container = new ContainingInner2(null);\n" + 
440
		"	                                                  ^^^^\n" + 
441
		"Type mismatch: required \'@NonNull Object\' but the provided value is null\n" + 
442
		"----------\n" + 
443
		"2. ERROR in X.java (at line 4)\n" + 
444
		"	ContainingInner2.Inner inner = container.new Inner(null);\n" + 
445
		"	                                                   ^^^^\n" + 
446
		"Type mismatch: required \'@NonNull Object\' but the provided value is null\n" + 
447
		"----------\n"  /* compiler output */);
448
}
449
// null is passed to a non-null parameter in a qualified allocation expression, target class read from .class
450
public void test_nonnull_parameter_011() {
451
	Map customOptions = getCompilerOptions();
452
	customOptions.put(JavaCore.COMPILER_PB_NULL_SPECIFICATION_INSUFFICIENT_INFO, JavaCore.ERROR);
453
	runConformTestWithLibs(
454
			new String[] {
455
				"ContainingInner2.java",
456
				"public class ContainingInner2 {\n" + 
457
				"    public ContainingInner2 (@org.eclipse.jdt.annotation.NonNull Object o) {\n" + 
458
				"    }\n" + 
459
				"    public class Inner {\n" + 
460
				"        public Inner (@org.eclipse.jdt.annotation.NonNull Object o) {\n" + 
461
				"        }\n" + 
462
				"    }\n" + 
463
				"}\n",
464
			},
465
			null /*customOptions*/,
466
			"");
467
	runNegativeTestWithLibs(
468
		false, // flush directory
469
		new String[] {
470
			"X.java",
471
			"public class X {\n" +
472
			"	 void create() {\n" +
473
			"          ContainingInner2 container = new ContainingInner2(null);\n" +
474
			"	       ContainingInner2.Inner inner = container.new Inner(null);\n" +
475
			"    }\n" +
476
		  	"}\n"},
477
		customOptions,
478
		"----------\n" + 
479
		"1. ERROR in X.java (at line 3)\n" + 
480
		"	ContainingInner2 container = new ContainingInner2(null);\n" + 
481
		"	                                                  ^^^^\n" + 
482
		"Type mismatch: required \'@NonNull Object\' but the provided value is null\n" + 
483
		"----------\n" + 
484
		"2. ERROR in X.java (at line 4)\n" + 
485
		"	ContainingInner2.Inner inner = container.new Inner(null);\n" + 
486
		"	                                                   ^^^^\n" + 
487
		"Type mismatch: required \'@NonNull Object\' but the provided value is null\n" + 
488
		"----------\n"  /* compiler output */);
489
}
490
// null is passed to a non-null parameter in a qualified allocation expression, generic constructor, target class read from .class
491
public void test_nonnull_parameter_012() {
492
	Map customOptions = getCompilerOptions();
493
	customOptions.put(JavaCore.COMPILER_PB_NULL_SPECIFICATION_INSUFFICIENT_INFO, JavaCore.ERROR);
494
	runConformTestWithLibs(
495
			new String[] {
496
				"ContainingInner2.java",
497
				"public class ContainingInner2 {\n" + 
498
				"    public ContainingInner2 (@org.eclipse.jdt.annotation.NonNull Object o) {\n" + 
499
				"    }\n" + 
500
				"    public class Inner {\n" + 
501
				"        public <T> Inner (@org.eclipse.jdt.annotation.NonNull T o) {\n" + 
502
				"        }\n" + 
503
				"    }\n" + 
504
				"}\n",
505
			},
506
			null /*customOptions*/,
507
			"");
508
	runNegativeTestWithLibs(
509
		false, // flush directory
510
		new String[] {
511
			"X.java",
512
			"public class X {\n" +
513
			"	 void create() {\n" +
514
			"          ContainingInner2 container = new ContainingInner2(null);\n" +
515
			"	       ContainingInner2.Inner inner = container.new Inner(null);\n" +
516
			"    }\n" +
517
		  	"}\n"},
518
		customOptions,
519
		"----------\n" + 
520
		"1. ERROR in X.java (at line 3)\n" + 
521
		"	ContainingInner2 container = new ContainingInner2(null);\n" + 
522
		"	                                                  ^^^^\n" + 
523
		"Type mismatch: required \'@NonNull Object\' but the provided value is null\n" + 
524
		"----------\n" + 
525
		"2. ERROR in X.java (at line 4)\n" + 
526
		"	ContainingInner2.Inner inner = container.new Inner(null);\n" + 
527
		"	                                                   ^^^^\n" + 
528
		"Type mismatch: required \'@NonNull Object\' but the provided value is null\n" + 
529
		"----------\n"  /* compiler output */);
530
}
531
// a method of a local class has a non-null parameter, client passes null
532
public void test_nonnull_parameter_013() {
533
	runNegativeTestWithLibs(
534
		new String[] {
535
			"B.java",
536
			"class B {\n" +
537
			"    void bar () {\n" +
538
			"        class Local {\n" +
539
			"            void callMe(@org.eclipse.jdt.annotation.NonNull Object o){\n" +
540
			"            }\n" +
541
			"        }\n" +
542
			"        Local l = new Local();\n" +
543
			"        l.callMe(null);\n" +
544
			"    } \n" +
545
			"}\n"
546
		},
547
		"----------\n" + 
548
		"1. ERROR in B.java (at line 8)\n" + 
549
		"	l.callMe(null);\n" + 
550
		"	         ^^^^\n" + 
551
		"Type mismatch: required \'@NonNull Object\' but the provided value is null\n" + 
552
		"----------\n");
553
}
554
// non-null varargs (message send)
555
public void test_nonnull_parameter_015() {
556
	if (this.complianceLevel > ClassFileConstants.JDK1_7) {
557
		fail("Reminder: should check if JSR 308 mandates a change in handling vararg elements (see bug 365983).");
558
		return;
559
	}
560
	runNegativeTest(
561
		new String[] {
562
			"X.java",
563
			"import org.eclipse.jdt.annotation.*;\n" +
564
			"public class X {\n" +
565
			"    void foo(@NonNull Object ... o) {\n" +
566
			"        if (o != null)\n" +
567
			"              System.out.print(o.toString());\n" +
568
			"    }\n" +
569
			"    void foo2(int i, @NonNull Object ... o) {\n" +
570
			"        if (o.length > 0 && o[0] != null)\n" +
571
			"              System.out.print(o[0].toString());\n" +
572
			"    }\n" +
573
			"    void bar() {\n" +
574
			"        foo((Object)null);\n" +		// unchecked: single plain argument
575
			"        Object[] objs = null;\n" +
576
			"        foo(objs);\n" +				// error
577
			"        foo(this, null);\n" +			// unchecked: multiple plain arguments
578
			"        foo2(2, (Object)null);\n" +    // unchecked: single plain argument
579
			"        foo2(2, null, this);\n" +      // unchecked: multiple plain arguments
580
			"        foo2(2, null);\n" +  			// error
581
			"    }\n" +
582
			"}\n"},
583
			"----------\n" + 
584
			"1. ERROR in X.java (at line 4)\n" + 
585
			"	if (o != null)\n" + 
586
			"	    ^\n" + 
587
			"Redundant null check: The variable o cannot be null at this location\n" + 
588
			"----------\n" + 
589
			"2. ERROR in X.java (at line 14)\n" + 
590
			"	foo(objs);\n" + 
591
			"	    ^^^^\n" + 
592
			"Type mismatch: required \'@NonNull Object[]\' but the provided value is null\n" + 
593
			"----------\n" + 
594
			"3. WARNING in X.java (at line 18)\n" + 
595
			"	foo2(2, null);\n" + 
596
			"	^^^^^^^^^^^^^\n" + 
597
			"The argument of type null should explicitly be cast to Object[] for the invocation of the varargs method foo2(int, Object...) from type X. It could alternatively be cast to Object for a varargs invocation\n" + 
598
			"----------\n" + 
599
			"4. ERROR in X.java (at line 18)\n" + 
600
			"	foo2(2, null);\n" + 
601
			"	        ^^^^\n" + 
602
			"Type mismatch: required \'@NonNull Object[]\' but the provided value is null\n" + 
603
			"----------\n",
604
		this.LIBS,
605
		true /* shouldFlush*/);
606
}
607
// non-null varargs (allocation and explicit constructor calls)
608
public void test_nonnull_parameter_016() {
609
	if (this.complianceLevel > ClassFileConstants.JDK1_7) {
610
		fail("Reminder: should check if JSR 308 mandates a change in handling vararg elements (see bug 365983).");
611
		return;
612
	}
613
	runNegativeTest(
614
		new String[] {
615
			"X.java",
616
			"import org.eclipse.jdt.annotation.*;\n" +
617
			"public class X {\n" +
618
			"    X(@NonNull Object ... o) {\n" +
619
			"        if (o != null)\n" +
620
			"              System.out.print(o.toString());\n" +
621
			"    }\n" +
622
			"    class Y extends X {\n" +
623
			"        Y(int i, @NonNull Object ... o) {\n" +
624
			"        	super(i, (Object)null);\n" +
625
			"        }\n" +
626
			"        Y(char c, @NonNull Object ... o) {\n" +
627
			"        	this(1, new Object(), null);\n" +
628
			"        }\n" +
629
			"    }\n" +
630
			"    void bar() {\n" +
631
			"        new X((Object[])null);\n" +
632
			"        new X(this, null);\n" +
633
			"        X x = new X(null, this);\n" +
634
			"        x.new Y(2, (Object)null);\n" +
635
			"        this.new Y(2, null, this);\n" +
636
			"        this.new Y(2, (Object[])null);\n" +
637
			"    }\n" +
638
			"}\n"},
639
			"----------\n" +
640
			"1. ERROR in X.java (at line 4)\n" +
641
			"	if (o != null)\n" +
642
			"	    ^\n" +
643
			"Redundant null check: The variable o cannot be null at this location\n" +
644
			"----------\n" +
645
			"2. ERROR in X.java (at line 16)\n" +
646
			"	new X((Object[])null);\n" +
647
			"	      ^^^^^^^^^^^^^^\n" +
648
			"Type mismatch: required \'@NonNull Object[]\' but the provided value is null\n" +
649
			"----------\n" +
650
			"3. ERROR in X.java (at line 21)\n" +
651
			"	this.new Y(2, (Object[])null);\n" +
652
			"	              ^^^^^^^^^^^^^^\n" +
653
			"Type mismatch: required \'@NonNull Object[]\' but the provided value is null\n" +
654
			"----------\n",
655
		this.LIBS,
656
		true /* shouldFlush*/);
657
}
658
// Bug 367203 - [compiler][null] detect assigning null to nonnull argument
659
public void test_nonnull_argument_001() {
660
	runNegativeTestWithLibs(
661
			new String[] {
662
				"ShowNPE2.java",
663
				"import org.eclipse.jdt.annotation.NonNullByDefault;\n" + 
664
				"@NonNullByDefault\n" + 
665
				"public class ShowNPE2 {\n" + 
666
				"     public Object foo(Object o1, final boolean b) {\n" + 
667
				"         o1 = null;   // expect NPE error\n" + 
668
				"         System.out.println(o1.toString());   \n" + 
669
				"         return null;  // expect NPE error\n" + 
670
				"    }\n" + 
671
				"}"
672
			},
673
			"----------\n" + 
674
			"1. ERROR in ShowNPE2.java (at line 5)\n" + 
675
			"	o1 = null;   // expect NPE error\n" + 
676
			"	     ^^^^\n" + 
677
			"Type mismatch: required \'@NonNull Object\' but the provided value is null\n" + 
678
			"----------\n" + 
679
			"2. ERROR in ShowNPE2.java (at line 7)\n" + 
680
			"	return null;  // expect NPE error\n" + 
681
			"	       ^^^^\n" + 
682
			"Type mismatch: required \'@NonNull Object\' but the provided value is null\n" + 
683
			"----------\n");
684
}
685
// Bug 367203 - [compiler][null] detect assigning null to nonnull argument
686
public void test_nonnull_argument_002() {
687
	runNegativeTestWithLibs(
688
			new String[] {
689
				"ShowNPE2.java",
690
				"import org.eclipse.jdt.annotation.NonNullByDefault;\n" + 
691
				"@NonNullByDefault\n" + 
692
				"public class ShowNPE2 {\n" + 
693
				"    public Object foo(Object o1, final boolean b) {\n" + 
694
				"        bar(o1); // expecting no problem\n" + 
695
				"        return null;  // expect NPE error\n" + 
696
				"    }\n" +
697
				"    void bar(Object o2) {}\n" + 
698
				"}"
699
			},
700
			"----------\n" + 
701
			"1. ERROR in ShowNPE2.java (at line 6)\n" + 
702
			"	return null;  // expect NPE error\n" + 
703
			"	       ^^^^\n" + 
704
			"Type mismatch: required \'@NonNull Object\' but the provided value is null\n" + 
705
			"----------\n");
706
}
707
// a method of a local class has a non-null parameter, client passes potential null (msg send)
708
public void test_nonnull_parameter_014() {
709
	runNegativeTestWithLibs(
710
		new String[] {
711
			"B.java",
712
			"class B {\n" +
713
			"    void bar () {\n" +
714
			"        class Local {\n" +
715
			"            void callMe(@org.eclipse.jdt.annotation.NonNull Object o){\n" +
716
			"            }\n" +
717
			"        }\n" +
718
			"        Local l = new Local();\n" +
719
			"        l.callMe(getNull());\n" +
720
			"    }\n" +
721
			"    @org.eclipse.jdt.annotation.Nullable Object getNull() { return null; }" +
722
			"}\n"
723
		},
724
		"----------\n" + 
725
		"1. ERROR in B.java (at line 8)\n" + 
726
		"	l.callMe(getNull());\n" + 
727
		"	         ^^^^^^^^^\n" + 
728
		"Type mismatch: required \'@NonNull Object\' but the provided value can be null\n" + 
729
		"----------\n");
730
}
731
// assigning potential null to a nonnull local variable
732
public void test_nonnull_local_001() {
733
	runNegativeTest(
734
		new String[] {
735
			"X.java",
736
			  "import org.eclipse.jdt.annotation.*;\n" +
737
			  "public class X {\n" +
738
			  "    void foo(boolean b, Object p) {\n" +
739
			  "        @NonNull Object o1 = b ? null : new Object();\n" +
740
			  "        @NonNull String o2 = \"\";\n" +
741
			  "        o2 = null;\n" +
742
			  "        @NonNull Object o3 = p;\n" +
743
			  "    }\n" +
744
			  "}\n"},
745
		"----------\n" +
746
		"1. ERROR in X.java (at line 4)\n" +
747
		"	@NonNull Object o1 = b ? null : new Object();\n" +
748
		"	                     ^^^^^^^^^^^^^^^^^^^^^^^\n" +
749
		"Type mismatch: required \'@NonNull Object\' but the provided value can be null\n" +
750
		"----------\n" +
751
		"2. ERROR in X.java (at line 6)\n" +
752
		"	o2 = null;\n" +
753
		"	     ^^^^\n" +
754
		"Type mismatch: required \'@NonNull String\' but the provided value is null\n" +
755
		"----------\n" +
756
		"3. WARNING in X.java (at line 7)\n" +
757
		"	@NonNull Object o3 = p;\n" +
758
		"	                     ^\n" +
759
		"Potential type mismatch: required \'@NonNull Object\' but nullness of the provided value is unknown\n" +
760
		"----------\n",
761
		this.LIBS,
762
		true /* shouldFlush*/);
763
}
764
765
// assigning potential null to a nonnull local variable - separate decl and assignment
766
public void test_nonnull_local_002() {
767
	runNegativeTest(
768
		new String[] {
769
			"X.java",
770
			  "import org.eclipse.jdt.annotation.*;\n" +
771
			  "public class X {\n" +
772
			  "    void foo(boolean b, Object p) {\n" +
773
			  "        @NonNull Object o1;\n" +
774
			  "        o1 = b ? null : new Object();\n" +
775
			  "        @NonNull String o2;\n" +
776
			  "        o2 = \"\";\n" +
777
			  "        o2 = null;\n" +
778
			  "        @NonNull Object o3;\n" +
779
			  "        o3 = p;\n" +
780
			  "    }\n" +
781
			  "}\n"},
782
		"----------\n" +
783
		"1. ERROR in X.java (at line 5)\n" +
784
		"	o1 = b ? null : new Object();\n" +
785
		"	     ^^^^^^^^^^^^^^^^^^^^^^^\n" +
786
		"Type mismatch: required \'@NonNull Object\' but the provided value can be null\n" +
787
		"----------\n" +
788
		"2. ERROR in X.java (at line 8)\n" +
789
		"	o2 = null;\n" +
790
		"	     ^^^^\n" +
791
		"Type mismatch: required \'@NonNull String\' but the provided value is null\n" +
792
		"----------\n" +
793
		"3. WARNING in X.java (at line 10)\n" +
794
		"	o3 = p;\n" +
795
		"	     ^\n" +
796
		"Potential type mismatch: required \'@NonNull Object\' but nullness of the provided value is unknown\n" +
797
		"----------\n",
798
		this.LIBS,
799
		true /* shouldFlush*/);
800
}
801
802
// a method tries to tighten the type specification, super declares parameter o as @Nullable
803
// other parameters: s is redefined from not constrained to @Nullable which is OK
804
//                   third is redefined from not constrained to @NonNull which is bad, too
805
public void test_parameter_specification_inheritance_001() {
806
	runConformTestWithLibs(
807
		new String[] {
808
			"Lib.java",
809
			"import org.eclipse.jdt.annotation.*;\n" +
810
			"public class Lib {\n" +
811
			"    void foo(String s, @Nullable Object o, Object third) { }\n" +
812
			"}\n"
813
		},
814
		null /*customOptions*/,
815
		"");
816
	runNegativeTestWithLibs(
817
		false, // don't flush
818
		new String[] {
819
			"X.java",
820
			"import org.eclipse.jdt.annotation.*;\n" +
821
			"public class X extends Lib {\n" +
822
			"    @Override\n" +
823
			"    void foo(@Nullable String s, @NonNull Object o, @NonNull Object third) { System.out.print(o.toString()); }\n" +
824
			"}\n"
825
		},
826
		null /*customOptions*/,
827
		"----------\n" +
828
		"1. ERROR in X.java (at line 4)\n" +
829
		"	void foo(@Nullable String s, @NonNull Object o, @NonNull Object third) { System.out.print(o.toString()); }\n" +
830
		"	                             ^^^^^^^^^^^^^^^\n" +
831
		"Illegal redefinition of parameter o, inherited method from Lib declares this parameter as @Nullable\n" +
832
		"----------\n" +
833
		"2. ERROR in X.java (at line 4)\n" +
834
		"	void foo(@Nullable String s, @NonNull Object o, @NonNull Object third) { System.out.print(o.toString()); }\n" +
835
		"	                                                ^^^^^^^^^^^^^^^\n" +
836
		"Illegal redefinition of parameter third, inherited method from Lib does not constrain this parameter\n" +
837
		"----------\n");
838
}
839
// a method body fails to redeclare the inherited null annotation, super declares parameter as @Nullable
840
public void test_parameter_specification_inheritance_002() {
841
	runConformTest(
842
		new String[] {
843
			"Lib.java",
844
			"import org.eclipse.jdt.annotation.*;\n" +
845
			"public class Lib {\n" +
846
			"    void foo(@Nullable Object o) { }\n" +
847
			"}\n"
848
		},
849
		"",
850
	    this.LIBS,
851
	    false/*shouldFlush*/,
852
	    null/*vmArgs*/);
853
	runNegativeTestWithLibs(
854
		false, // don't flush
855
		new String[] {
856
			"X.java",
857
			"public class X extends Lib {\n" +
858
			"    @Override\n" +
859
			"    void foo(Object o) {\n" +
860
			"        System.out.print(o.toString());\n" +
861
			"    }\n" +
862
			"}\n"
863
		},
864
		null /*customOptions*/,
865
		"----------\n" +
866
		"1. ERROR in X.java (at line 3)\n" +
867
		"	void foo(Object o) {\n" +
868
		"	         ^^^^^^\n" +
869
		"Missing nullable annotation: inherited method from Lib declares this parameter as @Nullable\n" +
870
		"----------\n");
871
}
872
// a method relaxes the parameter null specification, super interface declares parameter o as @NonNull
873
// other (first) parameter just repeats the inherited @NonNull
874
public void test_parameter_specification_inheritance_003() {
875
	runConformTest(
876
		new String[] {
877
			"IX.java",
878
			"import org.eclipse.jdt.annotation.*;\n" +
879
			"public interface IX {\n" +
880
			"    void foo(@NonNull String s, @NonNull Object o);\n" +
881
			"}\n",
882
			"X.java",
883
			"import org.eclipse.jdt.annotation.*;\n" +
884
			"public class X implements IX {\n" +
885
			"    public void foo(@NonNull String s, @Nullable Object o) { ; }\n" +
886
			"    void bar() { foo(\"OK\", null); }\n" +
887
			"}\n"
888
		},
889
		"",
890
	    this.LIBS,
891
	    false/*shouldFlush*/,
892
	    null/*vmArgs*/);
893
}
894
// a method adds a @NonNull annotation, super interface has no null annotation
895
// changing other from unconstrained to @Nullable is OK
896
public void test_parameter_specification_inheritance_004() {
897
	runConformTest(
898
		new String[] {
899
			"IX.java",
900
			"public interface IX {\n" +
901
			"    void foo(Object o, Object other);\n" +
902
			"}\n"
903
		});
904
	runNegativeTestWithLibs(
905
		false, // don't flush
906
		new String[] {
907
			"X.java",
908
			"import org.eclipse.jdt.annotation.*;\n" +
909
			"public class X implements IX {\n" +
910
			"    public void foo(@NonNull Object o, @Nullable Object other) { System.out.print(o.toString()); }\n" +
911
			"}\n"
912
		},
913
		null /*customOptions*/,
914
		"----------\n" +
915
		"1. ERROR in X.java (at line 3)\n" +
916
		"	public void foo(@NonNull Object o, @Nullable Object other) { System.out.print(o.toString()); }\n" +
917
		"	                ^^^^^^^^^^^^^^^\n" +
918
		"Illegal redefinition of parameter o, inherited method from IX does not constrain this parameter\n" +
919
		"----------\n");
920
}
921
// a method tries to relax the null contract, super declares @NonNull return
922
public void test_parameter_specification_inheritance_005() {
923
	runConformTestWithLibs(
924
		new String[] {
925
			"Lib.java",
926
			"import org.eclipse.jdt.annotation.*;\n" +
927
			"public class Lib {\n" +
928
			"    @NonNull Object getObject() { return new Object(); }\n" +
929
			"}\n"
930
		},
931
		null /*customOptions*/,
932
		"");
933
	runNegativeTestWithLibs(
934
		false, //dont' flush
935
		new String[] {
936
			"X.java",
937
			"import org.eclipse.jdt.annotation.*;\n" +
938
			"public class X extends Lib {\n" +
939
			"    @Override\n" +
940
			"    @Nullable Object getObject() { return null; }\n" +
941
			"}\n"
942
		},
943
		null /*customOptions*/,
944
		"----------\n" +
945
		"1. ERROR in X.java (at line 4)\n" +
946
		"	@Nullable Object getObject() { return null; }\n" +
947
		"	^^^^^^^^^^^^^^^^\n" +
948
		"The return type is incompatible with the @NonNull return from Lib.getObject()\n" +
949
		"----------\n");
950
}
951
952
// super has no constraint for return, sub method confirms the null contract as @Nullable
953
public void test_parameter_specification_inheritance_006() {
954
	runConformTest(
955
		new String[] {
956
			"Lib.java",
957
			"public class Lib {\n" +
958
			"    Object getObject() { return null; }\n" +
959
			"}\n"
960
		});
961
	runConformTestWithLibs(
962
		false, // don't flush
963
		new String[] {
964
			"X.java",
965
			"import org.eclipse.jdt.annotation.*;\n" +
966
			"public class X extends Lib {\n" +
967
			"    @Override\n" +
968
			"    @Nullable Object getObject() { return null; }\n" +
969
			"}\n"
970
		},
971
		null /*customOptions*/,
972
		"");
973
}
974
// a method body violates the inherited null specification, super declares @NonNull return, missing redeclaration
975
public void test_parameter_specification_inheritance_007() {
976
	runConformTestWithLibs(
977
		new String[] {
978
			"Lib.java",
979
			"import org.eclipse.jdt.annotation.*;\n" +
980
			"public class Lib {\n" +
981
			"    @NonNull Object getObject() { return new Object(); }\n" +
982
			"}\n"
983
		},
984
		null /*customOptions*/,
985
		"");
986
	runNegativeTestWithLibs(
987
		false, // don't flush
988
		new String[] {
989
			"X.java",
990
			"public class X extends Lib {\n" +
991
			"    @Override\n" +
992
			"    Object getObject() { return null; }\n" +
993
			"}\n"
994
		},
995
		null /*customOptions*/,
996
		"----------\n" +
997
		"1. ERROR in X.java (at line 3)\n" +
998
		"	Object getObject() { return null; }\n" +
999
		"	^^^^^^\n" +
1000
		"The return type is incompatible with the @NonNull return from Lib.getObject()\n" +
1001
		"----------\n");
1002
}
1003
//a method body violates the @NonNull return specification (repeated from super)
1004
public void test_parameter_specification_inheritance_007a() {
1005
	runConformTestWithLibs(
1006
		new String[] {
1007
			"Lib.java",
1008
			"import org.eclipse.jdt.annotation.*;\n" +
1009
			"public class Lib {\n" +
1010
			"    @NonNull Object getObject() { return new Object(); }\n" +
1011
			"}\n"
1012
		},
1013
		null /*customOptions*/,
1014
		"");
1015
	runNegativeTestWithLibs(
1016
		false, // don't flush
1017
		new String[] {
1018
			"X.java",
1019
			"import org.eclipse.jdt.annotation.*;\n" +
1020
			"public class X extends Lib {\n" +
1021
			"    @Override\n" +
1022
			"    @NonNull Object getObject() { return null; }\n" +
1023
			"}\n"
1024
		},
1025
		null /*customOptions*/,
1026
		"----------\n" +
1027
		"1. ERROR in X.java (at line 4)\n" +
1028
		"	@NonNull Object getObject() { return null; }\n" +
1029
		"	                                     ^^^^\n" +
1030
		"Type mismatch: required \'@NonNull Object\' but the provided value is null\n" +
1031
		"----------\n");
1032
}
1033
// a client potentially violates the inherited null specification, super interface declares @NonNull parameter
1034
public void test_parameter_specification_inheritance_008() {
1035
	Map options = getCompilerOptions();
1036
	options.put(JavaCore.COMPILER_PB_NULL_SPECIFICATION_INSUFFICIENT_INFO, JavaCore.ERROR);
1037
	runConformTestWithLibs(
1038
		new String[] {
1039
			"IX.java",
1040
			"import org.eclipse.jdt.annotation.*;\n" +
1041
			"public interface IX {\n" +
1042
			"    void printObject(@NonNull Object o);\n" +
1043
			"}\n"
1044
		},
1045
		null /*customOptions*/,
1046
		"");
1047
	runNegativeTestWithLibs(
1048
		false, // don't flush
1049
		new String[] {
1050
			"X.java",
1051
			"public class X implements IX {\n" +
1052
			"    public void printObject(Object o) { System.out.print(o.toString()); }\n" +
1053
			"}\n",
1054
			"M.java",
1055
			"public class M{\n" +
1056
			"    void foo(IX x, Object o) {\n" +
1057
			"        x.printObject(o);\n" +
1058
			"    }\n" +
1059
			"}\n"
1060
		},
1061
		options,
1062
		"----------\n" +
1063
		// additional error:
1064
		"1. ERROR in X.java (at line 2)\n" +
1065
		"	public void printObject(Object o) { System.out.print(o.toString()); }\n" +
1066
		"	                        ^^^^^^\n" +
1067
		"Missing non-null annotation: inherited method from IX declares this parameter as @NonNull\n" +
1068
		"----------\n" +
1069
		// main error:
1070
		"----------\n" +
1071
		"1. ERROR in M.java (at line 3)\n" +
1072
		"	x.printObject(o);\n" +
1073
		"	              ^\n" +
1074
		"Potential type mismatch: required \'@NonNull Object\' but nullness of the provided value is unknown\n" +
1075
		"----------\n");
1076
}
1077
// a static method has a more relaxed null contract than a like method in the super class, but no overriding.
1078
public void test_parameter_specification_inheritance_009() {
1079
	runConformTestWithLibs(
1080
		new String[] {
1081
			"Lib.java",
1082
			"import org.eclipse.jdt.annotation.*;\n" +
1083
			"public class Lib {\n" +
1084
			"    @NonNull static Object getObject() { return new Object(); }\n" +
1085
			"}\n",
1086
			"X.java",
1087
			"import org.eclipse.jdt.annotation.*;\n" +
1088
			"public class X extends Lib {\n" +
1089
			"    @Nullable static Object getObject() { return null; }\n" +
1090
			"}\n"
1091
		},
1092
		null /*customOptions*/,
1093
		"");
1094
}
1095
// class default is nonnull, method and its super both use the default
1096
public void test_parameter_specification_inheritance_010() {
1097
	Map customOptions = getCompilerOptions();
1098
	customOptions.put(JavaCore.COMPILER_PB_NULL_SPECIFICATION_INSUFFICIENT_INFO, JavaCore.ERROR);
1099
	runConformTestWithLibs(
1100
		new String[] {
1101
	"p1/X.java",
1102
			"package p1;\n" +
1103
			"import org.eclipse.jdt.annotation.*;\n" +
1104
			"@NonNullByDefault\n" +
1105
			"public class X {\n" +
1106
			"    protected String getString(String s) {\n" +
1107
			"        if (Character.isLowerCase(s.charAt(0)))\n" +
1108
			"	        return getString(s);\n" +
1109
			"	     return s;\n" +
1110
			"    }\n" +
1111
			"}\n",
1112
	"p1/Y.java",
1113
			"package p1;\n" +
1114
			"import org.eclipse.jdt.annotation.*;\n" +
1115
			"@NonNullByDefault\n" +
1116
			"public class Y extends X {\n" +
1117
			"    @Override\n" +
1118
			"    protected String getString(String s) {\n" +
1119
			"	     return super.getString(s);\n" +
1120
			"    }\n" +
1121
			"}\n",
1122
		},
1123
		customOptions,
1124
		"");
1125
}
1126
// class default is nonnull, method and its super both use the default, super-call passes null
1127
public void test_parameter_specification_inheritance_011() {
1128
	Map customOptions = getCompilerOptions();
1129
	customOptions.put(JavaCore.COMPILER_PB_NULL_SPECIFICATION_INSUFFICIENT_INFO, JavaCore.ERROR);
1130
	runNegativeTestWithLibs(
1131
		new String[] {
1132
	"p1/X.java",
1133
			"package p1;\n" +
1134
			"import org.eclipse.jdt.annotation.*;\n" +
1135
			"@NonNullByDefault\n" +
1136
			"public class X {\n" +
1137
			"    protected String getString(String s) {\n" +
1138
			"        if (Character.isLowerCase(s.charAt(0)))\n" +
1139
			"	        return getString(s);\n" +
1140
			"	     return s;\n" +
1141
			"    }\n" +
1142
			"}\n",
1143
	"p1/Y.java",
1144
			"package p1;\n" +
1145
			"import org.eclipse.jdt.annotation.*;\n" +
1146
			"@NonNullByDefault\n" +
1147
			"public class Y extends X {\n" +
1148
			"    @Override\n" +
1149
			"    protected String getString(String s) {\n" +
1150
			"	     return super.getString(null);\n" +
1151
			"    }\n" +
1152
			"}\n",
1153
		},
1154
		customOptions,
1155
		"----------\n" +
1156
		"1. ERROR in p1\\Y.java (at line 7)\n" +
1157
		"	return super.getString(null);\n" +
1158
		"	                       ^^^^\n" +
1159
		"Type mismatch: required \'@NonNull String\' but the provided value is null\n" +
1160
		"----------\n");
1161
}
1162
// methods from two super types have different null contracts.
1163
// sub-class merges both using the weakest common contract
1164
public void test_parameter_specification_inheritance_012() {
1165
	Map customOptions = getCompilerOptions();
1166
	customOptions.put(JavaCore.COMPILER_PB_NULL_SPECIFICATION_INSUFFICIENT_INFO, JavaCore.ERROR);
1167
	runConformTestWithLibs(
1168
		new String[] {
1169
	"p1/X.java",
1170
			"package p1;\n" +
1171
			"import org.eclipse.jdt.annotation.*;\n" +
1172
			"public class X {\n" +
1173
			"    public @Nullable String getString(String s1, @Nullable String s2, @NonNull String s3) {\n" +
1174
			"	     return s1;\n" +
1175
			"    }\n" +
1176
			"}\n",
1177
	"p1/IY.java",
1178
			"package p1;\n" +
1179
			"import org.eclipse.jdt.annotation.*;\n" +
1180
			"public interface IY {\n" +
1181
			"    @NonNull String getString(@NonNull String s1, @NonNull String s2, @Nullable String s3);\n" +
1182
			"}\n",
1183
	"p1/Y.java",
1184
			"package p1;\n" +
1185
			"import org.eclipse.jdt.annotation.*;\n" +
1186
			"public class Y extends X implements IY {\n" +
1187
			"    @Override\n" +
1188
			"    public @NonNull String getString(@Nullable String s1, @Nullable String s2, @Nullable String s3) {\n" +
1189
			"	     return \"\";\n" +
1190
			"    }\n" +
1191
			"}\n",
1192
		},
1193
		customOptions,
1194
		"");
1195
}
1196
// methods from two super types have different null contracts.
1197
// sub-class overrides this method in non-conforming ways
1198
public void test_parameter_specification_inheritance_013() {
1199
	Map customOptions = getCompilerOptions();
1200
	customOptions.put(JavaCore.COMPILER_PB_NULL_SPECIFICATION_INSUFFICIENT_INFO, JavaCore.ERROR);
1201
	runNegativeTestWithLibs(
1202
		new String[] {
1203
	"p1/X.java",
1204
			"package p1;\n" +
1205
			"import org.eclipse.jdt.annotation.*;\n" +
1206
			"public class X {\n" +
1207
			"    public @Nullable String getString(String s1, @Nullable String s2, @NonNull String s3) {\n" +
1208
			"	     return s1;\n" +
1209
			"    }\n" +
1210
			"}\n",
1211
	"p1/IY.java",
1212
			"package p1;\n" +
1213
			"import org.eclipse.jdt.annotation.*;\n" +
1214
			"public interface IY {\n" +
1215
			"    @NonNull String getString(@NonNull String s1, @NonNull String s2, @Nullable String s3);\n" +
1216
			"}\n",
1217
	"p1/Y.java",
1218
			"package p1;\n" +
1219
			"import org.eclipse.jdt.annotation.*;\n" +
1220
			"public class Y extends X implements IY {\n" +
1221
			"    @Override\n" +
1222
			"    public @Nullable String getString(String s1, @NonNull String s2, @NonNull String s3) {\n" +
1223
			"	     return \"\";\n" +
1224
			"    }\n" +
1225
			"}\n",
1226
		},
1227
		customOptions,
1228
		"----------\n" +
1229
		"1. ERROR in p1\\Y.java (at line 5)\n" +
1230
		"	public @Nullable String getString(String s1, @NonNull String s2, @NonNull String s3) {\n" +
1231
		"	       ^^^^^^^^^^^^^^^^\n" +
1232
		"The return type is incompatible with the @NonNull return from IY.getString(String, String, String)\n" +
1233
		"----------\n" +
1234
		"2. ERROR in p1\\Y.java (at line 5)\n" +
1235
		"	public @Nullable String getString(String s1, @NonNull String s2, @NonNull String s3) {\n" +
1236
		"	                                  ^^^^^^\n" +
1237
		"Missing non-null annotation: inherited method from IY declares this parameter as @NonNull\n" +
1238
		"----------\n" +
1239
		"3. ERROR in p1\\Y.java (at line 5)\n" +
1240
		"	public @Nullable String getString(String s1, @NonNull String s2, @NonNull String s3) {\n" +
1241
		"	                                             ^^^^^^^^^^^^^^^\n" +
1242
		"Illegal redefinition of parameter s2, inherited method from X declares this parameter as @Nullable\n" +
1243
		"----------\n" +
1244
		"4. ERROR in p1\\Y.java (at line 5)\n" +
1245
		"	public @Nullable String getString(String s1, @NonNull String s2, @NonNull String s3) {\n" +
1246
		"	                                                                 ^^^^^^^^^^^^^^^\n" +
1247
		"Illegal redefinition of parameter s3, inherited method from IY declares this parameter as @Nullable\n" +
1248
		"----------\n");
1249
}
1250
// methods from two super types have different null contracts.
1251
// sub-class does not override, but should to bridge the incompatibility
1252
public void test_parameter_specification_inheritance_014() {
1253
	Map customOptions = getCompilerOptions();
1254
	customOptions.put(JavaCore.COMPILER_PB_NULL_SPECIFICATION_INSUFFICIENT_INFO, JavaCore.ERROR);
1255
	runNegativeTestWithLibs(
1256
		new String[] {
1257
	"p1/IY.java",
1258
			"package p1;\n" +
1259
			"import org.eclipse.jdt.annotation.*;\n" +
1260
			"public interface IY {\n" +
1261
			"    public @NonNull String getString1(String s);\n" +
1262
			"    public @NonNull String getString2(String s);\n" +
1263
			"    public String getString3(@Nullable String s);\n" +
1264
			"    public @NonNull String getString4(@Nullable String s);\n" +
1265
			"    public @NonNull String getString5(@Nullable String s);\n" +
1266
			"    public @Nullable String getString6(@NonNull String s);\n" +
1267
			"}\n",
1268
	"p1/X.java",
1269
			"package p1;\n" +
1270
			"import org.eclipse.jdt.annotation.*;\n" +
1271
			"public class X {\n" +
1272
			"    public @Nullable String getString1(String s) {\n" + // incomp. return
1273
			"	     return s;\n" +
1274
			"    }\n" +
1275
			"    public String getString2(String s) {\n" +			 // incomp. return
1276
			"	     return s;\n" +
1277
			"    }\n" +
1278
			"    public String getString3(String s) {\n" +			 // incomp. arg
1279
			"	     return \"\";\n" +
1280
			"    }\n" +
1281
			"    public @NonNull String getString4(@Nullable String s) {\n" +
1282
			"	     return \"\";\n" +
1283
			"    }\n" +
1284
			"    public @NonNull String getString5(@NonNull String s) {\n" + // incomp. arg
1285
			"	     return s;\n" +
1286
			"    }\n" +
1287
			"    public @NonNull String getString6(@Nullable String s) {\n" +
1288
			"	     return \"\";\n" +
1289
			"    }\n" +
1290
			"}\n",
1291
	"p1/Y.java",
1292
			"package p1;\n" +
1293
			"public class Y extends X implements IY {\n" +
1294
			"}\n",
1295
		},
1296
		customOptions,
1297
		"----------\n" +
1298
		"1. ERROR in p1\\Y.java (at line 2)\n" +
1299
		"	public class Y extends X implements IY {\n" +
1300
		"	             ^\n" +
1301
		"The method getString1(String) from X cannot implement the corresponding method from IY due to incompatible nullness constraints\n" +
1302
		"----------\n" +
1303
		"2. ERROR in p1\\Y.java (at line 2)\n" +
1304
		"	public class Y extends X implements IY {\n" +
1305
		"	             ^\n" +
1306
		"The method getString2(String) from X cannot implement the corresponding method from IY due to incompatible nullness constraints\n" +
1307
		"----------\n" +
1308
		"3. ERROR in p1\\Y.java (at line 2)\n" +
1309
		"	public class Y extends X implements IY {\n" +
1310
		"	             ^\n" +
1311
		"The method getString5(String) from X cannot implement the corresponding method from IY due to incompatible nullness constraints\n" +
1312
		"----------\n" +
1313
		"4. ERROR in p1\\Y.java (at line 2)\n" +
1314
		"	public class Y extends X implements IY {\n" +
1315
		"	             ^\n" +
1316
		"The method getString3(String) from X cannot implement the corresponding method from IY due to incompatible nullness constraints\n" +
1317
		"----------\n");
1318
}
1319
// a nullable return value is dereferenced without a check
1320
public void test_nullable_return_001() {
1321
	runNegativeTestWithLibs(
1322
		new String[] {
1323
			"X.java",
1324
			"import org.eclipse.jdt.annotation.*;\n" +
1325
			"public class X {\n" +
1326
			"    @Nullable Object getObject() { return null; }\n" +
1327
			"    void foo() {\n" +
1328
			"        Object o = getObject();\n" +
1329
			"        System.out.print(o.toString());\n" +
1330
			"    }\n" +
1331
			"}\n"
1332
		},
1333
		"----------\n" +
1334
		"1. ERROR in X.java (at line 6)\n" +
1335
		"	System.out.print(o.toString());\n" +
1336
		"	                 ^\n" +
1337
		"Potential null pointer access: The variable o may be null at this location\n" +
1338
		"----------\n");
1339
}
1340
// a nullable return value is dereferenced without a check, method is read from .class file
1341
public void test_nullable_return_002() {
1342
	runConformTestWithLibs(
1343
		new String[] {
1344
			"Lib.java",
1345
			"import org.eclipse.jdt.annotation.*;\n" +
1346
			"public class Lib {\n" +
1347
			"    @Nullable Object getObject() { return null; }\n" +
1348
			"}\n"
1349
		},
1350
		null /*customOptions*/,
1351
		"");
1352
	runNegativeTestWithLibs(
1353
		false, // don't flush
1354
		new String[] {
1355
			"X.java",
1356
			"public class X {\n" +
1357
			"    void foo(Lib l) {\n" +
1358
			"        Object o = l.getObject();\n" +
1359
			"        System.out.print(o.toString());\n" +
1360
			"    }\n" +
1361
			"}\n"
1362
		},
1363
		null /*customOptions*/,
1364
		"----------\n" +
1365
		"1. ERROR in X.java (at line 4)\n" +
1366
		"	System.out.print(o.toString());\n" +
1367
		"	                 ^\n" +
1368
		"Potential null pointer access: The variable o may be null at this location\n" +
1369
		"----------\n");
1370
}
1371
// a non-null return value is checked for null, method is read from .class file
1372
public void test_nonnull_return_001() {
1373
	runConformTestWithLibs(
1374
		new String[] {
1375
			"Lib.java",
1376
			"import org.eclipse.jdt.annotation.*;\n" +
1377
			"public class Lib {\n" +
1378
			"    @NonNull Object getObject() { return new Object(); }\n" +
1379
			"}\n"
1380
		},
1381
		null /*customOptions*/,
1382
		"");
1383
	runNegativeTestWithLibs(
1384
		false, // don't flush
1385
		new String[] {
1386
			"X.java",
1387
			"public class X {\n" +
1388
			"    void foo(Lib l) {\n" +
1389
			"        Object o = l.getObject();\n" +
1390
			"        if (o != null)\n" +
1391
			"            System.out.print(o.toString());\n" +
1392
			"    }\n" +
1393
			"}\n"
1394
		},
1395
		null /*customOptions*/,
1396
		"----------\n" +
1397
		"1. ERROR in X.java (at line 4)\n" +
1398
		"	if (o != null)\n" +
1399
		"	    ^\n" +
1400
		"Redundant null check: The variable o cannot be null at this location\n" +
1401
		"----------\n");
1402
}
1403
// a non-null method returns null
1404
public void test_nonnull_return_003() {
1405
	runNegativeTestWithLibs(
1406
		new String[] {
1407
			"X.java",
1408
			"import org.eclipse.jdt.annotation.*;\n" +
1409
			"public class X {\n" +
1410
			"    @NonNull Object getObject(boolean b) {\n" +
1411
			"        if (b)\n" +
1412
			"            return null;\n" + // definite specification violation despite enclosing "if"
1413
			"        return new Object();\n" +
1414
			"    }\n" +
1415
			"}\n"
1416
		},
1417
		"----------\n" +
1418
		"1. ERROR in X.java (at line 5)\n" +
1419
		"	return null;\n" +
1420
		"	       ^^^^\n" +
1421
		"Type mismatch: required \'@NonNull Object\' but the provided value is null\n" +
1422
		"----------\n");
1423
}
1424
// a non-null method potentially returns null
1425
public void test_nonnull_return_004() {
1426
	runNegativeTestWithLibs(
1427
		new String[] {
1428
			"X.java",
1429
			"import org.eclipse.jdt.annotation.*;\n" +
1430
			"public class X {\n" +
1431
			"    @NonNull Object getObject(@Nullable Object o) {\n" +
1432
			"        return o;\n" + // 'o' is only potentially null
1433
			"    }\n" +
1434
			"}\n"
1435
		},
1436
		null /*customOptions*/,
1437
		"----------\n" +
1438
		"1. ERROR in X.java (at line 4)\n" +
1439
		"	return o;\n" +
1440
		"	       ^\n" +
1441
		"Type mismatch: required \'@NonNull Object\' but the provided value can be null\n" +
1442
		"----------\n");
1443
}
1444
// a non-null method returns its non-null argument
1445
public void test_nonnull_return_005() {
1446
	runConformTestWithLibs(
1447
		new String[] {
1448
			"X.java",
1449
			"import org.eclipse.jdt.annotation.*;\n" +
1450
			"public class X {\n" +
1451
			"    @NonNull Object getObject(@NonNull Object o) {\n" +
1452
			"        return o;\n" +
1453
			"    }\n" +
1454
			"}\n"
1455
		},
1456
		null, // options
1457
		"");
1458
}
1459
//a non-null method has insufficient nullness info for its return value
1460
public void test_nonnull_return_006() {
1461
	runNegativeTestWithLibs(
1462
		new String[] {
1463
			"X.java",
1464
			"import org.eclipse.jdt.annotation.*;\n" +
1465
			"public class X {\n" +
1466
			"    @NonNull Object getObject(Object o) {\n" +
1467
			"        return o;\n" +
1468
			"    }\n" +
1469
			"}\n"
1470
		},
1471
		"----------\n" +
1472
		"1. WARNING in X.java (at line 4)\n" +
1473
		"	return o;\n" +
1474
		"	       ^\n" +
1475
		"Potential type mismatch: required \'@NonNull Object\' but nullness of the provided value is unknown\n" +
1476
		"----------\n");
1477
}
1478
// a result from a nullable method is directly dereferenced
1479
public void test_nonnull_return_007() {
1480
	runNegativeTestWithLibs(
1481
		new String[] {
1482
			"X.java",
1483
			"import org.eclipse.jdt.annotation.*;\n" +
1484
			"public class X {\n" +
1485
			"    @Nullable Object getObject() {\n" +
1486
			"        return null;\n" +
1487
			"    }\n" +
1488
			"    void test() {\n" +
1489
			"        getObject().toString();\n" +
1490
			"    }\n" +
1491
			"}\n"
1492
		},
1493
		"----------\n" +
1494
		"1. ERROR in X.java (at line 7)\n" +
1495
		"	getObject().toString();\n" +
1496
		"	^^^^^^^^^^^\n" +
1497
		"Potential null pointer access: The method getObject() may return null\n" +
1498
		"----------\n");
1499
}
1500
// a result from a nonnull method is directly checked for null: redundant
1501
public void test_nonnull_return_008() {
1502
	Map customOptions = getCompilerOptions();
1503
	customOptions.put(JavaCore.COMPILER_PB_REDUNDANT_NULL_CHECK, JavaCore.ERROR);
1504
	runNegativeTestWithLibs(
1505
		new String[] {
1506
			"X.java",
1507
			"import org.eclipse.jdt.annotation.*;\n" +
1508
			"public class X {\n" +
1509
			"    @NonNull Object getObject() {\n" +
1510
			"        return new Object();\n" +
1511
			"    }\n" +
1512
			"    void test() {\n" +
1513
			"        if (getObject() == null)\n" +
1514
			"		     throw new RuntimeException();\n" +
1515
			"    }\n" +
1516
			"}\n"
1517
		},
1518
		customOptions,
1519
		"----------\n" +
1520
		"1. ERROR in X.java (at line 7)\n" +
1521
		"	if (getObject() == null)\n" +
1522
		"	    ^^^^^^^^^^^\n" +
1523
		"Redundant null check: The method getObject() cannot return null\n" +
1524
		"----------\n");
1525
}
1526
// a result from a nonnull method is directly checked for null (from local): redundant
1527
public void test_nonnull_return_009() {
1528
	Map customOptions = getCompilerOptions();
1529
	customOptions.put(JavaCore.COMPILER_PB_REDUNDANT_NULL_CHECK, JavaCore.ERROR);
1530
	runNegativeTestWithLibs(
1531
		new String[] {
1532
			"X.java",
1533
			"import org.eclipse.jdt.annotation.*;\n" +
1534
			"public class X {\n" +
1535
			"    @NonNull Object getObject() {\n" +
1536
			"        return new Object();\n" +
1537
			"    }\n" +
1538
			"    void test() {\n" +
1539
			"        Object left = null;\n" +
1540
			"        if (left != getObject())\n" +
1541
			"		     throw new RuntimeException();\n" +
1542
			"    }\n" +
1543
			"}\n"
1544
		},
1545
		customOptions,
1546
		"----------\n" +
1547
		"1. ERROR in X.java (at line 8)\n" +
1548
		"	if (left != getObject())\n" +
1549
		"	    ^^^^\n" +
1550
		"Redundant null check: The variable left can only be null at this location\n" +
1551
		"----------\n" +
1552
		"2. ERROR in X.java (at line 8)\n" +
1553
		"	if (left != getObject())\n" +
1554
		"	            ^^^^^^^^^^^\n" +
1555
		"Redundant null check: The method getObject() cannot return null\n" +
1556
		"----------\n");
1557
}
1558
// a result from a nonnull method is directly checked for null (from local): not redundant due to loop
1559
public void test_nonnull_return_009a() {
1560
	Map customOptions = getCompilerOptions();
1561
	customOptions.put(JavaCore.COMPILER_PB_REDUNDANT_NULL_CHECK, JavaCore.ERROR);
1562
	runConformTestWithLibs(
1563
		new String[] {
1564
			"X.java",
1565
			"import org.eclipse.jdt.annotation.*;\n" +
1566
			"public class X {\n" +
1567
			"    @NonNull Object getObject() {\n" +
1568
			"        return new Object();\n" +
1569
			"    }\n" +
1570
			"    void test() {\n" +
1571
			"        Object left = null;\n" +
1572
			"        for (int i=0; i<3; i++) {\n" +
1573
			"            if (left != getObject())\n" +
1574
			"	    	     throw new RuntimeException();\n" +
1575
			"            left = new Object();\n" +
1576
			"        }\n" +
1577
			"    }\n" +
1578
			"}\n"
1579
		},
1580
		customOptions,
1581
		"");
1582
}
1583
// a result from a nonnull method is directly checked for null (from local): redundant despite loop
1584
// disabled because only one of two desirable errors is raised
1585
// need to integrate @NonNull expressions (MessageSend and more) into deferred analysis by FlowContext
1586
public void _test_nonnull_return_009b() {
1587
	Map customOptions = getCompilerOptions();
1588
	customOptions.put(JavaCore.COMPILER_PB_REDUNDANT_NULL_CHECK, JavaCore.ERROR);
1589
	runConformTestWithLibs(
1590
		new String[] {
1591
			"X.java",
1592
			"import org.eclipse.jdt.annotation.*;\n" +
1593
			"public class X {\n" +
1594
			"    @NonNull Object getObject() {\n" +
1595
			"        return new Object();\n" +
1596
			"    }\n" +
1597
			"    void test() {\n" +
1598
			"        Object left = null;\n" +
1599
			"        for (int i=0; i<3; i++) {\n" +
1600
			"            if (left != getObject())\n" +
1601
			"	    	     throw new RuntimeException();\n" +
1602
			"            // left remains null\n" +
1603
			"        }\n" +
1604
			"    }\n" +
1605
			"}\n"
1606
		},
1607
		customOptions,
1608
		"----------\n" +
1609
		"1. ERROR in X.java (at line 9)\n" +
1610
		"	if (left != getObject())\n" +
1611
		"	    ^^^^\n" +
1612
		"Redundant null check: The variable left can only be null at this location\n" +
1613
		"----------\n" +
1614
		"2. ERROR in X.java (at line 9)\n" +
1615
		"	if (left != getObject())\n" +
1616
		"	            ^^^^^^^^^^^\n" +
1617
		"Redundant null check: The method getObject() cannot return null\n" +
1618
		"----------\n");
1619
}
1620
// a result from a nullable method is assigned and checked for null (from local): not redundant
1621
// see also Bug 336428 - [compiler][null] bogus warning "redundant null check" in condition of do {} while() loop
1622
public void test_nonnull_return_010() {
1623
	Map customOptions = getCompilerOptions();
1624
	customOptions.put(JavaCore.COMPILER_PB_REDUNDANT_NULL_CHECK, JavaCore.ERROR);
1625
	runNegativeTestWithLibs(
1626
		new String[] {
1627
			"X.java",
1628
			"import org.eclipse.jdt.annotation.*;\n" +
1629
			"public class X {\n" +
1630
			"    @Nullable X getX() {\n" +
1631
			"        return new X();\n" +
1632
			"    }\n" +
1633
			"    void test() {\n" +
1634
			"        X left = this;\n" +
1635
			"        do {\n" +
1636
			"            if (left == null) \n" +
1637
			"	   	         throw new RuntimeException();\n" +
1638
			"        } while ((left = left.getX()) != null);\n" + // no warning/error here!
1639
			"    }\n" +
1640
			"}\n"
1641
		},
1642
		customOptions,
1643
		"----------\n" +
1644
		"1. ERROR in X.java (at line 9)\n" +
1645
		"	if (left == null) \n" +
1646
		"	    ^^^^\n" +
1647
		"Null comparison always yields false: The variable left cannot be null at this location\n" +
1648
		"----------\n");
1649
}
1650
// a non-null method returns a checked-for null value, but that branch is dead code
1651
public void test_nonnull_return_011() {
1652
	Map customOptions = getCompilerOptions();
1653
	customOptions.put(JavaCore.COMPILER_PB_NULL_SPECIFICATION_INSUFFICIENT_INFO, JavaCore.ERROR);
1654
	runNegativeTestWithLibs(
1655
		new String[] {
1656
			"X.java",
1657
			"import org.eclipse.jdt.annotation.*;\n" +
1658
			"@NonNullByDefault\n" +
1659
			"public class X {\n" +
1660
			"    Object getObject(Object dubious) {\n" +
1661
			"        if (dubious == null)\n" + // redundant
1662
			"            return dubious;\n" + // definitely null, but not reported inside dead code
1663
			"        return new Object();\n" +
1664
			"    }\n" +
1665
			"}\n"
1666
		},
1667
		customOptions,
1668
		"----------\n" +
1669
		"1. ERROR in X.java (at line 5)\n" +
1670
		"	if (dubious == null)\n" +
1671
		"	    ^^^^^^^\n" +
1672
		"Null comparison always yields false: The variable dubious cannot be null at this location\n" +
1673
		"----------\n" +
1674
		"2. WARNING in X.java (at line 6)\n" +
1675
		"	return dubious;\n" +
1676
		"	^^^^^^^^^^^^^^^\n" +
1677
		"Dead code\n" +
1678
		"----------\n");
1679
}
1680
// a non-null method returns a definite null from a conditional expression
1681
// requires the fix for Bug 354554 - [null] conditional with redundant condition yields weak error message
1682
// TODO(SH): ENABLE!
1683
public void _test_nonnull_return_012() {
1684
	Map customOptions = getCompilerOptions();
1685
	customOptions.put(JavaCore.COMPILER_PB_NULL_SPECIFICATION_INSUFFICIENT_INFO, JavaCore.ERROR);
1686
	runNegativeTestWithLibs(
1687
		new String[] {
1688
			"X.java",
1689
			"import org.eclipse.jdt.annotation.*;\n" +
1690
			"@NonNullByDefault\n" +
1691
			"public class X {\n" +
1692
			"    Object getObject(Object dubious) {\n" +
1693
			"        return dubious == null ? dubious : null;\n" +
1694
			"    }\n" +
1695
			"}\n"
1696
		},
1697
		customOptions,
1698
		"----------\n" +
1699
		"1. ERROR in X.java (at line 5)\n" +
1700
		"	return dubious == null ? dubious : null;\n" +
1701
		"	       ^^^^^^^\n" +
1702
		"Null comparison always yields false: The variable dubious cannot be null at this location\n" +
1703
		"----------\n" +
1704
		"2. ERROR in X.java (at line 5)\n" +
1705
		"	return dubious == null ? dubious : null;\n" +
1706
		"	       ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^\n" +
1707
		"Type mismatch: required \'@NonNull Object\' but the provided value is null\n" +
1708
		"----------\n");
1709
}
1710
// don't apply any default annotations to return void
1711
public void test_nonnull_return_013() {
1712
	Map customOptions = getCompilerOptions();
1713
	customOptions.put(JavaCore.COMPILER_PB_NULL_SPECIFICATION_INSUFFICIENT_INFO, JavaCore.ERROR);
1714
	runConformTestWithLibs(
1715
		new String[] {
1716
			"X.java",
1717
			"import org.eclipse.jdt.annotation.*;\n" +
1718
			"@NonNullByDefault\n" +
1719
			"public class X {\n" +
1720
			"    void getObject() {}\n" +
1721
			"}\n",
1722
			"Y.java",
1723
			"public class Y extends X {\n" +
1724
			"    @Override\n" +
1725
			"    void getObject() {}\n" + // don't complain, void takes no (default) annotation
1726
			"}\n"
1727
		},
1728
		customOptions,
1729
		"");
1730
}
1731
// bug 365835: [compiler][null] inconsistent error reporting.
1732
public void test_nonnull_return_014() {
1733
	runNegativeTestWithLibs(
1734
		new String[] {
1735
			"X.java",
1736
			"import org.eclipse.jdt.annotation.NonNull;\n" + 
1737
			"\n" + 
1738
			"public class X {\n" + 
1739
			"	@NonNull\n" + 
1740
			"	public Object foo(Object x, int y) {\n" + 
1741
			"		@NonNull Object local;\n" + 
1742
			"		while (true) {\n" + 
1743
			"			if (y == 4) {\n" + 
1744
			"				local = x;  // error\n" + 
1745
			"				return x;   // only a warning.\n" + 
1746
			"			}\n" + 
1747
			"			x = null;\n" + 
1748
			"		}\n" + 
1749
			"	}\n" + 
1750
			"}"
1751
		},
1752
		"----------\n" + 
1753
		"1. ERROR in X.java (at line 9)\n" + 
1754
		"	local = x;  // error\n" + 
1755
		"	        ^\n" + 
1756
		"Type mismatch: required \'@NonNull Object\' but the provided value can be null\n" + 
1757
		"----------\n" + 
1758
		"2. ERROR in X.java (at line 10)\n" + 
1759
		"	return x;   // only a warning.\n" + 
1760
		"	       ^\n" + 
1761
		"Type mismatch: required \'@NonNull Object\' but the provided value can be null\n" + 
1762
		"----------\n");
1763
}
1764
//suppress an error regarding null-spec violation
1765
public void test_suppress_001() {
1766
	Map customOptions = getCompilerOptions();
1767
	customOptions.put(JavaCore.COMPILER_PB_SUPPRESS_OPTIONAL_ERRORS, JavaCore.ENABLED);
1768
	runConformTestWithLibs(
1769
			new String[] {
1770
				"X.java",
1771
				"import org.eclipse.jdt.annotation.*;\n" +
1772
				"public class X {\n" +
1773
				"    @SuppressWarnings(\"null\")\n" +
1774
				"    @NonNull Object getObject(@Nullable Object o) {\n" +
1775
				"        return o;\n" + // 'o' is only potentially null
1776
				"    }\n" +
1777
				"}\n"
1778
			},
1779
			customOptions,
1780
			"");
1781
}
1782
// mixed use of fully qualified name / explicit import
1783
public void test_annotation_import_001() {
1784
	Map customOptions = getCompilerOptions();
1785
	customOptions.put(JavaCore.COMPILER_NULLABLE_ANNOTATION_NAME, "org.foo.Nullable");
1786
	customOptions.put(JavaCore.COMPILER_NONNULL_ANNOTATION_NAME, "org.foo.NonNull");
1787
	runConformTestWithLibs(
1788
		new String[] {
1789
			CUSTOM_NULLABLE_NAME,
1790
			CUSTOM_NULLABLE_CONTENT,
1791
			CUSTOM_NONNULL_NAME,
1792
			CUSTOM_NONNULL_CONTENT,
1793
			"Lib.java",
1794
			"public class Lib {\n" +
1795
			"    @org.foo.NonNull Object getObject() { return new Object(); }\n" + 	// FQN
1796
			"}\n",
1797
			"X.java",
1798
			"import org.foo.NonNull;\n" +											// explicit import
1799
			"public class X {\n" +
1800
			"    @NonNull Object getObject(@NonNull Lib l) {\n" +
1801
			"        return l.getObject();\n" +
1802
			"    }\n" +
1803
			"}\n"
1804
		},
1805
		customOptions,
1806
		"");
1807
}
1808
1809
// use of explicit imports throughout
1810
public void test_annotation_import_002() {
1811
	Map customOptions = getCompilerOptions();
1812
	customOptions.put(JavaCore.COMPILER_NULLABLE_ANNOTATION_NAME, "org.foo.Nullable");
1813
	customOptions.put(JavaCore.COMPILER_NONNULL_ANNOTATION_NAME, "org.foo.NonNull");
1814
	runConformTest(
1815
		new String[] {
1816
			CUSTOM_NULLABLE_NAME,
1817
			CUSTOM_NULLABLE_CONTENT,
1818
			CUSTOM_NONNULL_NAME,
1819
			CUSTOM_NONNULL_CONTENT,
1820
			"Lib.java",
1821
			"import org.foo.NonNull;\n" +
1822
			"public class Lib {\n" +
1823
			"    @NonNull Object getObject() { return new Object(); }\n" +
1824
			"}\n",
1825
			"X.java",
1826
			"import org.foo.NonNull;\n" +
1827
			"public class X {\n" +
1828
			"    @NonNull Object getObject(@org.foo.Nullable String dummy, @NonNull Lib l) {\n" +
1829
			"        Object o = l.getObject();" +
1830
			"        return o;\n" +
1831
			"    }\n" +
1832
			"}\n"
1833
		},
1834
		customOptions,
1835
		"");
1836
}
1837
// explicit import of existing annotation types
1838
// using a Lib without null specifications
1839
public void test_annotation_import_005() {
1840
	Map customOptions = getCompilerOptions();
1841
	customOptions.put(JavaCore.COMPILER_PB_NULL_SPECIFICATION_INSUFFICIENT_INFO, JavaCore.ERROR);
1842
	customOptions.put(JavaCore.COMPILER_NULLABLE_ANNOTATION_NAME, "org.foo.MayBeNull");
1843
	customOptions.put(JavaCore.COMPILER_NONNULL_ANNOTATION_NAME, "org.foo.MustNotBeNull");
1844
	runNegativeTest(
1845
		true/*shouldFlushOutputDirectory*/,
1846
		new String[] {
1847
			"org/foo/MayBeNull.java",
1848
			"package org.foo;\n" +
1849
			"import java.lang.annotation.*;\n" +
1850
			"@Retention(RetentionPolicy.CLASS)\n" +
1851
			"public @interface MayBeNull {}\n",
1852
1853
			"org/foo/MustNotBeNull.java",
1854
			"package org.foo;\n" +
1855
			"import java.lang.annotation.*;\n" +
1856
			"@Retention(RetentionPolicy.CLASS)\n" +
1857
			"public @interface MustNotBeNull {}\n",
1858
1859
			"Lib.java",
1860
			"public class Lib {\n" +
1861
			"    Object getObject() { return new Object(); }\n" +
1862
			"}\n",
1863
			"X.java",
1864
			"import org.foo.*;\n" +
1865
			"public class X {\n" +
1866
			"    @MustNotBeNull Object getObject(@MustNotBeNull Lib l) {\n" +
1867
			"        return l.getObject();\n" +
1868
			"    }\n" +
1869
			"}\n",
1870
1871
		},
1872
		null /*no libs*/,
1873
		customOptions,
1874
		"----------\n" +
1875
		"1. ERROR in X.java (at line 4)\n" +
1876
		"	return l.getObject();\n" +
1877
		"	       ^^^^^^^^^^^^^\n" +
1878
		"Potential type mismatch: required \'@MustNotBeNull Object\' but nullness of the provided value is unknown\n" +
1879
		"----------\n",
1880
		JavacTestOptions.Excuse.EclipseWarningConfiguredAsError);
1881
}
1882
// a non-null method returns a value obtained from an unannotated method, missing annotation types
1883
public void test_annotation_import_006() {
1884
	Map customOptions = getCompilerOptions();
1885
	customOptions.put(JavaCore.COMPILER_PB_NULL_SPECIFICATION_INSUFFICIENT_INFO, JavaCore.ERROR);
1886
	customOptions.put(JavaCore.COMPILER_NULLABLE_ANNOTATION_NAME, "org.foo.MayBeNull");
1887
	customOptions.put(JavaCore.COMPILER_NONNULL_ANNOTATION_NAME, "org.foo.MustNotBeNull");
1888
	runNegativeTest(
1889
		true/*shouldFlushOutputDirectory*/,
1890
		new String[] {
1891
			"Lib.java",
1892
			"public class Lib {\n" +
1893
			"    Object getObject() { return new Object(); }\n" +
1894
			"}\n",
1895
			"X.java",
1896
			"public class X {\n" +
1897
			"    @MustNotBeNull Object getObject(@MustNotBeNull Lib l) {\n" +
1898
			"        return l.getObject();\n" +
1899
			"    }\n" +
1900
			"}\n"
1901
		},
1902
		null /* no libs */,
1903
		customOptions,
1904
		"----------\n" +
1905
		"1. ERROR in X.java (at line 2)\n" +
1906
		"	@MustNotBeNull Object getObject(@MustNotBeNull Lib l) {\n" +
1907
		"	 ^^^^^^^^^^^^^\n" +
1908
		"MustNotBeNull cannot be resolved to a type\n" +
1909
		"----------\n" +
1910
		"2. ERROR in X.java (at line 2)\n" +
1911
		"	@MustNotBeNull Object getObject(@MustNotBeNull Lib l) {\n" +
1912
		"	                                 ^^^^^^^^^^^^^\n" +
1913
		"MustNotBeNull cannot be resolved to a type\n" +
1914
		"----------\n",
1915
		JavacTestOptions.Excuse.EclipseWarningConfiguredAsError);
1916
}
1917
// using nullness defaulting to nonnull, missing annotation types, no longer a problem
1918
public void test_annotation_import_007() {
1919
	Map customOptions = getCompilerOptions();
1920
	customOptions.put(JavaCore.COMPILER_PB_NULL_SPECIFICATION_INSUFFICIENT_INFO, JavaCore.ERROR);
1921
	customOptions.put(JavaCore.COMPILER_NULLABLE_ANNOTATION_NAME, "org.foo.MayBeNull");
1922
	customOptions.put(JavaCore.COMPILER_NONNULL_ANNOTATION_NAME, "org.foo.MustNotBeNull");
1923
	customOptions.put(JavaCore.COMPILER_NONNULL_IS_DEFAULT, JavaCore.ENABLED);
1924
	runConformTestWithLibs(
1925
		new String[] {
1926
			"Lib.java",
1927
			"public class Lib {\n" +
1928
			"    Object getObject() { return new Object(); }\n" +
1929
			"}\n",
1930
			"X.java",
1931
			"public class X {\n" +
1932
			"    Object getObject(Lib l) {\n" +
1933
			"        return l.getObject();\n" +
1934
			"    }\n" +
1935
			"}\n"
1936
		},
1937
		customOptions,
1938
		"");
1939
}
1940
1941
// a null annotation is illegally used on a class:
1942
public void test_illegal_annotation_001() {
1943
	runNegativeTest(
1944
		new String[] {
1945
			"X.java",
1946
			"import org.eclipse.jdt.annotation.*;\n" +
1947
			"@NonNull public class X {\n" +
1948
			"}\n"
1949
		},
1950
		"----------\n" +
1951
		"1. ERROR in X.java (at line 2)\n" +
1952
		"	@NonNull public class X {\n" +
1953
		"	^^^^^^^^\n" +
1954
		"The annotation @NonNull is disallowed for this location\n" +
1955
		"----------\n",
1956
		this.LIBS,
1957
		false/*shouldFlush*/);
1958
}
1959
// this test has been removed:
1960
// setting default to nullable, default applies to a parameter
1961
// public void test_default_nullness_001()
1962
1963
// a null annotation is illegally defined by its simple name
1964
// disabled because specific error is not currently raised
1965
public void _test_illegal_annotation_002() {
1966
	Map customOptions = getCompilerOptions();
1967
	customOptions.put(JavaCore.COMPILER_NONNULL_ANNOTATION_NAME, "NichtNull");
1968
	runNegativeTestWithLibs(
1969
		new String[] {
1970
			"X.java",
1971
			"public class X {\n" +
1972
			"}\n"
1973
		},
1974
		customOptions,
1975
		"----------\n" +
1976
		"1. ERROR in X.java (at line 1)\n" +
1977
		"	public class X {\n" +
1978
		"	^\n" +
1979
		"Cannot use the unqualified name \'NichtNull\' as an annotation name for null specification\n" +
1980
		"----------\n");
1981
}
1982
1983
// a null annotation is illegally used on a void method:
1984
public void test_illegal_annotation_003() {
1985
	runNegativeTest(
1986
		new String[] {
1987
			"X.java",
1988
			"import org.eclipse.jdt.annotation.*;\n" +
1989
			"public class X {\n" +
1990
			"	@NonNull void foo() {}\n" +
1991
			"}\n"
1992
		},
1993
		"----------\n" +
1994
		"1. ERROR in X.java (at line 3)\n" +
1995
		"	@NonNull void foo() {}\n" +
1996
		"	^^^^^^^^^^^^^\n" +
1997
		"The nullness annotation @NonNull is not applicable for the primitive type void\n" +
1998
		"----------\n",
1999
		this.LIBS,
2000
		false/*shouldFlush*/);
2001
}
2002
2003
// a null annotation is illegally used on a primitive type parameter
2004
public void test_illegal_annotation_004() {
2005
	runNegativeTest(
2006
		new String[] {
2007
			"X.java",
2008
			"import org.eclipse.jdt.annotation.*;\n" +
2009
			"public class X {\n" +
2010
			"	void foo(@Nullable int i) {}\n" +
2011
			"}\n"
2012
		},
2013
		"----------\n" +
2014
		"1. ERROR in X.java (at line 3)\n" +
2015
		"	void foo(@Nullable int i) {}\n" +
2016
		"	         ^^^^^^^^^^^^^\n" +
2017
		"The nullness annotation @Nullable is not applicable for the primitive type int\n" +
2018
		"----------\n",
2019
		this.LIBS,
2020
		false/*shouldFlush*/);
2021
}
2022
2023
// a null annotation is illegally used on a primitive type local var
2024
public void test_illegal_annotation_005() {
2025
	runNegativeTest(
2026
		new String[] {
2027
			"X.java",
2028
			"import org.eclipse.jdt.annotation.*;\n" +
2029
			"public class X {\n" +
2030
			"	int foo() {\n" +
2031
			"       @Nullable int i = 3;\n" +
2032
			"       return i;\n" +
2033
			"   }\n" +
2034
			"}\n"
2035
		},
2036
		"----------\n" +
2037
		"1. ERROR in X.java (at line 4)\n" +
2038
		"	@Nullable int i = 3;\n" +
2039
		"	^^^^^^^^^^^^^\n" +
2040
		"The nullness annotation @Nullable is not applicable for the primitive type int\n" +
2041
		"----------\n",
2042
		this.LIBS,
2043
		false/*shouldFlush*/);
2044
}
2045
2046
// a configured annotation type does not exist
2047
// see https://bugs.eclipse.org/bugs/show_bug.cgi?id=186342#c133
2048
public void test_illegal_annotation_006() {
2049
	Map customOptions = getCompilerOptions();
2050
	customOptions.put(JavaCore.COMPILER_NULLABLE_ANNOTATION_NAME, "nullAnn.Nullable");
2051
	runNegativeTestWithLibs(
2052
		new String[] {
2053
			"p/Test.java",
2054
			"package p;\n" +
2055
			"import nullAnn.*;  // 1 \n" +
2056
			"\n" +
2057
			"public class Test { \n" +
2058
			"\n" +
2059
			"        void foo(@nullAnn.Nullable  Object o) {   // 2\n" +
2060
			"            o.toString();           \n" +
2061
			"        }\n" +
2062
			"}"
2063
		},
2064
		customOptions,
2065
		"----------\n" +
2066
		"1. ERROR in p\\Test.java (at line 2)\n" +
2067
		"	import nullAnn.*;  // 1 \n" +
2068
		"	       ^^^^^^^\n" +
2069
		"The import nullAnn cannot be resolved\n" +
2070
		"----------\n" +
2071
		"2. ERROR in p\\Test.java (at line 6)\n" +
2072
		"	void foo(@nullAnn.Nullable  Object o) {   // 2\n" +
2073
		"	          ^^^^^^^\n" +
2074
		"nullAnn cannot be resolved to a type\n" +
2075
		"----------\n");
2076
}
2077
2078
// a configured annotation type does not exist
2079
// see https://bugs.eclipse.org/bugs/show_bug.cgi?id=186342#c186
2080
public void test_illegal_annotation_007() {
2081
	Map customOptions = getCompilerOptions();
2082
	runNegativeTestWithLibs(
2083
		new String[] {
2084
			"p/Test.java",
2085
			"package p;\n" +
2086
			"import org.eclipse.jdt.annotation.*;\n" +
2087
			"interface TestInt{\n" +
2088
			"	@NonNull Object foo();\n" +
2089
			"}\n" +
2090
			"\n" +
2091
			"public class Test { \n" +
2092
			"	void bar() {" +
2093
			"		new TestInt() {\n" +
2094
			"        	@org public Object foo() {\n" +
2095
			"        	}\n" +
2096
			"		};\n" +
2097
			"	}\n" +
2098
			"}"
2099
		},
2100
		customOptions,
2101
		"----------\n" + 
2102
		"1. ERROR in p\\Test.java (at line 9)\n" + 
2103
		"	@org public Object foo() {\n" + 
2104
		"	 ^^^\n" + 
2105
		"org cannot be resolved to a type\n" + 
2106
		"----------\n" + 
2107
		"2. ERROR in p\\Test.java (at line 9)\n" + 
2108
		"	@org public Object foo() {\n" + 
2109
		"	            ^^^^^^\n" + 
2110
		"The return type is incompatible with the @NonNull return from TestInt.foo()\n" + 
2111
		"----------\n");
2112
}
2113
2114
public void test_default_nullness_002() {
2115
	Map customOptions = getCompilerOptions();
2116
//	customOptions.put(CompilerOptions.OPTION_ReportPotentialNullSpecViolation, JavaCore.ERROR);
2117
// This option currently does nothing:
2118
//	customOptions.put(JavaCore.COMPILER_NONNULL_IS_DEFAULT, JavaCore.ENABLED);
2119
	runNegativeTestWithLibs(
2120
		new String[] {
2121
			"X.java",
2122
			"import org.eclipse.jdt.annotation.*;\n" +
2123
			"@NonNullByDefault\n" +
2124
			"public class X {\n" +
2125
			"    Object getObject(@Nullable Object o) {\n" +
2126
			"        return new Object();\n" +
2127
			"    }\n" +
2128
			"}\n",
2129
			"Y.java",
2130
			"import org.eclipse.jdt.annotation.*;\n" +
2131
			"@NonNullByDefault\n" +
2132
			"public class Y extends X {\n" +
2133
			"    @Override\n" +
2134
			"    @Nullable Object getObject(Object o) {\n" + // complain illegal return redef and inherited annot is not repeated
2135
			"        return o;\n" +
2136
			"    }\n" +
2137
			"}\n",
2138
		},
2139
		customOptions,
2140
		// main error:
2141
		"----------\n" +
2142
		"1. ERROR in Y.java (at line 5)\n" +
2143
		"	@Nullable Object getObject(Object o) {\n" +
2144
		"	^^^^^^^^^^^^^^^^\n" +
2145
		"The return type is incompatible with the @NonNull return from X.getObject(Object)\n" +
2146
		"----------\n" +
2147
		// additional error:
2148
		"2. ERROR in Y.java (at line 5)\n" +
2149
		"	@Nullable Object getObject(Object o) {\n" +
2150
		"	                           ^^^^^^\n" +
2151
		"Illegal redefinition of parameter o, inherited method from X declares this parameter as @Nullable\n" +
2152
		"----------\n");
2153
}
2154
// package default is non-null
2155
public void test_default_nullness_003() {
2156
	Map customOptions = getCompilerOptions();
2157
//	customOptions.put(CompilerOptions.OPTION_ReportPotentialNullSpecViolation, JavaCore.ERROR);
2158
	runNegativeTestWithLibs(
2159
		new String[] {
2160
	"p1/X.java",
2161
			"package p1;\n" +
2162
			"import org.eclipse.jdt.annotation.*;\n" +
2163
			"@NonNullByDefault\n" +
2164
			"public class X {\n" +
2165
			"    protected Object getObject(@Nullable Object o) {\n" +
2166
			"        return new Object();\n" +
2167
			"    }\n" +
2168
			"}\n",
2169
	"p2/package-info.java",
2170
			"@org.eclipse.jdt.annotation.NonNullByDefault\n" +
2171
			"package p2;\n",
2172
	"p2/Y.java",
2173
			"package p2;\n" +
2174
			"import org.eclipse.jdt.annotation.*;\n" +
2175
			"public class Y extends p1.X {\n" +
2176
			"    @Override\n" +
2177
			"    protected @Nullable Object getObject(@Nullable Object o) {\n" +
2178
			"        bar(o);\n" +
2179
			"        return o;\n" +
2180
			"    }\n" +
2181
			"	 void bar(Object o2) { }\n" + // parameter is nonnull per package default
2182
			"}\n"
2183
		},
2184
		customOptions,
2185
		"----------\n" +
2186
		"1. ERROR in p2\\Y.java (at line 5)\n" +
2187
		"	protected @Nullable Object getObject(@Nullable Object o) {\n" +
2188
		"	          ^^^^^^^^^^^^^^^^\n" +
2189
		"The return type is incompatible with the @NonNull return from X.getObject(Object)\n" +
2190
		"----------\n" +
2191
		"2. ERROR in p2\\Y.java (at line 6)\n" +
2192
		"	bar(o);\n" +
2193
		"	    ^\n" +
2194
		"Type mismatch: required \'@NonNull Object\' but the provided value can be null\n" +
2195
		"----------\n");
2196
}
2197
// package level default is consumed from package-info.class, similarly for type level default
2198
public void test_default_nullness_003a() {
2199
	Map customOptions = getCompilerOptions();
2200
//	customOptions.put(CompilerOptions.OPTION_ReportPotentialNullSpecViolation, JavaCore.ERROR);
2201
	runConformTestWithLibs(
2202
		new String[] {
2203
	"p1/X.java",
2204
			"package p1;\n" +
2205
			"import org.eclipse.jdt.annotation.*;\n" +
2206
			"@NonNullByDefault\n" +
2207
			"public class X {\n" +
2208
			"    protected Object getObject(@Nullable Object o) {\n" +
2209
			"        return new Object();\n" +
2210
			"    }\n" +
2211
			"	 protected void bar(Object o2) { }\n" + // parameter is nonnull per type default
2212
			"}\n",
2213
	"p2/package-info.java",
2214
			"@org.eclipse.jdt.annotation.NonNullByDefault\n" +
2215
			"package p2;\n",
2216
			},
2217
			customOptions,
2218
			"");
2219
	// check if default is visible from package-info.class.
2220
	runNegativeTestWithLibs(
2221
		false, // don't flush
2222
		new String[] {
2223
	"p2/Y.java",
2224
			"package p2;\n" +
2225
			"import org.eclipse.jdt.annotation.*;\n" +
2226
			"public class Y extends p1.X {\n" +
2227
			"    @Override\n" +
2228
			"    protected @Nullable Object getObject(@Nullable Object o) {\n" + // can't override inherited default nonnull
2229
			"        bar(o);\n" + // parameter is nonnull in super class's .class file
2230
			"        accept(o);\n" +
2231
			"        return o;\n" +
2232
			"    }\n" +
2233
			"    void accept(Object a) {}\n" + // governed by package level default
2234
			"}\n"
2235
		},
2236
		customOptions,
2237
		"----------\n" +
2238
		"1. ERROR in p2\\Y.java (at line 5)\n" +
2239
		"	protected @Nullable Object getObject(@Nullable Object o) {\n" +
2240
		"	          ^^^^^^^^^^^^^^^^\n" +
2241
		"The return type is incompatible with the @NonNull return from X.getObject(Object)\n" +
2242
		"----------\n" +
2243
		"2. ERROR in p2\\Y.java (at line 6)\n" +
2244
		"	bar(o);\n" +
2245
		"	    ^\n" +
2246
		"Type mismatch: required \'@NonNull Object\' but the provided value can be null\n" +
2247
		"----------\n" +
2248
		"3. ERROR in p2\\Y.java (at line 7)\n" +
2249
		"	accept(o);\n" +
2250
		"	       ^\n" +
2251
		"Type mismatch: required \'@NonNull Object\' but the provided value can be null\n" +
2252
		"----------\n");
2253
}
2254
// same as test_default_nullness_003a, but default-induced annotations are combined with explicit ones (not null related)
2255
public void test_default_nullness_003b() {
2256
	Map customOptions = getCompilerOptions();
2257
	runConformTestWithLibs(
2258
		new String[] {
2259
	"p1/Annot.java",
2260
			"package p1;\n" +
2261
			"import static java.lang.annotation.ElementType.*;\n" +
2262
			"import java.lang.annotation.*;\n" +
2263
			"@Retention(RetentionPolicy.CLASS)\n" +
2264
			"@Target({METHOD,PARAMETER})\n" +
2265
			"public @interface Annot {}\n",
2266
	"p1/X.java",
2267
			"package p1;\n" +
2268
			"import org.eclipse.jdt.annotation.*;\n" +
2269
			"@NonNullByDefault\n" +
2270
			"public class X {\n" +
2271
			"    protected @Annot Object getObject(@Annot @Nullable Object o) {\n" +
2272
			"        return new Object();\n" +
2273
			"    }\n" +
2274
			"	 protected @Annot void bar(@Annot Object o2) { }\n" + // parameter is nonnull per type default
2275
			"}\n",
2276
	"p2/package-info.java",
2277
			"@org.eclipse.jdt.annotation.NonNullByDefault\n" +
2278
			"package p2;\n",
2279
			},
2280
			customOptions,
2281
			"");
2282
	// check if default is visible from package-info.class.
2283
	runNegativeTestWithLibs(
2284
		false, // don't flush
2285
		new String[] {
2286
	"p2/Y.java",
2287
			"package p2;\n" +
2288
			"import org.eclipse.jdt.annotation.*;\n" +
2289
			"public class Y extends p1.X {\n" +
2290
			"    @Override\n" +
2291
			"    protected @Nullable Object getObject(@Nullable Object o) {\n" + // can't override inherited default nonnull
2292
			"        bar(o);\n" + // parameter is nonnull in super class's .class file
2293
			"        accept(o);\n" +
2294
			"        return o;\n" +
2295
			"    }\n" +
2296
			"    void accept(@p1.Annot Object a) {}\n" + // governed by package level default
2297
			"}\n"
2298
		},
2299
		customOptions,
2300
		"----------\n" +
2301
		"1. ERROR in p2\\Y.java (at line 5)\n" +
2302
		"	protected @Nullable Object getObject(@Nullable Object o) {\n" +
2303
		"	          ^^^^^^^^^^^^^^^^\n" +
2304
		"The return type is incompatible with the @NonNull return from X.getObject(Object)\n" +
2305
		"----------\n" +
2306
		"2. ERROR in p2\\Y.java (at line 6)\n" +
2307
		"	bar(o);\n" +
2308
		"	    ^\n" +
2309
		"Type mismatch: required \'@NonNull Object\' but the provided value can be null\n" +
2310
		"----------\n" +
2311
		"3. ERROR in p2\\Y.java (at line 7)\n" +
2312
		"	accept(o);\n" +
2313
		"	       ^\n" +
2314
		"Type mismatch: required \'@NonNull Object\' but the provided value can be null\n" +
2315
		"----------\n");
2316
}
2317
// don't apply type-level default to non-reference type
2318
public void test_default_nullness_004() {
2319
	Map customOptions = getCompilerOptions();
2320
//	customOptions.put(CompilerOptions.OPTION_ReportPotentialNullSpecViolation, JavaCore.ERROR);
2321
	runConformTestWithLibs(
2322
		new String[] {
2323
	"p1/X.java",
2324
			"package p1;\n" +
2325
			"import org.eclipse.jdt.annotation.*;\n" +
2326
			"@NonNullByDefault\n" +
2327
			"public class X {\n" +
2328
			"    protected Object getObject(boolean o) {\n" +
2329
			"        return new Object();\n" +
2330
			"    }\n" +
2331
			"}\n",
2332
	"p2/Y.java",
2333
			"package p2;\n" +
2334
			"import org.eclipse.jdt.annotation.*;\n" +
2335
			"public class Y extends p1.X {\n" +
2336
			"    @Override\n" +
2337
			"    protected @NonNull Object getObject(boolean o) {\n" +
2338
			"        return o ? this : new Object();\n" +
2339
			"    }\n" +
2340
			"}\n"
2341
		},
2342
		customOptions,
2343
		"");
2344
}
2345
// package default is non-null
2346
// see also Bug 354536 - compiling package-info.java still depends on the order of compilation units
2347
public void test_default_nullness_005() {
2348
	Map customOptions = getCompilerOptions();
2349
//	customOptions.put(CompilerOptions.OPTION_ReportPotentialNullSpecViolation, JavaCore.ERROR);
2350
	customOptions.put(JavaCore.COMPILER_NONNULL_ANNOTATION_NAME, "org.foo.NonNull");
2351
	runNegativeTestWithLibs(
2352
		new String[] {
2353
	"p1/X.java",
2354
			"package p1;\n" +
2355
			"public class X {\n" +
2356
			"    class Inner {" +
2357
			"        protected Object getObject(String s) {\n" +
2358
			"            return null;\n" +
2359
			"        }\n" +
2360
			"    }\n" +
2361
			"}\n",
2362
	"p1/package-info.java",
2363
			"@org.eclipse.jdt.annotation.NonNullByDefault\n" +
2364
			"package p1;\n",
2365
	CUSTOM_NONNULL_NAME,
2366
			CUSTOM_NONNULL_CONTENT
2367
		},
2368
		customOptions,
2369
		"----------\n" +
2370
		"1. ERROR in p1\\X.java (at line 4)\n" +
2371
		"	return null;\n" +
2372
		"	       ^^^^\n" +
2373
		"Type mismatch: required \'@NonNull Object\' but the provided value is null\n" +
2374
		"----------\n");
2375
}
2376
// package default is non-null, package-info.java read before the annotation type
2377
// compile order: beginToCompile(X.Inner) triggers reading of package-info.java before the annotation type was read
2378
public void test_default_nullness_006() {
2379
	Map customOptions = getCompilerOptions();
2380
//	customOptions.put(CompilerOptions.OPTION_ReportPotentialNullSpecViolation, JavaCore.ERROR);
2381
	customOptions.put(JavaCore.COMPILER_NONNULL_ANNOTATION_NAME, "org.foo.NonNull");
2382
	runNegativeTestWithLibs(
2383
		new String[] {
2384
	"p1/package-info.java",
2385
			"@org.eclipse.jdt.annotation.NonNullByDefault\n" +
2386
			"package p1;\n",
2387
	"p1/X.java",
2388
			"package p1;\n" +
2389
			"public class X {\n" +
2390
			"    class Inner {" +
2391
			"        protected Object getObject(String s) {\n" +
2392
			"            return null;\n" +
2393
			"        }\n" +
2394
			"    }\n" +
2395
			"}\n",
2396
	CUSTOM_NONNULL_NAME,
2397
			CUSTOM_NONNULL_CONTENT
2398
		},
2399
		customOptions,
2400
		"----------\n" +
2401
		"1. ERROR in p1\\X.java (at line 4)\n" +
2402
		"	return null;\n" +
2403
		"	       ^^^^\n" +
2404
		"Type mismatch: required \'@NonNull Object\' but the provided value is null\n" +
2405
		"----------\n");
2406
}
2407
// global default nonnull, but return may be null
2408
// DISABLED due to dysfunctional global default after Bug 366063 - Compiler should not add synthetic @NonNull annotations
2409
public void _test_default_nullness_007() {
2410
	Map customOptions = getCompilerOptions();
2411
//	customOptions.put(CompilerOptions.OPTION_ReportPotentialNullSpecViolation, JavaCore.ERROR);
2412
	customOptions.put(JavaCore.COMPILER_NONNULL_IS_DEFAULT, JavaCore.ENABLED);
2413
	runNegativeTestWithLibs(
2414
		new String[] {
2415
			"X.java",
2416
			"import org.eclipse.jdt.annotation.*;\n" +
2417
			"public class X {\n" +
2418
			"    @Nullable Object dangerous() {\n" +
2419
			"        return null;\n" +
2420
			"    }\n" +
2421
			"    Object broken() {\n" +
2422
			"        return dangerous();\n" +
2423
			"    }\n" +
2424
			"}\n",
2425
2426
		},
2427
		customOptions,
2428
		"----------\n" +
2429
		"1. ERROR in X.java (at line 7)\n" +
2430
		"	return dangerous();\n" +
2431
		"	       ^^^^^^^^^^^\n" +
2432
		"Type mismatch: required \'@NonNull Object\' but the provided value can be null\n" +
2433
		"----------\n");
2434
}
2435
2436
// cancel type level default to comply with super specification
2437
public void test_default_nullness_008() {
2438
	Map customOptions = getCompilerOptions();
2439
//	customOptions.put(CompilerOptions.OPTION_ReportPotentialNullSpecViolation, JavaCore.ERROR);
2440
	runConformTestWithLibs(
2441
		new String[] {
2442
	"p1/X.java",
2443
			"package p1;\n" +
2444
			"public class X {\n" +
2445
			"    protected Object getObject(Object o) {\n" +
2446
			"        return new Object();\n" +
2447
			"    }\n" +
2448
			"}\n",
2449
	"p2/Y.java",
2450
			"package p2;\n" +
2451
			"import org.eclipse.jdt.annotation.*;\n" +
2452
			"@NonNullByDefault\n" +
2453
			"public class Y extends p1.X {\n" +
2454
			"    @Override\n" +
2455
			"    @NonNullByDefault(false)\n" +
2456
			"    protected Object getObject(Object o) {\n" +
2457
			"        if (o.toString().length() == 0)\n" + // dereference without a warning
2458
			"	        return null;\n" + // return null without a warning
2459
			"        return o.toString();\n" +
2460
			"    }\n" +
2461
			"}\n"
2462
		},
2463
		customOptions,
2464
		"");
2465
}
2466
2467
// cancel outer type level default to comply with super specification
2468
public void test_default_nullness_009() {
2469
	Map customOptions = getCompilerOptions();
2470
//	customOptions.put(CompilerOptions.OPTION_ReportPotentialNullSpecViolation, JavaCore.ERROR);
2471
	runNegativeTestWithLibs(
2472
		new String[] {
2473
	"p1/X.java",
2474
			"package p1;\n" +
2475
			"public class X {\n" +
2476
			"    protected Object getObject(Object o) {\n" +
2477
			"        return new Object();\n" +
2478
			"    }\n" +
2479
			"}\n",
2480
	"p2/Y.java",
2481
			"package p2;\n" +
2482
			"import org.eclipse.jdt.annotation.*;\n" +
2483
			"@NonNullByDefault\n" +
2484
			"public class Y { \n" +
2485
			"    @NonNullByDefault(false)\n" +
2486
			"    static class Z extends p1.X {\n" +
2487
			"        @Override\n" +
2488
			"        protected Object getObject(Object o) {\n" +
2489
			"            if (o.toString().length() == 0) {\n" +
2490
			"                o = null;\n" + // assign null without a warning
2491
			"                bar(o); // error: arg is declared @NonNull\n" +
2492
			"	             return null;\n" +
2493
			"            }\n" +
2494
			"            return o.toString();\n" +
2495
			"        }\n" +
2496
			"        String bar(@NonNull Object o) {\n" +
2497
			"            return getObject(o).toString();" +
2498
			"        }\n" +
2499
			"    }\n" +
2500
			"}\n"
2501
		},
2502
		customOptions,
2503
		"----------\n" +
2504
		"1. ERROR in p2\\Y.java (at line 11)\n" +
2505
		"	bar(o); // error: arg is declared @NonNull\n" +
2506
		"	    ^\n" +
2507
		"Type mismatch: required \'@NonNull Object\' but the provided value is null\n" +
2508
		"----------\n");
2509
}
2510
// non-null declarations are redundant within a default scope.
2511
public void test_default_nullness_010() {
2512
	Map customOptions = getCompilerOptions();
2513
//	customOptions.put(CompilerOptions.OPTION_ReportPotentialNullSpecViolation, JavaCore.ERROR);
2514
	runConformTestWithLibs(
2515
		new String[] {
2516
	"p2/Y.java",
2517
			"package p2;\n" +
2518
			"import org.eclipse.jdt.annotation.*;\n" +
2519
			"@NonNullByDefault\n" +
2520
			"public class Y {\n" +
2521
			"    protected @NonNull Object getObject(@NonNull Object o) {\n" +
2522
			"        return o;\n" +
2523
			"    }\n" +
2524
			"}\n"
2525
		},
2526
		customOptions,
2527
		"----------\n" +
2528
		"1. WARNING in p2\\Y.java (at line 5)\n" +
2529
		"	protected @NonNull Object getObject(@NonNull Object o) {\n" +
2530
		"	          ^^^^^^^^^^^^^^^\n" +
2531
		"The nullness annotation is redundant with a default that applies to this location\n" +
2532
		"----------\n" +
2533
		"2. WARNING in p2\\Y.java (at line 5)\n" +
2534
		"	protected @NonNull Object getObject(@NonNull Object o) {\n" +
2535
		"	                                    ^^^^^^^^^^^^^^^^^\n" +
2536
		"The nullness annotation is redundant with a default that applies to this location\n" +
2537
		"----------\n");
2538
}
2539
// package-info declares nonnull-by-default
2540
// special compile order due to import of type from that package
2541
// cf. https://bugs.eclipse.org/bugs/show_bug.cgi?id=186342#add_comment
2542
public void test_default_nullness_011() {
2543
	runNegativeTestWithLibs(
2544
		new String[] {
2545
			"Main.java",
2546
			"import p1.C;\n" +
2547
			"public class Main {\n" +
2548
			"    void test(@org.eclipse.jdt.annotation.NonNull Object o) {\n" +
2549
			"        o = null;\n" +
2550
			"        new C(null);\n" +
2551
			"    }\n" +
2552
			"}\n",
2553
			"p1/C.java",
2554
			"package p1;\n" +
2555
			"@org.eclipse.jdt.annotation.NonNullByDefault\n" +
2556
			"public class C {\n" +
2557
			"    public C (Object o) {}\n" +
2558
			"}\n",
2559
			"p1/package-info.java",
2560
			"@org.eclipse.jdt.annotation.NonNullByDefault\n" +
2561
			"package p1;\n"
2562
		},
2563
		"----------\n" + 
2564
		"1. ERROR in Main.java (at line 4)\n" + 
2565
		"	o = null;\n" + 
2566
		"	    ^^^^\n" + 
2567
		"Type mismatch: required \'@NonNull Object\' but the provided value is null\n" + 
2568
		"----------\n" + 
2569
		"2. ERROR in Main.java (at line 5)\n" + 
2570
		"	new C(null);\n" + 
2571
		"	      ^^^^\n" + 
2572
		"Type mismatch: required \'@NonNull Object\' but the provided value is null\n" + 
2573
		"----------\n" + 
2574
		"----------\n" + 
2575
		"1. WARNING in p1\\C.java (at line 2)\n" + 
2576
		"	@org.eclipse.jdt.annotation.NonNullByDefault\n" + 
2577
		"	^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^\n" + 
2578
		"Nullness default is redundant with a default specified for the enclosing package p1\n" + 
2579
		"----------\n");
2580
}
2581
// Bug 365836 - [compiler][null] Incomplete propagation of null defaults.
2582
public void test_default_nullness_012() {
2583
	runNegativeTestWithLibs(
2584
		new String[] {
2585
			"X.java",
2586
			"import org.eclipse.jdt.annotation.NonNullByDefault;\n" + 
2587
			"import org.eclipse.jdt.annotation.Nullable;\n" + 
2588
			"\n" + 
2589
			"public class X {\n" + 
2590
			"    @NonNullByDefault \n" + 
2591
			"    public void foo(@Nullable String [] args) {\n" + 
2592
			"        class local {\n" + 
2593
			"            void zoo(Object o) {\n" + 
2594
			"            }\n" + 
2595
			"        };\n" + 
2596
			"        new local().zoo(null); // defaults applying from foo\n" + 
2597
			"    }\n" + 
2598
			"}"
2599
		},
2600
		"----------\n" + 
2601
		"1. ERROR in X.java (at line 11)\n" + 
2602
		"	new local().zoo(null); // defaults applying from foo\n" + 
2603
		"	                ^^^^\n" + 
2604
		"Type mismatch: required \'@NonNull Object\' but the provided value is null\n" + 
2605
		"----------\n");
2606
}
2607
// Bug 365836 - [compiler][null] Incomplete propagation of null defaults.
2608
public void test_default_nullness_013() {
2609
	runNegativeTestWithLibs(
2610
		new String[] {
2611
			"X.java",
2612
			"import org.eclipse.jdt.annotation.NonNullByDefault;\n" + 
2613
			"import org.eclipse.jdt.annotation.Nullable;\n" + 
2614
			"\n" +
2615
			"@SuppressWarnings(\"unused\")\n" +
2616
			"public class X {\n" + 
2617
			"    @NonNullByDefault \n" + 
2618
			"    public void foo(@Nullable String [] args) {\n" + 
2619
			"        class local {\n" +
2620
			"            class Deeply {\n" + 
2621
			"                Object zoo() {\n" +
2622
			"                    return null; // defaults applying from foo\n" +
2623
			"                }\n" + 
2624
			"            }\n" + 
2625
			"        };\n" + 
2626
			"    }\n" + 
2627
			"}"
2628
		},
2629
		"----------\n" + 
2630
		"1. ERROR in X.java (at line 11)\n" + 
2631
		"	return null; // defaults applying from foo\n" + 
2632
		"	       ^^^^\n" + 
2633
		"Type mismatch: required \'@NonNull Object\' but the provided value is null\n" + 
2634
		"----------\n");
2635
}
2636
// bug 367154 - [compiler][null] Problem in propagating null defaults.
2637
public void test_default_nullness_014() {
2638
	runNegativeTestWithLibs(
2639
		new String[] {
2640
			"X.java",
2641
			"import org.eclipse.jdt.annotation.NonNullByDefault;\n" + 
2642
			"import org.eclipse.jdt.annotation.Nullable;\n" + 
2643
			"\n" + 
2644
			"@SuppressWarnings(\"unused\")\n" + 
2645
			"public class X {\n" + 
2646
			"\n" + 
2647
			"    public void foo(@Nullable String [] args) {\n" + 
2648
			"        @NonNullByDefault\n" + 
2649
			"        class local {\n" + 
2650
			"            class Deeply {\n" + 
2651
			"                Object zoo() {\n" + 
2652
			"                    return null;  // expect error here\n" + 
2653
			"                }\n" + 
2654
			"            }\n" + 
2655
			"        };\n" + 
2656
			"    }\n" + 
2657
			"}"
2658
		},
2659
		"----------\n" + 
2660
		"1. ERROR in X.java (at line 12)\n" + 
2661
		"	return null;  // expect error here\n" + 
2662
		"	       ^^^^\n" + 
2663
		"Type mismatch: required \'@NonNull Object\' but the provided value is null\n" + 
2664
		"----------\n");
2665
}
2666
// bug 367154 - [compiler][null] Problem in propagating null defaults.
2667
// initializer involved
2668
public void test_default_nullness_015() {
2669
	runNegativeTestWithLibs(
2670
		new String[] {
2671
			"X.java",
2672
			"import org.eclipse.jdt.annotation.NonNullByDefault;\n" + 
2673
			"import org.eclipse.jdt.annotation.Nullable;\n" + 
2674
			"\n" + 
2675
			"@SuppressWarnings(\"unused\")\n" + 
2676
			"@NonNullByDefault\n" + 
2677
			"public class X {\n" + 
2678
			"    {\n" + 
2679
			"        class local {\n" + 
2680
			"            class Deeply {\n" + 
2681
			"                Object zoo() {\n" + 
2682
			"                    return null;  // expect error here\n" + 
2683
			"                }\n" + 
2684
			"            }\n" + 
2685
			"        };\n" + 
2686
			"    }\n" + 
2687
			"}"
2688
		},
2689
		"----------\n" + 
2690
		"1. ERROR in X.java (at line 11)\n" + 
2691
		"	return null;  // expect error here\n" + 
2692
		"	       ^^^^\n" + 
2693
		"Type mismatch: required \'@NonNull Object\' but the provided value is null\n" + 
2694
		"----------\n");
2695
}
2696
2697
// redundant default annotations - class vs. inner class
2698
public void test_redundant_annotation_01() {
2699
	Map customOptions = getCompilerOptions();
2700
//	customOptions.put(CompilerOptions.OPTION_ReportPotentialNullSpecViolation, JavaCore.ERROR);
2701
	runConformTestWithLibs(
2702
		new String[] {
2703
			"p2/Y.java",
2704
			"package p2;\n" +
2705
			"import org.eclipse.jdt.annotation.*;\n" +
2706
			"@NonNullByDefault\n" +
2707
			"public class Y {\n" +
2708
			"    @NonNullByDefault class Inner {\n" +
2709
			"        @NonNullByDefault class DeepInner {}\n" +
2710
			"    }\n" +
2711
			"    class Inner2 {\n" +
2712
			"        @NonNullByDefault class DeepInner2 {\n" +
2713
			"        }\n" +
2714
			"        void foo() {\n" +
2715
			"            @SuppressWarnings(\"unused\") @NonNullByDefault class Local {}\n" +
2716
			"        }\n" +
2717
			"    }\n" +
2718
			"}\n" +
2719
			"@NonNullByDefault class V {}\n",
2720
			"p3/package-info.java",
2721
			"@org.eclipse.jdt.annotation.NonNullByDefault package p3;\n",
2722
			"p3/Z.java",
2723
			"package p3;\n" +
2724
			"import org.eclipse.jdt.annotation.*;\n" +
2725
			"@NonNullByDefault\n" +
2726
			"public class Z {\n" +
2727
			"}\n" +
2728
			"class X {\n" +
2729
			"    @NonNullByDefault class Inner {}\n" +
2730
			"    class Inner2 {\n" +
2731
			"        @NonNullByDefault class DeepInner {}\n" +
2732
			"    }\n" +
2733
			"}\n"
2734
		},
2735
		customOptions,
2736
		"----------\n" + 
2737
		"1. WARNING in p2\\Y.java (at line 5)\n" +
2738
		"	@NonNullByDefault class Inner {\n" +
2739
		"	^^^^^^^^^^^^^^^^^\n" +
2740
		"Nullness default is redundant with a default specified for the enclosing type Y\n" +
2741
		"----------\n" +
2742
		"2. WARNING in p2\\Y.java (at line 6)\n" +
2743
		"	@NonNullByDefault class DeepInner {}\n" +
2744
		"	^^^^^^^^^^^^^^^^^\n" +
2745
		"Nullness default is redundant with a default specified for the enclosing type Y.Inner\n" +
2746
		"----------\n" +
2747
		"3. WARNING in p2\\Y.java (at line 9)\n" +
2748
		"	@NonNullByDefault class DeepInner2 {\n" +
2749
		"	^^^^^^^^^^^^^^^^^\n" +
2750
		"Nullness default is redundant with a default specified for the enclosing type Y\n" +
2751
		"----------\n" +
2752
		"4. WARNING in p2\\Y.java (at line 12)\n" +
2753
		"	@SuppressWarnings(\"unused\") @NonNullByDefault class Local {}\n" +
2754
		"	                            ^^^^^^^^^^^^^^^^^\n" +
2755
		"Nullness default is redundant with a default specified for the enclosing type Y\n" +
2756
		"----------\n" +
2757
		"----------\n" +
2758
		"1. WARNING in p3\\Z.java (at line 3)\n" +
2759
		"	@NonNullByDefault\n" +
2760
		"	^^^^^^^^^^^^^^^^^\n" +
2761
		"Nullness default is redundant with a default specified for the enclosing package p3\n" +
2762
		"----------\n" +
2763
		"2. WARNING in p3\\Z.java (at line 7)\n" +
2764
		"	@NonNullByDefault class Inner {}\n" +
2765
		"	^^^^^^^^^^^^^^^^^\n" +
2766
		"Nullness default is redundant with a default specified for the enclosing package p3\n" +
2767
		"----------\n" +
2768
		"3. WARNING in p3\\Z.java (at line 9)\n" +
2769
		"	@NonNullByDefault class DeepInner {}\n" +
2770
		"	^^^^^^^^^^^^^^^^^\n" +
2771
		"Nullness default is redundant with a default specified for the enclosing package p3\n" +
2772
		"----------\n");
2773
}
2774
2775
// redundant default annotations - class vs. method
2776
public void test_redundant_annotation_02() {
2777
	Map customOptions = getCompilerOptions();
2778
	runConformTestWithLibs(
2779
		new String[] {
2780
			"p2/Y.java",
2781
			"package p2;\n" +
2782
			"import org.eclipse.jdt.annotation.*;\n" +
2783
			"@NonNullByDefault\n" +
2784
			"public class Y {\n" +
2785
			"    @NonNullByDefault void foo() {}\n" +
2786
			"}\n" +
2787
			"class Z {\n" +
2788
			"    @NonNullByDefault void bar() {\n" +
2789
			"         @NonNullByDefault @SuppressWarnings(\"unused\") class Zork {\n" +
2790
			"             @NonNullByDefault void fubar() {}\n" +
2791
			"         }\n" +
2792
			"    }\n" +
2793
			"    @NonNullByDefault void zink() {\n" +
2794
			"         @SuppressWarnings(\"unused\") class Bork {\n" +
2795
			"             @NonNullByDefault void jubar() {}\n" +
2796
			"         }\n" +
2797
			"    }\n" +
2798
			"}\n"
2799
		},
2800
		customOptions,
2801
		"----------\n" +
2802
		"1. WARNING in p2\\Y.java (at line 5)\n" +
2803
		"	@NonNullByDefault void foo() {}\n" +
2804
		"	^^^^^^^^^^^^^^^^^\n" +
2805
		"Nullness default is redundant with a default specified for the enclosing type Y\n" +
2806
		"----------\n" +
2807
		"2. WARNING in p2\\Y.java (at line 9)\n" +
2808
		"	@NonNullByDefault @SuppressWarnings(\"unused\") class Zork {\n" +
2809
		"	^^^^^^^^^^^^^^^^^\n" +
2810
		"Nullness default is redundant with a default specified for the enclosing method bar()\n" +
2811
		"----------\n" +
2812
		"3. WARNING in p2\\Y.java (at line 10)\n" +
2813
		"	@NonNullByDefault void fubar() {}\n" +
2814
		"	^^^^^^^^^^^^^^^^^\n" +
2815
		"Nullness default is redundant with a default specified for the enclosing type Zork\n" +
2816
		"----------\n" +
2817
		"4. WARNING in p2\\Y.java (at line 15)\n" +
2818
		"	@NonNullByDefault void jubar() {}\n" +
2819
		"	^^^^^^^^^^^^^^^^^\n" +
2820
		"Nullness default is redundant with a default specified for the enclosing method zink()\n" +
2821
		"----------\n");
2822
}
2823
2824
//redundant default annotations - class vs. method - generics
2825
public void test_redundant_annotation_02g() {
2826
	Map customOptions = getCompilerOptions();
2827
	runConformTestWithLibs(
2828
		new String[] {
2829
			"p2/Y.java",
2830
			"package p2;\n" +
2831
			"import org.eclipse.jdt.annotation.*;\n" +
2832
			"@NonNullByDefault\n" +
2833
			"public class Y<TY> {\n" +
2834
			"    @NonNullByDefault <TF> void foo(TF arg) {}\n" +
2835
			"}\n" +
2836
			"class Z {\n" +
2837
			"    @NonNullByDefault <TB> void bar() {\n" +
2838
			"         @NonNullByDefault @SuppressWarnings(\"unused\") class Zork {\n" +
2839
			"             @NonNullByDefault void fubar(TB arg) {}\n" +
2840
			"         }\n" +
2841
			"    }\n" +
2842
			"}\n"
2843
		},
2844
		customOptions,
2845
		"----------\n" + 
2846
		"1. WARNING in p2\\Y.java (at line 5)\n" + 
2847
		"	@NonNullByDefault <TF> void foo(TF arg) {}\n" + 
2848
		"	^^^^^^^^^^^^^^^^^\n" + 
2849
		"Nullness default is redundant with a default specified for the enclosing type Y<TY>\n" + 
2850
		"----------\n" + 
2851
		"2. WARNING in p2\\Y.java (at line 9)\n" + 
2852
		"	@NonNullByDefault @SuppressWarnings(\"unused\") class Zork {\n" + 
2853
		"	^^^^^^^^^^^^^^^^^\n" + 
2854
		"Nullness default is redundant with a default specified for the enclosing method bar()\n" + 
2855
		"----------\n" + 
2856
		"3. WARNING in p2\\Y.java (at line 10)\n" + 
2857
		"	@NonNullByDefault void fubar(TB arg) {}\n" + 
2858
		"	^^^^^^^^^^^^^^^^^\n" + 
2859
		"Nullness default is redundant with a default specified for the enclosing type Zork\n" + 
2860
		"----------\n");
2861
}
2862
2863
// redundant default annotations - package / class / method vs global default
2864
// DISABLED due to dysfunctional global default after Bug 366063 - Compiler should not add synthetic @NonNull annotations
2865
public void _test_redundant_annotation_03() {
2866
	Map customOptions = getCompilerOptions();
2867
	customOptions.put(JavaCore.COMPILER_NONNULL_IS_DEFAULT, JavaCore.ENABLED);
2868
	runConformTestWithLibs(
2869
		new String[] {
2870
			"p2/Y.java",
2871
			"package p2;\n" +
2872
			"import org.eclipse.jdt.annotation.*;\n" +
2873
			"@NonNullByDefault\n" +
2874
			"public class Y {\n" +
2875
			"    @NonNullByDefault void foo() {}\n" +
2876
			"}\n" +
2877
			"class Z {\n" +
2878
			"    @NonNullByDefault void bar() {}\n" +
2879
			"}\n",
2880
			"p3/package-info.java",
2881
			"@org.eclipse.jdt.annotation.NonNullByDefault package p3;\n"
2882
		},
2883
		customOptions,
2884
		"----------\n" + 
2885
		"1. WARNING in p2\\Y.java (at line 3)\n" +
2886
		"	@NonNullByDefault\n" +
2887
		"	^^^^^^^^^^^^^^^^^\n" +
2888
		"Nullness default is redundant with the global default\n" +
2889
		"----------\n" +
2890
		"2. WARNING in p2\\Y.java (at line 5)\n" +
2891
		"	@NonNullByDefault void foo() {}\n" +
2892
		"	^^^^^^^^^^^^^^^^^\n" +
2893
		"Nullness default is redundant with a default specified for the enclosing type Y\n" +
2894
		"----------\n" +
2895
		"3. WARNING in p2\\Y.java (at line 8)\n" +
2896
		"	@NonNullByDefault void bar() {}\n" +
2897
		"	^^^^^^^^^^^^^^^^^\n" +
2898
		"Nullness default is redundant with the global default\n" +
2899
		"----------\n" +
2900
		"----------\n" +
2901
		"1. WARNING in p3\\package-info.java (at line 1)\n" +
2902
		"	@org.eclipse.jdt.annotation.NonNullByDefault package p3;\n" +
2903
		"	^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^\n" +
2904
		"Nullness default is redundant with the global default\n" +
2905
		"----------\n");
2906
}
2907
2908
// redundant default annotations - class vs. inner class
2909
// ensure that disabling null annotations also disables this diagnostic
2910
public void test_redundant_annotation_04() {
2911
	Map customOptions = getCompilerOptions();
2912
	customOptions.put(JavaCore.COMPILER_ANNOTATION_NULL_ANALYSIS, JavaCore.DISABLED);
2913
	runConformTestWithLibs(
2914
		new String[] {
2915
			"p2/Y.java",
2916
			"package p2;\n" +
2917
			"import org.eclipse.jdt.annotation.*;\n" +
2918
			"@NonNullByDefault\n" +
2919
			"public class Y {\n" +
2920
			"    @NonNullByDefault class Inner {\n" +
2921
			"        @NonNullByDefault class DeepInner {}\n" +
2922
			"    }\n" +
2923
			"    class Inner2 {\n" +
2924
			"        @NonNullByDefault class DeepInner2 {\n" +
2925
			"        }\n" +
2926
			"        @NonNullByDefault void foo(@Nullable @NonNull Object arg) {\n" +
2927
			"            @NonNullByDefault class Local {}\n" +
2928
			"        }\n" +
2929
			"    }\n" +
2930
			"}\n" +
2931
			"@NonNullByDefault class V {}\n",
2932
			"p3/package-info.java",
2933
			"@org.eclipse.jdt.annotation.NonNullByDefault package p3;\n",
2934
			"p3/Z.java",
2935
			"package p3;\n" +
2936
			"import org.eclipse.jdt.annotation.*;\n" +
2937
			"@NonNullByDefault\n" +
2938
			"public class Z {\n" +
2939
			"}\n" +
2940
			"class X {\n" +
2941
			"    @NonNullByDefault class Inner {}\n" +
2942
			"    class Inner2 {\n" +
2943
			"        @NonNullByDefault class DeepInner {}\n" +
2944
			"    }\n" +
2945
			"}\n"
2946
		},
2947
		customOptions,
2948
		"");
2949
}
2950
2951
// contradictory null annotations
2952
public void test_contradictory_annotations_01() {
2953
	Map customOptions = getCompilerOptions();
2954
	runNegativeTestWithLibs(
2955
		new String[] {
2956
			"p2/Y.java",
2957
			"package p2;\n" +
2958
			"import org.eclipse.jdt.annotation.*;\n" +
2959
			"public class Y {\n" +
2960
			"    void foo(@NonNull @Nullable Object o) {}\n" +
2961
			"    @Nullable @NonNull Object bar() {\n" +
2962
			"        @NonNull @Nullable Object o = null;\n" +
2963
			"        return o;\n" +
2964
			"    }\n" +
2965
			"}\n" +
2966
			"class Z {\n" +
2967
			"    @NonNullByDefault void bar() {}\n" +
2968
			"}\n"
2969
		},
2970
		customOptions,
2971
		"----------\n" + 
2972
		"1. ERROR in p2\\Y.java (at line 4)\n" + 
2973
		"	void foo(@NonNull @Nullable Object o) {}\n" + 
2974
		"	                  ^^^^^^^^^\n" + 
2975
		"Contradictory null specification; only one of @NonNull and @Nullable can be specified at any location\n" + 
2976
		"----------\n" + 
2977
		"2. ERROR in p2\\Y.java (at line 5)\n" + 
2978
		"	@Nullable @NonNull Object bar() {\n" + 
2979
		"	          ^^^^^^^^\n" + 
2980
		"Contradictory null specification; only one of @NonNull and @Nullable can be specified at any location\n" + 
2981
		"----------\n" + 
2982
		"3. ERROR in p2\\Y.java (at line 6)\n" + 
2983
		"	@NonNull @Nullable Object o = null;\n" + 
2984
		"	         ^^^^^^^^^\n" + 
2985
		"Contradictory null specification; only one of @NonNull and @Nullable can be specified at any location\n" + 
2986
		"----------\n");
2987
}
2988
2989
// a nonnull variable is dereferenced in a loop
2990
public void test_nonnull_var_in_constrol_structure_1() {
2991
	Map customOptions = getCompilerOptions();
2992
//	customOptions.put(CompilerOptions.OPTION_ReportPotentialNullSpecViolation, JavaCore.ERROR);
2993
// This option currently does nothing:
2994
//	customOptions.put(JavaCore.COMPILER_NONNULL_IS_DEFAULT, JavaCore.ENABLED);
2995
	runNegativeTestWithLibs(
2996
		new String[] {
2997
			"X.java",
2998
			"import org.eclipse.jdt.annotation.*;\n" +
2999
			"@NonNullByDefault\n" +
3000
			"public class X {\n" +
3001
			"    void print4(@NonNull String s) {\n" +
3002
			"        for (int i=0; i<4; i++)\n" +
3003
			"             print(s);\n" +
3004
			"    }\n" +
3005
			"    void print5(@Nullable String s) {\n" +
3006
			"        for (int i=0; i<5; i++)\n" +
3007
			"             print(s);\n" +
3008
			"    }\n" +
3009
			"    void print6(boolean b) {\n" +
3010
			"        String s = b ? null : \"\";\n" +
3011
			"        for (int i=0; i<5; i++)\n" +
3012
			"             print(s);\n" +
3013
			"    }\n" +
3014
			"    void print(@NonNull String s) {\n" +
3015
			"        System.out.print(s);\n" +
3016
			"    }\n" +
3017
			"}\n",
3018
3019
		},
3020
		customOptions,
3021
		"----------\n" +
3022
		"1. WARNING in X.java (at line 4)\n" +
3023
		"	void print4(@NonNull String s) {\n" +
3024
		"	            ^^^^^^^^^^^^^^^^^\n" +
3025
		"The nullness annotation is redundant with a default that applies to this location\n" +
3026
		"----------\n" +
3027
		"2. ERROR in X.java (at line 10)\n" +
3028
		"	print(s);\n" +
3029
		"	      ^\n" +
3030
		"Type mismatch: required \'@NonNull String\' but the provided value can be null\n" +
3031
		"----------\n" +
3032
		"3. ERROR in X.java (at line 15)\n" +
3033
		"	print(s);\n" +
3034
		"	      ^\n" +
3035
		"Type mismatch: required \'@NonNull String\' but the provided value can be null\n" +
3036
		"----------\n" +
3037
		"4. WARNING in X.java (at line 17)\n" +
3038
		"	void print(@NonNull String s) {\n" +
3039
		"	           ^^^^^^^^^^^^^^^^^\n" +
3040
		"The nullness annotation is redundant with a default that applies to this location\n" +
3041
		"----------\n");
3042
}
3043
// a nonnull variable is dereferenced in a finally block
3044
public void test_nonnull_var_in_constrol_structure_2() {
3045
	Map customOptions = getCompilerOptions();
3046
//	customOptions.put(CompilerOptions.OPTION_ReportPotentialNullSpecViolation, JavaCore.ERROR);
3047
// This option currently does nothing:
3048
//	customOptions.put(JavaCore.COMPILER_NONNULL_IS_DEFAULT, JavaCore.ENABLED);
3049
	runNegativeTestWithLibs(
3050
		new String[] {
3051
			"X.java",
3052
			"import org.eclipse.jdt.annotation.*;" +
3053
			"@NonNullByDefault\n" +
3054
			"public class X {\n" +
3055
			"    void print4(String s) {\n" +
3056
			"        try { /*empty*/ } finally {\n" +
3057
			"             print(s);\n" +
3058
			"        }\n" +
3059
			"    }\n" +
3060
			"    void print5(@Nullable String s) {\n" +
3061
			"        try { /*empty*/ } finally {\n" +
3062
			"             print(s);\n" +
3063
			"        }\n" +
3064
			"    }\n" +
3065
			"    void print6(boolean b) {\n" +
3066
			"        String s = b ? null : \"\";\n" +
3067
			"        try { /*empty*/ } finally {\n" +
3068
			"             print(s);\n" +
3069
			"        }\n" +
3070
			"    }\n" +
3071
			"    void print(String s) {\n" +
3072
			"        System.out.print(s);\n" +
3073
			"    }\n" +
3074
			"}\n",
3075
3076
		},
3077
		customOptions,
3078
		"----------\n" +
3079
		"1. ERROR in X.java (at line 10)\n" +
3080
		"	print(s);\n" +
3081
		"	      ^\n" +
3082
		"Type mismatch: required \'@NonNull String\' but the provided value can be null\n" +
3083
		"----------\n" +
3084
		"2. ERROR in X.java (at line 16)\n" +
3085
		"	print(s);\n" +
3086
		"	      ^\n" +
3087
		"Type mismatch: required \'@NonNull String\' but the provided value can be null\n" +
3088
		"----------\n");
3089
}
3090
// a nonnull variable is dereferenced in a finally block inside a loop
3091
public void test_nonnull_var_in_constrol_structure_3() {
3092
	Map customOptions = getCompilerOptions();
3093
//	customOptions.put(CompilerOptions.OPTION_ReportPotentialNullSpecViolation, JavaCore.ERROR);
3094
	customOptions.put(JavaCore.COMPILER_NONNULL_IS_DEFAULT, JavaCore.ENABLED);
3095
	customOptions.put(JavaCore.COMPILER_PB_REDUNDANT_NULL_ANNOTATION, JavaCore.IGNORE);
3096
	runNegativeTestWithLibs(
3097
		new String[] {
3098
			"X.java",
3099
			"import org.eclipse.jdt.annotation.*;\n" +
3100
			"public class X {\n" +
3101
			"    void print4(@NonNull String s) {\n" +
3102
			"        for (int i=0; i<4; i++)\n" +
3103
			"            try { /*empty*/ } finally {\n" +
3104
			"                 print(s);\n" +
3105
			"            }\n" +
3106
			"    }\n" +
3107
			"    void print5(@Nullable String s) {\n" +
3108
			"        for (int i=0; i<5; i++)\n" +
3109
			"            try { /*empty*/ } finally {\n" +
3110
			"                 print(s);\n" +
3111
			"            }\n" +
3112
			"    }\n" +
3113
			"    void print6(boolean b) {\n" +
3114
			"        String s = b ? null : \"\";\n" +
3115
			"        for (int i=0; i<4; i++)\n" +
3116
			"            try { /*empty*/ } finally {\n" +
3117
			"                 print(s);\n" +
3118
			"            }\n" +
3119
			"    }\n" +
3120
			"    void print(@NonNull String s) {\n" +
3121
			"        System.out.print(s);\n" +
3122
			"    }\n" +
3123
			"}\n",
3124
3125
		},
3126
		customOptions,
3127
		"----------\n" +
3128
		"1. ERROR in X.java (at line 12)\n" +
3129
		"	print(s);\n" +
3130
		"	      ^\n" +
3131
		"Type mismatch: required \'@NonNull String\' but the provided value can be null\n" +
3132
		"----------\n" +
3133
		"2. ERROR in X.java (at line 19)\n" +
3134
		"	print(s);\n" +
3135
		"	      ^\n" +
3136
		"Type mismatch: required \'@NonNull String\' but the provided value can be null\n" +
3137
		"----------\n");
3138
}
3139
// witness for an AIOOBE in FlowContext.recordExpectedType()
3140
public void test_message_send_in_control_structure_01() {
3141
	Map customOptions = getCompilerOptions();
3142
	customOptions.put(JavaCore.COMPILER_PB_NULL_SPECIFICATION_INSUFFICIENT_INFO, JavaCore.IGNORE);
3143
	customOptions.put(JavaCore.COMPILER_PB_POTENTIAL_NULL_REFERENCE, JavaCore.WARNING);
3144
	runNegativeTestWithLibs(
3145
		new String[] {
3146
			"p/Scope.java",
3147
			"package p;\n" +
3148
			"@org.eclipse.jdt.annotation.NonNullByDefault\n" +
3149
			"public abstract class Scope {\n" +
3150
			"	public ReferenceBinding findMemberType(char[] typeName, ReferenceBinding enclosingType) {\n" +
3151
			"		ReferenceBinding enclosingSourceType = enclosingSourceType();\n" +
3152
			"		PackageBinding currentPackage = getCurrentPackage();\n" +
3153
			"		CompilationUnitScope unitScope = compilationUnitScope();\n" +
3154
			"		ReferenceBinding memberType = enclosingType.getMemberType(typeName);\n" +
3155
			"		ReferenceBinding currentType = enclosingType;\n" +
3156
			"		ReferenceBinding[] interfacesToVisit = null;\n" +
3157
			"		while (true) {\n" +
3158
			"			ReferenceBinding[] itsInterfaces = currentType.superInterfaces();\n" +
3159
			"			if (itsInterfaces != null) {\n" +
3160
			"				if (interfacesToVisit == null) {\n" +
3161
			"					interfacesToVisit = itsInterfaces;\n" +
3162
			"				}\n" +
3163
			"			}\n" +
3164
			"			unitScope.recordReference(currentType, typeName);\n" +
3165
			"			\n" +
3166
			"			if ((memberType = currentType.getMemberType(typeName)) != null) {\n" +
3167
			"				if (enclosingSourceType == null\n" +
3168
			"					? memberType.canBeSeenBy(currentPackage)\n" +
3169
			"					: memberType.canBeSeenBy(enclosingType, enclosingSourceType)) {\n" +
3170
			"						return memberType;\n" +
3171
			"				}\n" +
3172
			"			}\n" +
3173
			"		}\n" +
3174
			"	}\n" +
3175
			"	private CompilationUnitScope compilationUnitScope() {\n" +
3176
			"		return compilationUnitScope();\n" +
3177
			"	}\n" +
3178
			"	private PackageBinding getCurrentPackage() {\n" +
3179
			"		return getCurrentPackage();\n" +
3180
			"	}\n" +
3181
			"	private ReferenceBinding enclosingSourceType() {\n" +
3182
			"		return enclosingSourceType();\n" +
3183
			"	}\n" +
3184
			"}\n",
3185
			"p/CompilationUnitScope.java",
3186
			"package p;\n" +
3187
			"@org.eclipse.jdt.annotation.NonNullByDefault\n" +
3188
			"public class CompilationUnitScope {\n" +
3189
			"    void recordReference(ReferenceBinding rb, char[] name) {}\n" +
3190
			"}\n",
3191
			"p/PackageBinding.java",
3192
			"package p;\n" +
3193
			"@org.eclipse.jdt.annotation.NonNullByDefault\n" +
3194
			"public class PackageBinding {\n" +
3195
			"}\n",
3196
			"p/ReferenceBinding.java",
3197
			"package p;\n" +
3198
			"@org.eclipse.jdt.annotation.NonNullByDefault\n" +
3199
			"public class ReferenceBinding {\n" +
3200
			"    ReferenceBinding getMemberType(char[] name) { return this; }\n" +
3201
			"    ReferenceBinding[] superInterfaces() { return new ReferenceBinding[0]; }\n" +
3202
			"    boolean canBeSeenBy(PackageBinding ob) { return true; }\n" +
3203
			"    boolean canBeSeenBy(ReferenceBinding rb, ReferenceBinding rb2) { return true; }\n" +
3204
			"}\n"
3205
		},
3206
		customOptions,
3207
		"----------\n" +
3208
		"1. ERROR in p\\Scope.java (at line 13)\n" +
3209
		"	if (itsInterfaces != null) {\n" +
3210
		"	    ^^^^^^^^^^^^^\n" +
3211
		"Redundant null check: The variable itsInterfaces cannot be null at this location\n" +
3212
		"----------\n" +
3213
		"2. ERROR in p\\Scope.java (at line 20)\n" +
3214
		"	if ((memberType = currentType.getMemberType(typeName)) != null) {\n" +
3215
		"	    ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^\n" +
3216
		"Redundant null check: The variable memberType cannot be null at this location\n" +
3217
		"----------\n" +
3218
		"3. ERROR in p\\Scope.java (at line 21)\n" +
3219
		"	if (enclosingSourceType == null\n" +
3220
		"	    ^^^^^^^^^^^^^^^^^^^\n" +
3221
		"Null comparison always yields false: The variable enclosingSourceType cannot be null at this location\n" +
3222
		"----------\n");
3223
}
3224
// Bug 370930 - NonNull annotation not considered for enhanced for loops
3225
public void test_message_send_in_control_structure_02() {
3226
	runNegativeTestWithLibs(
3227
		new String[] {
3228
			"Bug370930.java",
3229
			"import org.eclipse.jdt.annotation.*;\n" +
3230
			"import java.util.*;\n" +
3231
			"public class Bug370930 {\n" +
3232
			"	void loop(Collection<String> list) {\n" + 
3233
			"		for(@NonNull String s: list) { // warning here: insufficient info on elements\n" + 
3234
			"			expectNonNull(s); // no warning here\n" + 
3235
			"		}\n" + 
3236
			"	}\n" + 
3237
			"	\n" + 
3238
			"	void expectNonNull(@NonNull String s) {}\n" +
3239
			"}\n"
3240
		},
3241
		"----------\n" + 
3242
		"1. WARNING in Bug370930.java (at line 5)\n" + 
3243
		"	for(@NonNull String s: list) { // warning here: insufficient info on elements\n" + 
3244
		"	                       ^^^^\n" + 
3245
		"Potential type mismatch: required \'@NonNull String\' but nullness of the provided value is unknown\n" + 
3246
		"----------\n");
3247
}
3248
//Bug 370930 - NonNull annotation not considered for enhanced for loops
3249
public void test_message_send_in_control_structure_03() {
3250
	runNegativeTestWithLibs(
3251
		new String[] {
3252
			"Bug370930.java",
3253
			"import org.eclipse.jdt.annotation.*;\n" +
3254
			"import java.util.*;\n" +
3255
			"public class Bug370930 {\n" +
3256
			"	void loop(Collection<String> list) {\n" + 
3257
			"		for(@Nullable String s: list) {\n" + 
3258
			"			expectNonNull(s); // warning here\n" + 
3259
			"		}\n" + 
3260
			"	}\n" + 
3261
			"	\n" + 
3262
			"	void expectNonNull(@NonNull String s) {}\n" +
3263
			"}\n"
3264
		},
3265
		"----------\n" + 
3266
		"1. ERROR in Bug370930.java (at line 6)\n" + 
3267
		"	expectNonNull(s); // warning here\n" + 
3268
		"	              ^\n" + 
3269
		"Type mismatch: required \'@NonNull String\' but the provided value can be null\n" + 
3270
		"----------\n");
3271
}
3272
public void test_assignment_expression_1() {
3273
	Map customOptions = getCompilerOptions();
3274
//	customOptions.put(CompilerOptions.OPTION_ReportPotentialNullSpecViolation, JavaCore.ERROR);
3275
	customOptions.put(JavaCore.COMPILER_NONNULL_IS_DEFAULT, JavaCore.ENABLED);
3276
	customOptions.put(JavaCore.COMPILER_PB_REDUNDANT_NULL_CHECK, JavaCore.ERROR);
3277
	runConformTestWithLibs(
3278
		new String[] {
3279
			"X.java",
3280
			"import org.eclipse.jdt.annotation.*;\n" +
3281
			"public class X {\n" +
3282
			"	@Nullable Object foo() {\n" +
3283
			"		Object o = null;\n" +
3284
			"		boolean keepLooking = true;\n" +
3285
			"		while(keepLooking) {\n" +
3286
			"			if ((o=getO()) != null) {\n" +
3287
			"				return o;\n" +
3288
			"			}\n" +
3289
			"		}\n" +
3290
			"		return null;\n" +
3291
			"	}\n" +
3292
			"\n" +
3293
			"	private @Nullable Object getO() {\n" +
3294
			"		return new Object();\n" +
3295
			"	}\n" +
3296
			"}\n",
3297
3298
		},
3299
		customOptions,
3300
		"");	
3301
}
3302
// a nonnull variable is dereferenced in a method of a nested type
3303
public void test_nesting_1() {
3304
	Map customOptions = getCompilerOptions();
3305
//	customOptions.put(CompilerOptions.OPTION_ReportPotentialNullSpecViolation, JavaCore.ERROR);
3306
// This option currently does nothing:
3307
//	customOptions.put(JavaCore.COMPILER_NONNULL_IS_DEFAULT, JavaCore.ENABLED);
3308
	runNegativeTestWithLibs(
3309
		new String[] {
3310
			"X.java",
3311
			"import org.eclipse.jdt.annotation.*;\n" +
3312
			"@NonNullByDefault\n" +
3313
			"public class X {\n" +
3314
			"    void print4(final String s1) {\n" +
3315
			"        for (int i=0; i<3; i++)\n" +
3316
			"            new Runnable() {\n" +
3317
			"                public void run() {\n" +
3318
			"                     print(s1);\n" +
3319
			"                }\n" +
3320
			"            }.run();\n" +
3321
			"    }\n" +
3322
			"    void print8(final @Nullable String s2) {\n" +
3323
			"        for (int i=0; i<3; i++)\n" +
3324
			"            new Runnable() {\n" +
3325
			"                public void run() {\n" +
3326
			"                     print(s2);\n" +
3327
			"                }\n" +
3328
			"            }.run();\n" +
3329
			"    }\n" +
3330
			"    void print16(boolean b) {\n" +
3331
			"        final String s3 = b ? null : \"\";\n" +
3332
			"        for (int i=0; i<3; i++)\n" +
3333
			"            new Runnable() {\n" +
3334
			"                public void run() {\n" +
3335
			"                     @NonNull String s3R = s3;\n" +
3336
			"                }\n" +
3337
			"            }.run();\n" +
3338
			"    }\n" +
3339
			"    void print(String s) {\n" +
3340
			"        System.out.print(s);\n" +
3341
			"    }\n" +
3342
			"}\n",
3343
3344
		},
3345
		customOptions,
3346
		"----------\n" +
3347
		"1. ERROR in X.java (at line 16)\n" +
3348
		"	print(s2);\n" +
3349
		"	      ^^\n" +
3350
		"Type mismatch: required \'@NonNull String\' but the provided value can be null\n" +
3351
		"----------\n" +
3352
		"2. ERROR in X.java (at line 25)\n" +
3353
		"	@NonNull String s3R = s3;\n" +
3354
		"	                      ^^\n" +
3355
		"Type mismatch: required \'@NonNull String\' but the provided value can be null\n" +
3356
		"----------\n");
3357
}
3358
// Test a regression incurred to the OT/J based implementation
3359
// by the fix in Bug 360328 - [compiler][null] detect null problems in nested code (local class inside a loop)
3360
public void test_constructor_with_nested_class() {
3361
	runConformTest(
3362
		new String[] {
3363
			"X.java",
3364
			"public class X {\n" +
3365
			"    final Object o1;\n" +
3366
			"    final Object o2;\n" +
3367
			"    public X() {\n" +
3368
			"         this.o1 = new Object() {\n" +
3369
			"             public String toString() { return \"O1\"; }\n" +
3370
			"         };\n" +
3371
			"         this.o2 = new Object();" +
3372
			"    }\n" +
3373
			"}\n"
3374
		},
3375
		"");
3376
}
3377
// test analysis disablement, binary type contains annotation
3378
public void test_options_01() {
3379
	Map customOptions = getCompilerOptions();
3380
	customOptions.put(JavaCore.COMPILER_PB_NULL_SPECIFICATION_INSUFFICIENT_INFO, JavaCore.ERROR);
3381
	runConformTestWithLibs(
3382
			new String[] {
3383
				"ContainingInner2.java",
3384
				"public class ContainingInner2 {\n" + 
3385
				"    public ContainingInner2 (@org.eclipse.jdt.annotation.NonNull Object o) {\n" + 
3386
				"    }\n" + 
3387
				"    public class Inner {\n" + 
3388
				"        public <T> Inner (@org.eclipse.jdt.annotation.NonNull T o) {\n" + 
3389
				"        }\n" + 
3390
				"    }\n" + 
3391
				"}\n",
3392
			},
3393
			null /*customOptions*/,
3394
			"");
3395
	customOptions.put(JavaCore.COMPILER_ANNOTATION_NULL_ANALYSIS, JavaCore.DISABLED);
3396
	runConformTestWithLibs(
3397
		false, // flush directory
3398
		new String[] {
3399
			"X.java",
3400
			"public class X {\n" +
3401
			"	 void create() {\n" +
3402
			"          ContainingInner2 container = new ContainingInner2(null);\n" +
3403
			"	       ContainingInner2.Inner inner = container.new Inner(null);\n" +
3404
			"    }\n" +
3405
		  	"}\n"},
3406
		customOptions,
3407
		""  /* compiler output */);
3408
}
3409
// test illegally trying to ignore null spec violations
3410
public void test_options_02() {
3411
	Map customOptions = getCompilerOptions();
3412
	customOptions.put(JavaCore.COMPILER_PB_NULL_SPECIFICATION_VIOLATION, JavaCore.IGNORE); // has no effect
3413
	runNegativeTestWithLibs(
3414
		new String[] {
3415
			"Test.java",
3416
			"public class Test {\n" +
3417
			"    public void foo(@org.eclipse.jdt.annotation.NonNull Object o) {\n" +
3418
			"        o = null;\n" +
3419
			"        Object p = o;\n" +
3420
			"        if (p == null)\n" +
3421
			"            p.toString();\n" +
3422
			"    }\n" + 
3423
			"}\n",
3424
		},
3425
		customOptions,
3426
		"----------\n" + 
3427
		"1. ERROR in Test.java (at line 3)\n" + 
3428
		"	o = null;\n" + 
3429
		"	    ^^^^\n" + 
3430
		"Type mismatch: required \'@NonNull Object\' but the provided value is null\n" + 
3431
		"----------\n" + 
3432
		"2. ERROR in Test.java (at line 5)\n" + 
3433
		"	if (p == null)\n" + 
3434
		"	    ^\n" + 
3435
		"Null comparison always yields false: The variable p cannot be null at this location\n" + 
3436
		"----------\n" + 
3437
		"3. WARNING in Test.java (at line 6)\n" + 
3438
		"	p.toString();\n" + 
3439
		"	^^^^^^^^^^^^\n" + 
3440
		"Dead code\n" + 
3441
		"----------\n");
3442
}
3443
// test setting null spec violations to "warning"
3444
public void test_options_03() {
3445
	Map customOptions = getCompilerOptions();
3446
	customOptions.put(JavaCore.COMPILER_PB_NULL_SPECIFICATION_VIOLATION, JavaCore.WARNING); // OK
3447
	runNegativeTestWithLibs(
3448
		new String[] {
3449
			"Test.java",
3450
			"public class Test {\n" +
3451
			"    public void foo(@org.eclipse.jdt.annotation.NonNull Object o) {\n" +
3452
			"        o = null;\n" +
3453
			"        Object p = o;\n" +
3454
			"        if (p == null)\n" +
3455
			"            p.toString();\n" +
3456
			"    }\n" + 
3457
			"}\n",
3458
		},
3459
		customOptions,
3460
		"----------\n" + 
3461
		"1. WARNING in Test.java (at line 3)\n" + 
3462
		"	o = null;\n" + 
3463
		"	    ^^^^\n" + 
3464
		"Type mismatch: required \'@NonNull Object\' but the provided value is null\n" + 
3465
		"----------\n" + 
3466
		"2. ERROR in Test.java (at line 5)\n" + 
3467
		"	if (p == null)\n" + 
3468
		"	    ^\n" + 
3469
		"Null comparison always yields false: The variable p cannot be null at this location\n" + 
3470
		"----------\n" + 
3471
		"3. WARNING in Test.java (at line 6)\n" + 
3472
		"	p.toString();\n" + 
3473
		"	^^^^^^^^^^^^\n" + 
3474
		"Dead code\n" + 
3475
		"----------\n");
3476
}
3477
}
(-)a/org.eclipse.jdt.core.tests.compiler/src/org/eclipse/jdt/core/tests/compiler/regression/NullReferenceTest.java (-11 / +520 lines)
Lines 1-5 Link Here
1
/*******************************************************************************
1
/*******************************************************************************
2
 * Copyright (c) 2005, 2011 IBM Corporation and others.
2
 * Copyright (c) 2005, 2012 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 18-23 Link Here
18
 *     						bug 336428 - [compiler][null] bogus warning "redundant null check" in condition of do {} while() loop
18
 *     						bug 336428 - [compiler][null] bogus warning "redundant null check" in condition of do {} while() loop
19
 * 							bug 324178 - [null] ConditionalExpression.nullStatus(..) doesn't take into account the analysis of condition itself
19
 * 							bug 324178 - [null] ConditionalExpression.nullStatus(..) doesn't take into account the analysis of condition itself
20
 * 							bug 354554 - [null] conditional with redundant condition yields weak error message
20
 * 							bug 354554 - [null] conditional with redundant condition yields weak error message
21
 * 							bug 358827 - [1.7] exception analysis for t-w-r spoils null analysis
22
 * 							bug 349326 - [1.7] new warning for missing try-with-resources
23
 * 							bug 360328 - [compiler][null] detect null problems in nested code (local class inside a loop)
24
 * 							bug 367879 - Incorrect "Potential null pointer access" warning on statement after try-with-resources within try-finally
21
 *******************************************************************************/
25
 *******************************************************************************/
22
package org.eclipse.jdt.core.tests.compiler.regression;
26
package org.eclipse.jdt.core.tests.compiler.regression;
23
27
Lines 45-51 Link Here
45
// Only the highest compliance level is run; add the VM argument
49
// Only the highest compliance level is run; add the VM argument
46
// -Dcompliance=1.4 (for example) to lower it if needed
50
// -Dcompliance=1.4 (for example) to lower it if needed
47
static {
51
static {
48
//		TESTS_NAMES = new String[] { "testBug348379" };
52
//		TESTS_NAMES = new String[] { "testBug360328" };
49
//		TESTS_NUMBERS = new int[] { 561 };
53
//		TESTS_NUMBERS = new int[] { 561 };
50
//		TESTS_RANGE = new int[] { 1, 2049 };
54
//		TESTS_RANGE = new int[] { 1, 2049 };
51
}
55
}
Lines 6014-6020 Link Here
6014
// https://bugs.eclipse.org/bugs/show_bug.cgi?id=150854
6018
// https://bugs.eclipse.org/bugs/show_bug.cgi?id=150854
6015
// (slightly different) variant of 561
6019
// (slightly different) variant of 561
6016
public void test0562_try_catch_unchecked_exception() {
6020
public void test0562_try_catch_unchecked_exception() {
6021
	Map options = getCompilerOptions();
6022
	options.put(CompilerOptions.OPTION_ReportUnclosedCloseable, CompilerOptions.WARNING);
6023
	options.put(CompilerOptions.OPTION_ReportPotentiallyUnclosedCloseable, CompilerOptions.WARNING);
6017
	this.runNegativeTest(
6024
	this.runNegativeTest(
6025
		true,
6018
		new String[] {
6026
		new String[] {
6019
			"X.java",
6027
			"X.java",
6020
			"import java.io.*;\n" +
6028
			"import java.io.*;\n" +
Lines 6029-6040 Link Here
6029
			"    }\n" +
6037
			"    }\n" +
6030
			"  }\n" +
6038
			"  }\n" +
6031
			"}\n"},
6039
			"}\n"},
6032
		"----------\n" +
6040
			null,
6033
		"1. ERROR in X.java (at line 8)\n" +
6041
			options,
6034
		"	o.toString();\n" +
6042
			"----------\n" +
6035
		"	^\n" +
6043
			"1. WARNING in X.java (at line 6)\n" +
6036
		"Potential null pointer access: The variable o may be null at this location\n" +
6044
			"	o = new LineNumberReader(new FileReader(\"dummy\"));\n" +
6037
		"----------\n",
6045
			"	^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^\n" +
6046
			"Potential resource leak: \'o\' may not be closed\n" +
6047
			"----------\n" +
6048
			"2. ERROR in X.java (at line 8)\n" +
6049
			"	o.toString();\n" +
6050
			"	^\n" +
6051
			"Potential null pointer access: The variable o may be null at this location\n" +
6052
			"----------\n",
6038
	    JavacTestOptions.Excuse.EclipseWarningConfiguredAsError);
6053
	    JavacTestOptions.Excuse.EclipseWarningConfiguredAsError);
6039
}
6054
}
6040
6055
Lines 6085-6090 Link Here
6085
// null analysis - try/catch
6100
// null analysis - try/catch
6086
// https://bugs.eclipse.org/bugs/show_bug.cgi?id=150854
6101
// https://bugs.eclipse.org/bugs/show_bug.cgi?id=150854
6087
public void test0564_try_catch_unchecked_exception() {
6102
public void test0564_try_catch_unchecked_exception() {
6103
	Map options = getCompilerOptions();
6104
	options.put(CompilerOptions.OPTION_ReportUnclosedCloseable, CompilerOptions.WARNING);
6088
	this.runConformTest(
6105
	this.runConformTest(
6089
		new String[] {
6106
		new String[] {
6090
			"X.java",
6107
			"X.java",
Lines 6099-6111 Link Here
6099
			"    return result;\n" +
6116
			"    return result;\n" +
6100
			"  }\n" +
6117
			"  }\n" +
6101
			"}"},
6118
			"}"},
6102
		"");
6119
		"",
6120
		null /* no extra class libraries */,
6121
		true /* flush output directory */,
6122
		null /* no vm arguments */,
6123
		options,
6124
		null /* no custom requestor*/,
6125
	  	false /* do not skip javac for this peculiar test */);
6103
}
6126
}
6104
6127
6105
// null analysis - try/catch
6128
// null analysis - try/catch
6106
// https://bugs.eclipse.org/bugs/show_bug.cgi?id=150854
6129
// https://bugs.eclipse.org/bugs/show_bug.cgi?id=150854
6107
// variant
6130
// variant
6108
public void test0565_try_catch_unchecked_exception() {
6131
public void test0565_try_catch_unchecked_exception() {
6132
	Map options = getCompilerOptions();
6133
	options.put(CompilerOptions.OPTION_ReportUnclosedCloseable, CompilerOptions.WARNING);
6109
	this.runConformTest(
6134
	this.runConformTest(
6110
		new String[] {
6135
		new String[] {
6111
			"X.java",
6136
			"X.java",
Lines 6121-6133 Link Here
6121
			"    return result;\n" +
6146
			"    return result;\n" +
6122
			"  }\n" +
6147
			"  }\n" +
6123
			"}"},
6148
			"}"},
6124
		"");
6149
		"",
6150
		null /* no extra class libraries */,
6151
		true /* flush output directory */,
6152
		null /* no vm arguments */,
6153
		options,
6154
		null /* no custom requestor*/,
6155
	  	false /* do not skip javac for this peculiar test */);
6125
}
6156
}
6126
6157
6127
// null analysis - try/catch
6158
// null analysis - try/catch
6128
// https://bugs.eclipse.org/bugs/show_bug.cgi?id=150854
6159
// https://bugs.eclipse.org/bugs/show_bug.cgi?id=150854
6129
// variant
6160
// variant
6130
public void test0566_try_catch_unchecked_exception() {
6161
public void test0566_try_catch_unchecked_exception() {
6162
	Map options = getCompilerOptions();
6163
	options.put(CompilerOptions.OPTION_ReportUnclosedCloseable, CompilerOptions.WARNING);
6131
	this.runConformTest(
6164
	this.runConformTest(
6132
		new String[] {
6165
		new String[] {
6133
			"X.java",
6166
			"X.java",
Lines 6152-6158 Link Here
6152
			"    return null;\n" +
6185
			"    return null;\n" +
6153
			"  }\n" +
6186
			"  }\n" +
6154
			"}"},
6187
			"}"},
6155
		"");
6188
		"",
6189
		null /* no extra class libraries */,
6190
		true /* flush output directory */,
6191
		null /* no vm arguments */,
6192
		options,
6193
		null /* no custom requestor*/,
6194
	  	false /* do not skip javac for this peculiar test */);
6156
}
6195
}
6157
6196
6158
// null analysis - try/catch for checked exceptions
6197
// null analysis - try/catch for checked exceptions
Lines 14944-14947 Link Here
14944
		"Redundant null check: The variable u cannot be null at this location\n" + 
14983
		"Redundant null check: The variable u cannot be null at this location\n" + 
14945
		"----------\n");
14984
		"----------\n");
14946
}
14985
}
14986
// Bug 358827 - [1.7] exception analysis for t-w-r spoils null analysis
14987
public void test358827() {
14988
	if (this.complianceLevel >= ClassFileConstants.JDK1_7) {
14989
		this.runNegativeTest(
14990
				new String[] {
14991
					"Bug358827.java",
14992
					"import java.io.FileReader;\n" +
14993
					"public class Bug358827 {\n" +
14994
					"	Object foo2() throws Exception {\n" + 
14995
					"		String o = null;\n" + 
14996
					"		try (FileReader rf = new FileReader(\"file\")){\n" + 
14997
					"			o = o.toUpperCase();\n" + 
14998
					"		} finally {\n" + 
14999
					"			o = \"OK\";\n" + 
15000
					"		}\n" + 
15001
					"		return o;\n" + 
15002
					"	}\n" + 
15003
					"}\n"
15004
				},
15005
				"----------\n" + 
15006
				"1. ERROR in Bug358827.java (at line 6)\n" + 
15007
				"	o = o.toUpperCase();\n" + 
15008
				"	    ^\n" + 
15009
				"Null pointer access: The variable o can only be null at this location\n" + 
15010
				"----------\n");
15011
	}
15012
}
15013
// Bug 367879 - Incorrect "Potential null pointer access" warning on statement after try-with-resources within try-finally
15014
public void test367879() {
15015
	if (this.complianceLevel >= ClassFileConstants.JDK1_7) {
15016
		this.runConformTest(
15017
				new String[] {
15018
					"Bug367879.java",
15019
					"import java.io.IOException;\n" +
15020
					"import java.io.InputStream;\n" +
15021
					"import java.net.HttpURLConnection;\n" +
15022
					"import java.net.URL;\n" +
15023
					"public class Bug367879 {\n" +
15024
					"    public void test() throws IOException {\n" + 
15025
					"    HttpURLConnection http = null;\n" + 
15026
					"        try {\n" + 
15027
					"            http = (HttpURLConnection) new URL(\"http://example.com/\").openConnection();\n" + 
15028
					"            try (InputStream in = http.getInputStream()) { /* get input */ }\n" + 
15029
					"            http.getURL();\n" + // shouldn't *not* flag as Potential null pointer access 
15030
					"        } finally {\n" + 
15031
					"            if (http != null) { http.disconnect(); }\n" + 
15032
					"        }\n" + 
15033
					"    }\n" + 
15034
					"}\n"
15035
				},
15036
				"");
15037
	}
15038
}
15039
// https://bugs.eclipse.org/bugs/show_bug.cgi?id=256796
15040
public void testBug256796() {
15041
	Map compilerOptions = getCompilerOptions();
15042
	compilerOptions.put(CompilerOptions.OPTION_ReportUnnecessaryElse, CompilerOptions.IGNORE);
15043
	compilerOptions.put(CompilerOptions.OPTION_ReportDeadCode, CompilerOptions.WARNING);
15044
	compilerOptions.put(CompilerOptions.OPTION_ReportDeadCodeInTrivialIfStatement, CompilerOptions.DISABLED);
15045
	this.runNegativeTest(
15046
			new String[] {
15047
				"Bug.java",
15048
				"public class Bug {\n" +
15049
				"	private static final boolean TRUE = true;\n" +
15050
				"   private static final boolean FALSE = false;\n" +
15051
				"	void foo() throws Exception {\n" + 
15052
				"		if (TRUE) return;\n" +
15053
				"		else System.out.println(\"\");\n" +
15054
				"		System.out.println(\"\");\n" + 		// not dead code
15055
				"		if (TRUE) throw new Exception();\n" +
15056
				"		else System.out.println(\"\");\n" +
15057
				"		System.out.println(\"\");\n" + 		// not dead code
15058
				"		if (TRUE) return;\n" +
15059
				"		System.out.println(\"\");\n" + 		// not dead code
15060
				"		if (FALSE) System.out.println(\"\");\n" +
15061
				"		else return;\n" +
15062
				"		System.out.println(\"\");\n" + 		// not dead code
15063
				"		if (FALSE) return;\n" +
15064
				"		System.out.println(\"\");\n" + 		// not dead code
15065
				"		if (false) return;\n" +				// dead code
15066
				"		System.out.println(\"\");\n" + 		
15067
				"		if (true) return;\n" +
15068
				"		System.out.println(\"\");\n" + 		// dead code
15069
				"	}\n" + 
15070
				"}\n"
15071
			},
15072
			"----------\n" + 
15073
			"1. WARNING in Bug.java (at line 18)\n" + 
15074
			"	if (false) return;\n" + 
15075
			"	           ^^^^^^^\n" + 
15076
			"Dead code\n" + 
15077
			"----------\n" + 
15078
			"2. WARNING in Bug.java (at line 21)\n" + 
15079
			"	System.out.println(\"\");\n" + 
15080
			"	^^^^^^^^^^^^^^^^^^^^^^\n" + 
15081
			"Dead code\n" + 
15082
			"----------\n",
15083
			null,
15084
			true,
15085
			compilerOptions);
15086
}
15087
// https://bugs.eclipse.org/bugs/show_bug.cgi?id=256796
15088
public void testBug256796a() {
15089
	Map compilerOptions = getCompilerOptions();
15090
	compilerOptions.put(CompilerOptions.OPTION_ReportUnnecessaryElse, CompilerOptions.IGNORE);
15091
	compilerOptions.put(CompilerOptions.OPTION_ReportDeadCode, CompilerOptions.WARNING);
15092
	compilerOptions.put(CompilerOptions.OPTION_ReportDeadCodeInTrivialIfStatement, CompilerOptions.ENABLED);
15093
	this.runNegativeTest(
15094
			new String[] {
15095
				"Bug.java",
15096
				"public class Bug {\n" +
15097
				"	private static final boolean TRUE = true;\n" +
15098
				"   private static final boolean FALSE = false;\n" +
15099
				"	void foo() throws Exception {\n" + 
15100
				"		if (TRUE) return;\n" +
15101
				"		else System.out.println(\"\");\n" +
15102
				"		System.out.println(\"\");\n" + 		// dead code
15103
				"	}\n" +
15104
				"   void foo2() {\n" +
15105
				"		if (TRUE) return;\n" +
15106
				"		System.out.println(\"\");\n" + 		// dead code
15107
				"	}\n" +
15108
				"	void foo3() throws Exception {\n" + 
15109
				"		if (TRUE) throw new Exception();\n" +
15110
				"		else System.out.println(\"\");\n" + // dead code
15111
				"		System.out.println(\"\");\n" + 		// dead code
15112
				"	}\n" + 
15113
				"	void foo4() throws Exception {\n" + 
15114
				"		if (FALSE) System.out.println(\"\");\n" +
15115
				"		else return;\n" +
15116
				"		System.out.println(\"\");\n" + 		// dead code
15117
				"	}\n" + 
15118
				"	void foo5() throws Exception {\n" + 
15119
				"		if (FALSE) return;\n" +				// dead code
15120
				"		System.out.println(\"\");\n" + 		
15121
				"	}\n" +
15122
				"	void foo6() throws Exception {\n" + 
15123
				"		if (false) return;\n" +				// dead code
15124
				"		System.out.println(\"\");\n" + 		
15125
				"		if (true) return;\n" +
15126
				"		System.out.println(\"\");\n" + 		// dead code
15127
				"	}\n" +
15128
				"}\n"
15129
			},
15130
			"----------\n" + 
15131
			"1. WARNING in Bug.java (at line 6)\n" + 
15132
			"	else System.out.println(\"\");\n" + 
15133
			"	     ^^^^^^^^^^^^^^^^^^^^^^\n" + 
15134
			"Dead code\n" + 
15135
			"----------\n" + 
15136
			"2. WARNING in Bug.java (at line 7)\n" + 
15137
			"	System.out.println(\"\");\n" + 
15138
			"	^^^^^^^^^^^^^^^^^^^^^^\n" + 
15139
			"Dead code\n" + 
15140
			"----------\n" + 
15141
			"3. WARNING in Bug.java (at line 11)\n" + 
15142
			"	System.out.println(\"\");\n" + 
15143
			"	^^^^^^^^^^^^^^^^^^^^^^\n" + 
15144
			"Dead code\n" + 
15145
			"----------\n" + 
15146
			"4. WARNING in Bug.java (at line 15)\n" + 
15147
			"	else System.out.println(\"\");\n" + 
15148
			"	     ^^^^^^^^^^^^^^^^^^^^^^\n" + 
15149
			"Dead code\n" + 
15150
			"----------\n" + 
15151
			"5. WARNING in Bug.java (at line 16)\n" + 
15152
			"	System.out.println(\"\");\n" + 
15153
			"	^^^^^^^^^^^^^^^^^^^^^^\n" + 
15154
			"Dead code\n" + 
15155
			"----------\n" + 
15156
			"6. WARNING in Bug.java (at line 19)\n" + 
15157
			"	if (FALSE) System.out.println(\"\");\n" + 
15158
			"	           ^^^^^^^^^^^^^^^^^^^^^^\n" + 
15159
			"Dead code\n" + 
15160
			"----------\n" + 
15161
			"7. WARNING in Bug.java (at line 21)\n" + 
15162
			"	System.out.println(\"\");\n" + 
15163
			"	^^^^^^^^^^^^^^^^^^^^^^\n" + 
15164
			"Dead code\n" + 
15165
			"----------\n" + 
15166
			"8. WARNING in Bug.java (at line 24)\n" + 
15167
			"	if (FALSE) return;\n" + 
15168
			"	           ^^^^^^^\n" + 
15169
			"Dead code\n" + 
15170
			"----------\n" + 
15171
			"9. WARNING in Bug.java (at line 28)\n" + 
15172
			"	if (false) return;\n" + 
15173
			"	           ^^^^^^^\n" + 
15174
			"Dead code\n" + 
15175
			"----------\n" + 
15176
			"10. WARNING in Bug.java (at line 31)\n" + 
15177
			"	System.out.println(\"\");\n" + 
15178
			"	^^^^^^^^^^^^^^^^^^^^^^\n" + 
15179
			"Dead code\n" + 
15180
			"----------\n",
15181
			null,
15182
			true,
15183
			compilerOptions);
15184
}
15185
// Bug 360328 - [compiler][null] detect null problems in nested code (local class inside a loop)
15186
public void testBug360328() {
15187
	Map customOptions = getCompilerOptions();
15188
	customOptions.put(CompilerOptions.OPTION_ReportNullReference, CompilerOptions.ERROR);
15189
	customOptions.put(CompilerOptions.OPTION_ReportRedundantNullCheck, CompilerOptions.ERROR);
15190
	runNegativeTest(
15191
		true, /* flushOutputDir */
15192
		new String[] {
15193
			"X.java",
15194
			"public class X {\n" +
15195
			"    void print4() {\n" +
15196
			"        final String s1 = \"\";\n" +
15197
			"        for (int i=0; i<4; i++)\n" +
15198
			"            new Runnable() {\n" +
15199
			"                public void run() {\n" +
15200
			"                     if (s1 != null)\n" +
15201
			"                         s1.toString();\n" +
15202
			"                }\n" +
15203
			"            }.run();\n" +
15204
			"    }\n" +
15205
			"    void print16(boolean b) {\n" +
15206
			"        final String s3 = b ? null : \"\";\n" +
15207
			"        for (int i=0; i<16; i++)\n" +
15208
			"            new Runnable() {\n" +
15209
			"                public void run() {\n" +
15210
			"                     s3.toString();\n" +
15211
			"                }\n" +
15212
			"            }.run();\n" +
15213
			"    }\n" +
15214
			"    void print23() {\n" +
15215
			"        final String s23 = null;\n" +
15216
			"        for (int i=0; i<23; i++)\n" +
15217
			"            new Runnable() {\n" +
15218
			"                public void run() {\n" +
15219
			"                     s23.toString();\n" +
15220
			"                }\n" +
15221
			"            }.run();\n" +
15222
			"    }\n" +
15223
			"}\n",
15224
15225
		},
15226
		null, /* classLibs */
15227
		customOptions,
15228
		"----------\n" +
15229
		"1. ERROR in X.java (at line 7)\n" +
15230
		"	if (s1 != null)\n" +
15231
		"	    ^^\n" +
15232
		"Redundant null check: The variable s1 cannot be null at this location\n" +
15233
		"----------\n" +
15234
		"2. ERROR in X.java (at line 17)\n" +
15235
		"	s3.toString();\n" +
15236
		"	^^\n" +
15237
		"Potential null pointer access: The variable s3 may be null at this location\n" +
15238
		"----------\n" +
15239
		"3. ERROR in X.java (at line 26)\n" +
15240
		"	s23.toString();\n" +
15241
		"	^^^\n" +
15242
		"Null pointer access: The variable s23 can only be null at this location\n" +
15243
		"----------\n",
15244
		"",/* expected output */
15245
		"",/* expected error */
15246
	    JavacTestOptions.Excuse.EclipseWarningConfiguredAsError);
15247
}
15248
// Bug 360328 - [compiler][null] detect null problems in nested code (local class inside a loop)
15249
// constructors
15250
public void testBug360328b() {
15251
	Map customOptions = getCompilerOptions();
15252
	customOptions.put(CompilerOptions.OPTION_ReportNullReference, CompilerOptions.ERROR);
15253
	customOptions.put(CompilerOptions.OPTION_ReportRedundantNullCheck, CompilerOptions.ERROR);
15254
	runNegativeTest(
15255
		true, /* flushOutputDir */
15256
		new String[] {
15257
			"X.java",
15258
			"public class X {\n" +
15259
			"    void print4() {\n" +
15260
			"        final String s1 = \"\";\n" +
15261
			"        for (int i=0; i<4; i++) {\n" +
15262
			"            class R {\n" +
15263
			"                public R() {\n" +
15264
			"                     if (s1 != null)\n" +
15265
			"                         s1.toString();\n" +
15266
			"                }\n" +
15267
			"            };\n" +
15268
			"            new R();\n" +
15269
			"        }\n" +
15270
			"    }\n" +
15271
			"    void print16(boolean b) {\n" +
15272
			"        final String s3 = b ? null : \"\";\n" +
15273
			"        int i=0; while (i++<16) {\n" +
15274
			"            class R {\n" +
15275
			"                public R() {\n" +
15276
			"                     s3.toString();\n" +
15277
			"                }\n" +
15278
			"            };\n" +
15279
			"            new R();\n" +
15280
			"        };\n" +
15281
			"    }\n" +
15282
			"    void print23() {\n" +
15283
			"        final String s23 = null;\n" +
15284
			"        for (int i=0; i<23; i++) {\n" +
15285
			"            class R {\n" +
15286
			"                public R() {\n" +
15287
			"                     s23.toString();\n" +
15288
			"                }\n" +
15289
			"            };\n" +
15290
			"            new R();\n" +
15291
			"        };\n" +
15292
			"    }\n" +
15293
			"}\n",
15294
15295
		},
15296
		null, /* classLibs */
15297
		customOptions,
15298
		"----------\n" +
15299
		"1. ERROR in X.java (at line 7)\n" +
15300
		"	if (s1 != null)\n" +
15301
		"	    ^^\n" +
15302
		"Redundant null check: The variable s1 cannot be null at this location\n" +
15303
		"----------\n" +
15304
		"2. ERROR in X.java (at line 19)\n" +
15305
		"	s3.toString();\n" +
15306
		"	^^\n" +
15307
		"Potential null pointer access: The variable s3 may be null at this location\n" +
15308
		"----------\n" +
15309
		"3. ERROR in X.java (at line 30)\n" +
15310
		"	s23.toString();\n" +
15311
		"	^^^\n" +
15312
		"Null pointer access: The variable s23 can only be null at this location\n" +
15313
		"----------\n",
15314
		"",/* expected output */
15315
		"",/* expected error */
15316
	    JavacTestOptions.Excuse.EclipseWarningConfiguredAsError);
15317
}
15318
// Bug 360328 - [compiler][null] detect null problems in nested code (local class inside a loop)
15319
// initializers
15320
public void testBug360328c() {
15321
	Map customOptions = getCompilerOptions();
15322
	customOptions.put(CompilerOptions.OPTION_ReportNullReference, CompilerOptions.ERROR);
15323
	customOptions.put(CompilerOptions.OPTION_ReportRedundantNullCheck, CompilerOptions.ERROR);
15324
	customOptions.put(CompilerOptions.OPTION_ReportUnusedPrivateMember, CompilerOptions.IGNORE);
15325
	runNegativeTest(
15326
		true, /* flushOutputDir */
15327
		new String[] {
15328
			"X.java",
15329
			"public class X {\n" +
15330
			"    void print4() {\n" +
15331
			"        final String s1 = \"\";\n" +
15332
			"        for (int i=0; i<4; i++) {\n" +
15333
			"            class R {\n" +
15334
			"                String s1R;\n" +
15335
			"                {\n" +
15336
			"                    if (s1 != null)\n" +
15337
			"                         s1R = s1;\n" +
15338
			"                }\n" +
15339
			"            };\n" +
15340
			"            new R();\n" +
15341
			"        }\n" +
15342
			"    }\n" +
15343
			"    void print16(boolean b) {\n" +
15344
			"        final String s3 = b ? null : \"\";\n" +
15345
			"        for (int i=0; i<16; i++) {\n" +
15346
			"            class R {\n" +
15347
			"                String s3R = s3.toString();\n" +
15348
			"            };\n" +
15349
			"            new R();\n" +
15350
			"        };\n" +
15351
			"    }\n" +
15352
			"    void print23() {\n" +
15353
			"        final String s23 = null;\n" +
15354
			"        for (int i=0; i<23; i++) {\n" +
15355
			"            class R {\n" +
15356
			"                String s23R;\n" +
15357
			"                {\n" +
15358
			"                     s23R = s23.toString();\n" +
15359
			"                }\n" +
15360
			"            };\n" +
15361
			"            new R();\n" +
15362
			"        };\n" +
15363
			"    }\n" +
15364
			"}\n",
15365
15366
		},
15367
		null, /* classLibs */
15368
		customOptions,
15369
		"----------\n" +
15370
		"1. ERROR in X.java (at line 8)\n" +
15371
		"	if (s1 != null)\n" +
15372
		"	    ^^\n" +
15373
		"Redundant null check: The variable s1 cannot be null at this location\n" +
15374
		"----------\n" +
15375
		"2. ERROR in X.java (at line 19)\n" +
15376
		"	String s3R = s3.toString();\n" +
15377
		"	             ^^\n" +
15378
		"Potential null pointer access: The variable s3 may be null at this location\n" +
15379
		"----------\n" +
15380
		"3. ERROR in X.java (at line 30)\n" +
15381
		"	s23R = s23.toString();\n" +
15382
		"	       ^^^\n" +
15383
		"Null pointer access: The variable s23 can only be null at this location\n" +
15384
		"----------\n",
15385
		"",/* expected output */
15386
		"",/* expected error */
15387
	    JavacTestOptions.Excuse.EclipseWarningConfiguredAsError);
15388
}
15389
// Bug 360328 - [compiler][null] detect null problems in nested code (local class inside a loop)
15390
// try-finally instead of loop
15391
public void testBug360328d() {
15392
	Map customOptions = getCompilerOptions();
15393
	customOptions.put(CompilerOptions.OPTION_ReportNullReference, CompilerOptions.ERROR);
15394
	customOptions.put(CompilerOptions.OPTION_ReportRedundantNullCheck, CompilerOptions.ERROR);
15395
	runNegativeTest(
15396
		true, /* flushOutputDir */
15397
		new String[] {
15398
			"X.java",
15399
			"public class X {\n" +
15400
			"    void print4() {\n" +
15401
			"        final String s1 = \"\";\n" +
15402
			"        try { } finally {\n" +
15403
			"            new Runnable() {\n" +
15404
			"                public void run() {\n" +
15405
			"                     if (s1 != null)\n" +
15406
			"                         s1.toString();\n" +
15407
			"                }\n" +
15408
			"            }.run();\n" +
15409
			"        }\n" +
15410
			"    }\n" +
15411
			"    void print16(boolean b) {\n" +
15412
			"        final String s3 = b ? null : \"\";\n" +
15413
			"        try { } finally {\n" +
15414
			"            new Runnable() {\n" +
15415
			"                public void run() {\n" +
15416
			"                     s3.toString();\n" +
15417
			"                }\n" +
15418
			"            }.run();\n" +
15419
			"        }\n" +
15420
			"    }\n" +
15421
			"    void print23() {\n" +
15422
			"        final String s23 = null;\n" +
15423
			"        try { } finally {\n" +
15424
			"            new Runnable() {\n" +
15425
			"                public void run() {\n" +
15426
			"                     s23.toString();\n" +
15427
			"                }\n" +
15428
			"            }.run();\n" +
15429
			"        }\n" +
15430
			"    }\n" +
15431
			"}\n",
15432
15433
		},
15434
		null, /* classLibs */
15435
		customOptions,
15436
		"----------\n" +
15437
		"1. ERROR in X.java (at line 7)\n" +
15438
		"	if (s1 != null)\n" +
15439
		"	    ^^\n" +
15440
		"Redundant null check: The variable s1 cannot be null at this location\n" +
15441
		"----------\n" +
15442
		"2. ERROR in X.java (at line 18)\n" +
15443
		"	s3.toString();\n" +
15444
		"	^^\n" +
15445
		"Potential null pointer access: The variable s3 may be null at this location\n" +
15446
		"----------\n" +
15447
		"3. ERROR in X.java (at line 28)\n" +
15448
		"	s23.toString();\n" +
15449
		"	^^^\n" +
15450
		"Null pointer access: The variable s23 can only be null at this location\n" +
15451
		"----------\n",
15452
		"",/* expected output */
15453
		"",/* expected error */
15454
	    JavacTestOptions.Excuse.EclipseWarningConfiguredAsError);
15455
}
14947
}
15456
}
(-)a/org.eclipse.jdt.core.tests.compiler/src/org/eclipse/jdt/core/tests/compiler/regression/ProblemTypeAndMethodTest.java (+112 lines)
Lines 7076-7079 Link Here
7076
		compilerOptions /* custom options */
7076
		compilerOptions /* custom options */
7077
	);
7077
	);
7078
}
7078
}
7079
7080
// https://bugs.eclipse.org/bugs/show_bug.cgi?id=354502
7081
// Anonymous class instantiation of a non-static member type, method can't be static
7082
public void test354502() {
7083
	if (this.complianceLevel < ClassFileConstants.JDK1_5)
7084
		return;
7085
	Map compilerOptions = getCompilerOptions();
7086
	compilerOptions.put(CompilerOptions.OPTION_ReportMethodCanBeStatic, CompilerOptions.ERROR);
7087
	compilerOptions.put(CompilerOptions.OPTION_ReportMethodCanBePotentiallyStatic, CompilerOptions.ERROR);
7088
	compilerOptions.put(CompilerOptions.OPTION_ReportUnusedPrivateMember, CompilerOptions.IGNORE);
7089
	this.runNegativeTest(
7090
		new String[] {
7091
				"X.java", 
7092
				"public class X {\n" +
7093
				"   public abstract class Abstract{}\n" +
7094
				"   public static abstract class Abstract2{}\n" +
7095
				"	private void method1() {\n" + 	// don't warn
7096
				"		new Abstract() {};\n" +
7097
				"	}\n" +
7098
				"	private void method2() {\n" + 	// warn
7099
				"		new Abstract2() {};\n" +
7100
				"	}\n" +
7101
				"}"
7102
		},
7103
		"----------\n" + 
7104
		"1. ERROR in X.java (at line 7)\n" + 
7105
		"	private void method2() {\n" + 
7106
		"	             ^^^^^^^^^\n" + 
7107
		"The method method2() from the type X can be declared as static\n" + 
7108
		"----------\n",
7109
		null /* no extra class libraries */,
7110
		true /* flush output directory */,
7111
		compilerOptions /* custom options */
7112
	);
7113
}
7114
// https://bugs.eclipse.org/bugs/show_bug.cgi?id=360164
7115
public void test360164() {
7116
	if (this.complianceLevel < ClassFileConstants.JDK1_5) return;
7117
	this.runConformTest(
7118
			new String[] {
7119
					"p/B.java", 
7120
					"package p;\n" +
7121
					"\n" +
7122
					"public abstract class B<K,V> {\n" +
7123
					"	 protected abstract V foo(K element);\n" +
7124
					"}\n",
7125
					"p/C.java", 
7126
					"package p;\n" +
7127
					"public class C {\n" +
7128
					"}\n",
7129
					"p/D.java", 
7130
					"package p;\n" +
7131
					"public class D extends E {\n" +
7132
					"}\n",
7133
					"p/E.java", 
7134
					"package p;\n" +
7135
					"public abstract class E implements I {\n" +
7136
					"}\n",
7137
					"p/I.java", 
7138
					"package p;\n" +
7139
					"public interface I {\n" +
7140
					"}\n",
7141
					"p/X.java", 
7142
					"package p;\n" +
7143
					"public class X {\n" +
7144
					"	private final class A extends B<C,D>{\n" +
7145
					"		@Override\n" +
7146
					"		protected D foo(C c) {\n" +
7147
					"			return null;\n" +
7148
					"		}\n" +
7149
					"   }\n" +
7150
					"}\n",
7151
			},
7152
			"");
7153
7154
	// delete binary file I (i.e. simulate removing it from classpath for subsequent compile)
7155
	Util.delete(new File(OUTPUT_DIR, "p" + File.separator + "I.class"));
7156
7157
	runNegativeTest(
7158
		// test directory preparation
7159
		false /* do not flush output directory */,
7160
		new String[] { /* test files */
7161
				"p/X.java", 
7162
				"package p;\n" +
7163
				"public class X {\n" +
7164
				"	private final class A extends B<C,D>{\n" +
7165
				"		@Override\n" +
7166
				"		protected D foo(C c) {\n" +
7167
				"            Zork z;\n" +
7168
				"			return null;\n" +
7169
				"		}\n" +
7170
				"   }\n" +
7171
				"}\n",
7172
		},
7173
		// compiler options
7174
		null /* no class libraries */,
7175
		null /* no custom options */,
7176
		// compiler results 
7177
		"----------\n" + 
7178
		"1. WARNING in p\\X.java (at line 3)\n" + 
7179
		"	private final class A extends B<C,D>{\n" + 
7180
		"	                    ^\n" + 
7181
		"The type X.A is never used locally\n" + 
7182
		"----------\n" + 
7183
		"2. ERROR in p\\X.java (at line 6)\n" + 
7184
		"	Zork z;\n" + 
7185
		"	^^^^\n" + 
7186
		"Zork cannot be resolved to a type\n" + 
7187
		"----------\n",
7188
		// javac options
7189
		JavacTestOptions.SKIP_UNTIL_FRAMEWORK_FIX /* javac test options */);
7190
}
7079
}
7191
}
(-)a/org.eclipse.jdt.core.tests.compiler/src/org/eclipse/jdt/core/tests/compiler/regression/ResourceLeakTests.java (+3713 lines)
Added Link Here
1
/*******************************************************************************
2
 * Copyright (c) 2011, 2012 GK Software AG and others.
3
 * All rights reserved. This program and the accompanying materials
4
 * are made available under the terms of the Eclipse Public License v1.0
5
 * which accompanies this distribution, and is available at
6
 * http://www.eclipse.org/legal/epl-v10.html
7
 *
8
 * Contributors:
9
 *     Stephan Herrmann - initial API and implementation
10
 *******************************************************************************/
11
package org.eclipse.jdt.core.tests.compiler.regression;
12
13
import java.io.IOException;
14
import java.net.URL;
15
import java.util.Map;
16
17
import junit.framework.Test;
18
19
import org.eclipse.core.runtime.FileLocator;
20
import org.eclipse.core.runtime.Path;
21
import org.eclipse.core.runtime.Platform;
22
import org.eclipse.jdt.core.JavaCore;
23
import org.eclipse.jdt.internal.compiler.classfmt.ClassFileConstants;
24
import org.eclipse.jdt.internal.compiler.impl.CompilerOptions;
25
26
public class ResourceLeakTests extends AbstractRegressionTest {
27
28
static {
29
//	TESTS_NAMES = new String[] { "test066"};
30
//	TESTS_NUMBERS = new int[] { 50 };
31
//	TESTS_RANGE = new int[] { 11, -1 };
32
}
33
public ResourceLeakTests(String name) {
34
	super(name);
35
}
36
public static Test suite() {
37
	return buildAllCompliancesTestSuite(ResourceLeakTests.class);
38
}
39
40
void runTestsExpectingErrorsOnlyIn17(String[] testFiles, String errorsIn17, Map options) {
41
	if (this.complianceLevel >= ClassFileConstants.JDK1_7)
42
		runNegativeTest(testFiles, errorsIn17, null, true, options);
43
	else
44
		runConformTest(testFiles, "", null, true, null, options, null);
45
}
46
47
// Bug 349326 - [1.7] new warning for missing try-with-resources
48
// a method uses an AutoCloseable without ever closing it.
49
public void test056() {
50
	Map options = getCompilerOptions();
51
	options.put(CompilerOptions.OPTION_ReportUnclosedCloseable, CompilerOptions.ERROR);
52
	options.put(CompilerOptions.OPTION_ReportPotentiallyUnclosedCloseable, CompilerOptions.WARNING);
53
	this.runNegativeTest(
54
		new String[] {
55
			"X.java",
56
			"import java.io.File;\n" +
57
			"import java.io.FileReader;\n" +
58
			"import java.io.IOException;\n" +
59
			"public class X {\n" +
60
			"    void foo() throws IOException {\n" +
61
			"        File file = new File(\"somefile\");\n" +
62
			"        FileReader fileReader = new FileReader(file);\n" +
63
// not invoking any methods on FileReader, try to avoid necessary call to superclass() in the compiler
64
//			"        char[] in = new char[50];\n" +
65
//			"        fileReader.read(in);\n" +
66
			"    }\n" +
67
			"    public static void main(String[] args) throws IOException {\n" +
68
			"        new X().foo();\n" +
69
			"    }\n" +
70
			"}\n"
71
		},
72
		"----------\n" +
73
		"1. ERROR in X.java (at line 7)\n" +
74
		"	FileReader fileReader = new FileReader(file);\n" +
75
		"	           ^^^^^^^^^^\n" +
76
		"Resource leak: 'fileReader' is never closed\n" +
77
		"----------\n",
78
		null,
79
		true,
80
		options);
81
}
82
// Bug 349326 - [1.7] new warning for missing try-with-resources
83
// a method uses an AutoCloseable and closes it but not protected by t-w-r nor regular try-finally
84
public void test056a() {
85
	Map options = getCompilerOptions();
86
	options.put(CompilerOptions.OPTION_ReportUnclosedCloseable, CompilerOptions.ERROR);
87
	options.put(CompilerOptions.OPTION_ReportPotentiallyUnclosedCloseable, CompilerOptions.ERROR);
88
	options.put(CompilerOptions.OPTION_ReportExplicitlyClosedAutoCloseable, CompilerOptions.ERROR);
89
	runTestsExpectingErrorsOnlyIn17(
90
		new String[] {
91
			"X.java",
92
			"import java.io.File;\n" +
93
			"import java.io.FileReader;\n" +
94
			"import java.io.IOException;\n" +
95
			"public class X {\n" +
96
			"    void foo() throws IOException {\n" +
97
			"        File file = new File(\"somefile\");\n" +
98
			"        FileReader fileReader = new FileReader(file);\n" +
99
			"        char[] in = new char[50];\n" +
100
			"        fileReader.read(in);\n" +
101
			"		 fileReader.close();\n" +
102
			"    }\n" +
103
			"}\n"
104
		},
105
		"----------\n" +
106
		"1. ERROR in X.java (at line 7)\n" +
107
		"	FileReader fileReader = new FileReader(file);\n" +
108
		"	           ^^^^^^^^^^\n" +
109
		"Resource 'fileReader' should be managed by try-with-resource\n" +
110
		"----------\n",
111
		options);
112
}
113
// Bug 349326 - [1.7] new warning for missing try-with-resources
114
// a method uses an AutoCloseable and closes it properly in a finally block
115
public void test056b() {
116
	Map options = getCompilerOptions();
117
	options.put(CompilerOptions.OPTION_ReportUnclosedCloseable, CompilerOptions.ERROR);
118
	options.put(CompilerOptions.OPTION_ReportPotentiallyUnclosedCloseable, CompilerOptions.ERROR);
119
	this.runConformTest(
120
		new String[] {
121
			"X.java",
122
			"import java.io.File;\n" +
123
			"import java.io.FileReader;\n" +
124
			"import java.io.IOException;\n" +
125
			"public class X {\n" +
126
			"    void foo() throws IOException {\n" +
127
			"        File file = new File(\"somefile\");\n" +
128
			"        FileReader fileReader = new FileReader(file);\n" +
129
			"        try {\n" +
130
			"            char[] in = new char[50];\n" +
131
			"            fileReader.read(in);\n" +
132
			"        } finally {\n" +
133
			"		     fileReader.close();\n" +
134
			"        }\n" +
135
			"    }\n" +
136
			"    public static void main(String[] args) {\n" +
137
			"        try {\n" +
138
			"            new X().foo();\n" +
139
			"        } catch (IOException ioex) {\n" +
140
			"            System.out.println(\"caught\");\n" +
141
			"        }\n" +
142
			"    }\n" +
143
			"}\n"
144
		},
145
		"caught", /*output*/
146
		null/*classLibs*/,
147
		true/*shouldFlush*/,
148
		null/*vmargs*/,
149
		options,
150
		null/*requestor*/);
151
}
152
// Bug 349326 - [1.7] new warning for missing try-with-resources
153
// a method uses an AutoCloseable properly within try-with-resources.
154
public void test056c() {
155
	if (this.complianceLevel < ClassFileConstants.JDK1_7) return; // t-w-r used
156
	Map options = getCompilerOptions();
157
	options.put(CompilerOptions.OPTION_ReportUnclosedCloseable, CompilerOptions.ERROR);
158
	options.put(CompilerOptions.OPTION_ReportPotentiallyUnclosedCloseable, CompilerOptions.WARNING);
159
	this.runConformTest(
160
		new String[] {
161
			"X.java",
162
			"import java.io.File;\n" +
163
			"import java.io.FileReader;\n" +
164
			"import java.io.IOException;\n" +
165
			"public class X {\n" +
166
			"    void foo() throws IOException {\n" +
167
			"        File file = new File(\"somefile\");\n" +
168
			"        try (FileReader fileReader = new FileReader(file)) {\n" +
169
			"            char[] in = new char[50];\n" +
170
			"            fileReader.read(in);\n" +
171
			"		 }\n" +
172
			"    }\n" +
173
			"    public static void main(String[] args) {\n" +
174
			"        try {\n" +
175
			"            new X().foo();\n" +
176
			"        } catch (IOException ioex) {\n" +
177
			"            System.out.println(\"caught\");\n" +
178
			"        }\n" +
179
			"    }\n" +
180
			"}\n"
181
		},
182
		"caught", /*output*/
183
		null/*classLibs*/,
184
		true/*shouldFlush*/,
185
		null/*vmargs*/,
186
		options,
187
		null/*requestor*/);
188
}
189
// Bug 349326 - [1.7] new warning for missing try-with-resources
190
// a method uses two AutoCloseables (testing independent analysis)
191
//- one closeable may be unclosed at a conditional return
192
//- the other is only conditionally closed
193
public void test056d() {
194
	Map options = getCompilerOptions();
195
	options.put(CompilerOptions.OPTION_ReportUnclosedCloseable, CompilerOptions.ERROR);
196
	options.put(CompilerOptions.OPTION_ReportPotentiallyUnclosedCloseable, CompilerOptions.WARNING);
197
	this.runNegativeTest(
198
		new String[] {
199
			"X.java",
200
			"import java.io.File;\n" +
201
			"import java.io.FileReader;\n" +
202
			"import java.io.IOException;\n" +
203
			"public class X {\n" +
204
			"    void foo(boolean flag1, boolean flag2) throws IOException {\n" +
205
			"        File file = new File(\"somefile\");\n" +
206
			"        char[] in = new char[50];\n" +
207
			"        FileReader fileReader1 = new FileReader(file);\n" +
208
			"        fileReader1.read(in);\n" +
209
			"        FileReader fileReader2 = new FileReader(file);\n" +
210
			"        fileReader2.read(in);\n" +
211
			"        if (flag1) {\n" +
212
			"            fileReader2.close();\n" +
213
			"            return;\n" +
214
			"        } else if (flag2) {\n" +
215
			"            fileReader2.close();\n" +
216
			"        }\n" +
217
			"        fileReader1.close();\n" +
218
			"    }\n" +
219
			"    public static void main(String[] args) throws IOException {\n" +
220
			"        new X().foo(false, true);\n" +
221
			"    }\n" +
222
			"}\n"
223
		},
224
		"----------\n" +
225
		"1. WARNING in X.java (at line 10)\n" +
226
		"	FileReader fileReader2 = new FileReader(file);\n" +
227
		"	           ^^^^^^^^^^^\n" +
228
		"Potential resource leak: 'fileReader2' may not be closed\n" +
229
		"----------\n" +
230
		"2. ERROR in X.java (at line 14)\n" +
231
		"	return;\n" +
232
		"	^^^^^^^\n" +
233
		"Resource leak: 'fileReader1' is not closed at this location\n" +
234
		"----------\n",
235
		null,
236
		true,
237
		options);
238
}
239
// Bug 349326 - [1.7] new warning for missing try-with-resources
240
// a method uses two AutoCloseables (testing independent analysis)
241
//- one closeable may be unclosed at a conditional return
242
//- the other is only conditionally closed
243
public void test056d_suppress() {
244
	if (this.complianceLevel < ClassFileConstants.JDK1_5) return; // annotations used
245
	Map options = getCompilerOptions();
246
	options.put(CompilerOptions.OPTION_ReportUnclosedCloseable, CompilerOptions.ERROR);
247
	options.put(CompilerOptions.OPTION_ReportPotentiallyUnclosedCloseable, CompilerOptions.WARNING);
248
	options.put(CompilerOptions.OPTION_SuppressOptionalErrors, CompilerOptions.ENABLED);
249
	this.runNegativeTest(
250
		new String[] {
251
			"X.java",
252
			"import java.io.File;\n" +
253
			"import java.io.FileReader;\n" +
254
			"import java.io.IOException;\n" +
255
			"public class X {\n" +
256
			"    void foo(boolean flag1, boolean flag2) throws IOException {\n" +
257
			"        @SuppressWarnings(\"resource\") File file = new File(\"somefile\"); // unnecessary suppress\n" +
258
			"        char[] in = new char[50];\n" +
259
			"        FileReader fileReader1 = new FileReader(file);\n" +
260
			"        fileReader1.read(in);\n" +
261
			"        @SuppressWarnings(\"resource\") FileReader fileReader2 = new FileReader(file); // useful suppress\n" +
262
			"        fileReader2.read(in);\n" +
263
			"        if (flag1) {\n" +
264
			"            fileReader2.close();\n" +
265
			"            return; // not suppressed\n" +
266
			"        } else if (flag2) {\n" +
267
			"            fileReader2.close();\n" +
268
			"        }\n" +
269
			"        fileReader1.close();\n" +
270
			"    }\n" +
271
			"    @SuppressWarnings(\"resource\") // useful suppress\n" +
272
			"    void bar() throws IOException {\n" +
273
			"        File file = new File(\"somefile\");\n" +
274
			"        FileReader fileReader = new FileReader(file);\n" +
275
			"        char[] in = new char[50];\n" +
276
			"        fileReader.read(in);\n" +
277
			"    }\n" +
278
			"    public static void main(String[] args) throws IOException {\n" +
279
			"        new X().foo(false, true);\n" +
280
			"    }\n" +
281
			"}\n"
282
		},
283
		"----------\n" +
284
		"1. WARNING in X.java (at line 6)\n" +
285
		"	@SuppressWarnings(\"resource\") File file = new File(\"somefile\"); // unnecessary suppress\n" +
286
		"	                  ^^^^^^^^^^\n" +
287
		"Unnecessary @SuppressWarnings(\"resource\")\n" +
288
		"----------\n" +
289
		"2. ERROR in X.java (at line 14)\n" +
290
		"	return; // not suppressed\n" +
291
		"	^^^^^^^\n" +
292
		"Resource leak: 'fileReader1' is not closed at this location\n" +
293
		"----------\n",
294
		null,
295
		true,
296
		options);
297
}
298
// Bug 349326 - [1.7] new warning for missing try-with-resources
299
// Bug 362332 - Only report potential leak when closeable not created in the local scope
300
// one method returns an AutoCleasble, a second method uses this object without ever closing it.
301
public void test056e() {
302
	Map options = getCompilerOptions();
303
	options.put(CompilerOptions.OPTION_ReportUnclosedCloseable, CompilerOptions.ERROR);
304
	options.put(CompilerOptions.OPTION_ReportPotentiallyUnclosedCloseable, CompilerOptions.ERROR);
305
	this.runNegativeTest(
306
		new String[] {
307
			"X.java",
308
			"import java.io.File;\n" +
309
			"import java.io.FileReader;\n" +
310
			"import java.io.IOException;\n" +
311
			"public class X {\n" +
312
			"    FileReader getReader(String filename) throws IOException {\n" +
313
			"        File file = new File(\"somefile\");\n" +
314
			"        FileReader fileReader = new FileReader(file);\n" +
315
			"        return fileReader;\n" + 		// don't complain here, pass responsibility to caller
316
			"    }\n" +
317
			"    void foo() throws IOException {\n" +
318
			"        FileReader reader = getReader(\"somefile\");\n" +
319
			"        char[] in = new char[50];\n" +
320
			"        reader.read(in);\n" +
321
			"    }\n" +
322
			"    public static void main(String[] args) throws IOException {\n" +
323
			"        new X().foo();\n" +
324
			"    }\n" +
325
			"}\n"
326
		},
327
		"----------\n" +
328
		"1. ERROR in X.java (at line 11)\n" +
329
		"	FileReader reader = getReader(\"somefile\");\n" +
330
		"	           ^^^^^^\n" +
331
		"Potential resource leak: \'reader\' may not be closed\n" +
332
		"----------\n",
333
		null,
334
		true,
335
		options);
336
}
337
// Bug 349326 - [1.7] new warning for missing try-with-resources
338
// a method explicitly closes its AutoCloseable rather than using t-w-r
339
public void test056f() {
340
	Map options = getCompilerOptions();
341
	options.put(CompilerOptions.OPTION_ReportUnclosedCloseable, CompilerOptions.ERROR);
342
	options.put(CompilerOptions.OPTION_ReportPotentiallyUnclosedCloseable, CompilerOptions.WARNING);
343
	options.put(CompilerOptions.OPTION_ReportExplicitlyClosedAutoCloseable, CompilerOptions.ERROR);
344
	runTestsExpectingErrorsOnlyIn17(
345
		new String[] {
346
			"X.java",
347
			"import java.io.File;\n" +
348
			"import java.io.FileReader;\n" +
349
			"import java.io.IOException;\n" +
350
			"public class X {\n" +
351
			"    void foo() throws IOException {\n" +
352
			"        File file = new File(\"somefile\");\n" +
353
			"        FileReader fileReader = null;\n" +
354
			"        try {\n" +
355
			"            fileReader = new FileReader(file);\n" +
356
			"            char[] in = new char[50];\n" +
357
			"            fileReader.read(in);\n" +
358
			"        } finally {\n" +
359
			"            fileReader.close();\n" +
360
			"        }\n" +
361
			"    }\n" +
362
			"}\n"
363
		},
364
		"----------\n" +
365
		"1. ERROR in X.java (at line 7)\n" +
366
		"	FileReader fileReader = null;\n" +
367
		"	           ^^^^^^^^^^\n" +
368
		"Resource 'fileReader' should be managed by try-with-resource\n" +
369
		"----------\n",
370
		options);
371
}
372
// Bug 349326 - [1.7] new warning for missing try-with-resources
373
// an AutoCloseable local is re-assigned
374
public void test056g() {
375
	Map options = getCompilerOptions();
376
	options.put(JavaCore.COMPILER_PB_UNCLOSED_CLOSEABLE, CompilerOptions.ERROR);
377
	options.put(JavaCore.COMPILER_PB_POTENTIALLY_UNCLOSED_CLOSEABLE, CompilerOptions.WARNING);
378
	options.put(JavaCore.COMPILER_PB_EXPLICITLY_CLOSED_AUTOCLOSEABLE, CompilerOptions.IGNORE);
379
	this.runNegativeTest(
380
		new String[] {
381
			"X.java",
382
			"import java.io.File;\n" +
383
			"import java.io.FileReader;\n" +
384
			"import java.io.IOException;\n" +
385
			"public class X {\n" +
386
			"    void foo() throws IOException {\n" +
387
			"        File file = new File(\"somefile\");\n" +
388
			"        FileReader fileReader = new FileReader(file);\n" +
389
			"        char[] in = new char[50];\n" +
390
			"        fileReader.read(in);\n" +
391
			"        fileReader = new FileReader(file);\n" +
392
			"        fileReader.read(in);\n" +
393
			"        fileReader.close();\n" +
394
			"        fileReader = null;\n" +
395
			"    }\n" +
396
			"    public static void main(String[] args) throws IOException {\n" +
397
			"        new X().foo();\n" +
398
			"    }\n" +
399
			"}\n"
400
		},
401
		"----------\n" +
402
		"1. ERROR in X.java (at line 10)\n" +
403
		"	fileReader = new FileReader(file);\n" +
404
		"	^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^\n" +
405
		"Resource leak: 'fileReader' is not closed at this location\n" +
406
		"----------\n",
407
		null,
408
		true,
409
		options);
410
}
411
// Bug 349326 - [1.7] new warning for missing try-with-resources
412
// an AutoCloseable local is re-assigned after null-assigned
413
public void test056g2() {
414
	Map options = getCompilerOptions();
415
	options.put(JavaCore.COMPILER_PB_UNCLOSED_CLOSEABLE, CompilerOptions.ERROR);
416
	options.put(JavaCore.COMPILER_PB_POTENTIALLY_UNCLOSED_CLOSEABLE, CompilerOptions.WARNING);
417
	options.put(JavaCore.COMPILER_PB_EXPLICITLY_CLOSED_AUTOCLOSEABLE, CompilerOptions.IGNORE);
418
	this.runNegativeTest(
419
		new String[] {
420
			"X.java",
421
			"import java.io.File;\n" +
422
			"import java.io.FileReader;\n" +
423
			"import java.io.IOException;\n" +
424
			"public class X {\n" +
425
			"    void foo() throws IOException {\n" +
426
			"        File file = new File(\"somefile\");\n" +
427
			"        FileReader fileReader = new FileReader(file);\n" +
428
			"        char[] in = new char[50];\n" +
429
			"        fileReader.read(in);\n" +
430
			"        fileReader = null;\n" +
431
			"        fileReader = new FileReader(file);\n" + // don't complain again, fileReader is null, so nothing can leak here
432
			"        fileReader.read(in);\n" +
433
			"        fileReader.close();\n" +
434
			"    }\n" +
435
			"    public static void main(String[] args) throws IOException {\n" +
436
			"        new X().foo();\n" +
437
			"    }\n" +
438
			"}\n"
439
		},
440
		"----------\n" +
441
		"1. ERROR in X.java (at line 10)\n" +
442
		"	fileReader = null;\n" +
443
		"	^^^^^^^^^^^^^^^^^\n" +
444
		"Resource leak: 'fileReader' is not closed at this location\n" +
445
		"----------\n",
446
		null,
447
		true,
448
		options);
449
}
450
// Bug 349326 - [1.7] new warning for missing try-with-resources
451
// two AutoCloseables at different nesting levels (anonymous local type)
452
public void test056h() {
453
	Map options = getCompilerOptions();
454
	options.put(JavaCore.COMPILER_PB_UNCLOSED_CLOSEABLE, CompilerOptions.ERROR);
455
	options.put(JavaCore.COMPILER_PB_POTENTIALLY_UNCLOSED_CLOSEABLE, CompilerOptions.WARNING);
456
	options.put(JavaCore.COMPILER_PB_EXPLICITLY_CLOSED_AUTOCLOSEABLE, CompilerOptions.IGNORE);
457
	this.runNegativeTest(
458
		new String[] {
459
			"X.java",
460
			"import java.io.File;\n" +
461
			"import java.io.FileReader;\n" +
462
			"import java.io.IOException;\n" +
463
			"public class X {\n" +
464
			"    void foo() throws IOException {\n" +
465
			"        final File file = new File(\"somefile\");\n" +
466
			"        final FileReader fileReader = new FileReader(file);\n" +
467
			"        char[] in = new char[50];\n" +
468
			"        fileReader.read(in);\n" +
469
			"        new Runnable() {\n public void run() {\n" +
470
			"            try {\n" +
471
			"                fileReader.close();\n" +
472
			"                FileReader localReader = new FileReader(file);\n" +
473
			"            } catch (IOException ex) { /* nop */ }\n" +
474
			"        }}.run();\n" +
475
			"    }\n" +
476
			"    public static void main(String[] args) throws IOException {\n" +
477
			"        new X().foo();\n" +
478
			"    }\n" +
479
			"}\n"
480
		},
481
		"----------\n" +
482
		"1. WARNING in X.java (at line 7)\n" +
483
		"	final FileReader fileReader = new FileReader(file);\n" +
484
		"	                 ^^^^^^^^^^\n" +
485
		"Potential resource leak: 'fileReader' may not be closed\n" +
486
		"----------\n" +
487
		"2. ERROR in X.java (at line 14)\n" +
488
		"	FileReader localReader = new FileReader(file);\n" +
489
		"	           ^^^^^^^^^^^\n" +
490
		"Resource leak: 'localReader' is never closed\n" +
491
		"----------\n",
492
		null,
493
		true,
494
		options);
495
}
496
// Bug 349326 - [1.7] new warning for missing try-with-resources
497
// three AutoCloseables in different blocks of the same method
498
public void test056i() {
499
	Map options = getCompilerOptions();
500
	options.put(JavaCore.COMPILER_PB_UNCLOSED_CLOSEABLE, CompilerOptions.ERROR);
501
	options.put(JavaCore.COMPILER_PB_POTENTIALLY_UNCLOSED_CLOSEABLE, CompilerOptions.WARNING);
502
	options.put(JavaCore.COMPILER_PB_EXPLICITLY_CLOSED_AUTOCLOSEABLE, CompilerOptions.IGNORE);
503
	this.runNegativeTest(
504
		new String[] {
505
			"X.java",
506
			"import java.io.File;\n" +
507
			"import java.io.FileReader;\n" +
508
			"import java.io.IOException;\n" +
509
			"public class X {\n" +
510
			"    void foo(boolean f1, boolean f2) throws IOException {\n" +
511
			"        File file = new File(\"somefile\");\n" +
512
			"        if (f1) {\n" +
513
			"            FileReader fileReader = new FileReader(file); // err: not closed\n" +
514
			"            char[] in = new char[50];\n" +
515
			"            fileReader.read(in);\n" +
516
			"            while (true) {\n" +
517
			"                 FileReader loopReader = new FileReader(file); // don't warn, properly closed\n" +
518
			"                 loopReader.close();" +
519
			"                 break;\n" +
520
			"            }\n" +
521
			"        } else {\n" +
522
			"            FileReader fileReader = new FileReader(file); // warn: not closed on all paths\n" +
523
			"            if (f2)\n" +
524
			"                fileReader.close();\n" +
525
			"        }\n" +
526
			"    }\n" +
527
			"    public static void main(String[] args) throws IOException {\n" +
528
			"        new X().foo(true, true);\n" +
529
			"    }\n" +
530
			"}\n"
531
		},
532
		"----------\n" +
533
		"1. ERROR in X.java (at line 8)\n" +
534
		"	FileReader fileReader = new FileReader(file); // err: not closed\n" +
535
		"	           ^^^^^^^^^^\n" +
536
		"Resource leak: 'fileReader' is never closed\n" +
537
		"----------\n" +
538
		"2. WARNING in X.java (at line 16)\n" +
539
		"	FileReader fileReader = new FileReader(file); // warn: not closed on all paths\n" +
540
		"	           ^^^^^^^^^^\n" +
541
		"Potential resource leak: 'fileReader' may not be closed\n" +
542
		"----------\n",
543
		null,
544
		true,
545
		options);
546
}
547
// Bug 349326 - [1.7] new warning for missing try-with-resources
548
// three AutoCloseables in different blocks of the same method - problems ignored
549
public void test056i_ignore() {
550
	Map options = getCompilerOptions();
551
	options.put(JavaCore.COMPILER_PB_UNCLOSED_CLOSEABLE, CompilerOptions.IGNORE);
552
	options.put(JavaCore.COMPILER_PB_POTENTIALLY_UNCLOSED_CLOSEABLE, CompilerOptions.IGNORE);
553
	options.put(JavaCore.COMPILER_PB_EXPLICITLY_CLOSED_AUTOCLOSEABLE, CompilerOptions.IGNORE);
554
	this.runConformTest(
555
		new String[] {
556
			"X.java",
557
			"import java.io.File;\n" +
558
			"import java.io.FileReader;\n" +
559
			"import java.io.IOException;\n" +
560
			"public class X {\n" +
561
			"    void foo(boolean f1, boolean f2) throws IOException {\n" +
562
			"        File file = new File(\"somefile\");\n" +
563
			"        if (f1) {\n" +
564
			"            FileReader fileReader = new FileReader(file); // err: not closed\n" +
565
			"            char[] in = new char[50];\n" +
566
			"            fileReader.read(in);\n" +
567
			"            while (true) {\n" +
568
			"                 FileReader loopReader = new FileReader(file); // don't warn, properly closed\n" +
569
			"                 loopReader.close();" +
570
			"                 break;\n" +
571
			"            }\n" +
572
			"        } else {\n" +
573
			"            FileReader fileReader = new FileReader(file); // warn: not closed on all paths\n" +
574
			"            if (f2)\n" +
575
			"                fileReader.close();\n" +
576
			"        }\n" +
577
			"    }\n" +
578
			"}\n"
579
		},
580
		"",
581
		null,
582
		true,
583
		null,
584
		options,
585
		null);
586
}
587
// Bug 349326 - [1.7] new warning for missing try-with-resources
588
// three AutoCloseables in different blocks of the same method
589
public void test056i2() {
590
	Map options = getCompilerOptions();
591
	options.put(JavaCore.COMPILER_PB_UNCLOSED_CLOSEABLE, CompilerOptions.ERROR);
592
	options.put(JavaCore.COMPILER_PB_POTENTIALLY_UNCLOSED_CLOSEABLE, CompilerOptions.ERROR);
593
	options.put(JavaCore.COMPILER_PB_EXPLICITLY_CLOSED_AUTOCLOSEABLE, CompilerOptions.IGNORE);
594
	this.runNegativeTest(
595
		new String[] {
596
			"X.java",
597
			"import java.io.File;\n" +
598
			"import java.io.FileReader;\n" +
599
			"import java.io.IOException;\n" +
600
			"public class X {\n" +
601
			"    void foo(boolean f1, boolean f2) throws IOException {\n" +
602
			"        File file = new File(\"somefile\");\n" +
603
			"        if (f1) {\n" +
604
			"            FileReader fileReader = new FileReader(file); // properly closed\n" +
605
			"            char[] in = new char[50];\n" +
606
			"            fileReader.read(in);\n" +
607
			"            while (true) {\n" +
608
			"                  fileReader.close();\n" +
609
			"                  FileReader loopReader = new FileReader(file); // don't warn, properly closed\n" +
610
			"                  loopReader.close();\n" +
611
			"                  break;\n" +
612
			"            }\n" +
613
			"        } else {\n" +
614
			"            FileReader fileReader = new FileReader(file); // warn: not closed on all paths\n" +
615
			"            if (f2)\n" +
616
			"                fileReader.close();\n" +
617
			"        }\n" +
618
			"    }\n" +
619
			"    public static void main(String[] args) throws IOException {\n" +
620
			"        new X().foo(true, true);\n" +
621
			"    }\n" +
622
			"}\n"
623
		},
624
		"----------\n" +
625
		"1. ERROR in X.java (at line 18)\n" +
626
		"	FileReader fileReader = new FileReader(file); // warn: not closed on all paths\n" +
627
		"	           ^^^^^^^^^^\n" +
628
		"Potential resource leak: 'fileReader' may not be closed\n" +
629
		"----------\n",
630
		null,
631
		true,
632
		options);
633
}
634
// Bug 349326 - [1.7] new warning for missing try-with-resources
635
// a method uses an AutoCloseable without closing it locally but passing as arg to another method
636
public void test056j() {
637
	Map options = getCompilerOptions();
638
	options.put(CompilerOptions.OPTION_ReportUnclosedCloseable, CompilerOptions.ERROR);
639
	options.put(CompilerOptions.OPTION_ReportPotentiallyUnclosedCloseable, CompilerOptions.ERROR);
640
	this.runNegativeTest(
641
		new String[] {
642
			"X.java",
643
			"import java.io.File;\n" +
644
			"import java.io.FileReader;\n" +
645
			"import java.io.IOException;\n" +
646
			"public class X {\n" +
647
			"    void foo() throws IOException {\n" +
648
			"        File file = new File(\"somefile\");\n" +
649
			"        FileReader fileReader = new FileReader(file);\n" +
650
			"        read(fileReader);\n" +
651
			"    }\n" +
652
			"    void read(FileReader reader) { }\n" +
653
			"    public static void main(String[] args) throws IOException {\n" +
654
			"        new X().foo();\n" +
655
			"    }\n" +
656
			"}\n"
657
		},
658
		"----------\n" +
659
		"1. ERROR in X.java (at line 7)\n" +
660
		"	FileReader fileReader = new FileReader(file);\n" +
661
		"	           ^^^^^^^^^^\n" +
662
		"Potential resource leak: 'fileReader' may not be closed\n" +
663
		"----------\n",
664
		null,
665
		true,
666
		options);
667
}
668
// Bug 349326 - [1.7] new warning for missing try-with-resources
669
// a method uses an AutoCloseable without closing it locally but passing as arg to another method
670
public void test056jconditional() {
671
	Map options = getCompilerOptions();
672
	options.put(CompilerOptions.OPTION_ReportUnclosedCloseable, CompilerOptions.ERROR);
673
	options.put(CompilerOptions.OPTION_ReportPotentiallyUnclosedCloseable, CompilerOptions.ERROR);
674
	this.runNegativeTest(
675
		new String[] {
676
			"X.java",
677
			"import java.io.File;\n" +
678
			"import java.io.FileReader;\n" +
679
			"import java.io.IOException;\n" +
680
			"public class X {\n" +
681
			"    void foo(boolean b) throws IOException {\n" +
682
			"        File file = new File(\"somefile\");\n" +
683
			"        FileReader fileReader = new FileReader(file);\n" +
684
			"        synchronized (b ? this : new X()) {\n" +
685
			"            new ReadDelegator(fileReader);\n" +
686
			"        }\n" +
687
			"    }\n" +
688
			"    class ReadDelegator { ReadDelegator(FileReader reader) { } }\n" +
689
			"    public static void main(String[] args) throws IOException {\n" +
690
			"        new X().foo(true);\n" +
691
			"    }\n" +
692
			"}\n"
693
		},
694
		"----------\n" +
695
		"1. ERROR in X.java (at line 7)\n" +
696
		"	FileReader fileReader = new FileReader(file);\n" +
697
		"	           ^^^^^^^^^^\n" +
698
		"Potential resource leak: 'fileReader' may not be closed\n" +
699
		"----------\n",
700
		null,
701
		true,
702
		options);
703
}
704
// Bug 349326 - [1.7] new warning for missing try-with-resources
705
// many locals, some are AutoCloseable.
706
// Unfortunately analysis cannot respect how exception exits may affect ra3 and rb3,
707
// doing so would create false positives.
708
public void test056k() {
709
	Map options = getCompilerOptions();
710
	options.put(CompilerOptions.OPTION_ReportUnclosedCloseable, CompilerOptions.ERROR);
711
	options.put(CompilerOptions.OPTION_ReportPotentiallyUnclosedCloseable, CompilerOptions.WARNING);
712
	options.put(CompilerOptions.OPTION_ReportExplicitlyClosedAutoCloseable, CompilerOptions.ERROR);
713
	String expectedProblems = this.complianceLevel < ClassFileConstants.JDK1_7 ?
714
				"----------\n" +
715
				"1. ERROR in X.java (at line 15)\n" +
716
				"	ra2 = new FileReader(file);\n" +
717
				"	^^^^^^^^^^^^^^^^^^^^^^^^^^\n" +
718
				"Resource leak: \'ra2\' is never closed\n" +
719
				"----------\n" +
720
				"2. ERROR in X.java (at line 28)\n" +
721
				"	rb2 = new FileReader(file);\n" +
722
				"	^^^^^^^^^^^^^^^^^^^^^^^^^^\n" +
723
				"Resource leak: \'rb2\' is never closed\n" +
724
				"----------\n"
725
			:
726
				"----------\n" +
727
				"1. ERROR in X.java (at line 12)\n" +
728
				"	FileReader ra1 = null, ra2 = null;\n" +
729
				"	           ^^^\n" +
730
				"Resource 'ra1' should be managed by try-with-resource\n" +
731
				"----------\n" +
732
				"2. ERROR in X.java (at line 15)\n" +
733
				"	ra2 = new FileReader(file);\n" +
734
				"	^^^^^^^^^^^^^^^^^^^^^^^^^^\n" +
735
				"Resource leak: 'ra2' is never closed\n" +
736
				"----------\n" +
737
				"3. ERROR in X.java (at line 16)\n" +
738
				"	FileReader ra3 = new FileReader(file);\n" +
739
				"	           ^^^\n" +
740
				"Resource 'ra3' should be managed by try-with-resource\n" +
741
				"----------\n" +
742
				"4. ERROR in X.java (at line 25)\n" +
743
				"	FileReader rb1 = null, rb2 = null;\n" +
744
				"	           ^^^\n" +
745
				"Resource 'rb1' should be managed by try-with-resource\n" +
746
				"----------\n" +
747
				"5. ERROR in X.java (at line 28)\n" +
748
				"	rb2 = new FileReader(file);\n" +
749
				"	^^^^^^^^^^^^^^^^^^^^^^^^^^\n" +
750
				"Resource leak: 'rb2' is never closed\n" +
751
				"----------\n" +
752
				"6. ERROR in X.java (at line 29)\n" +
753
				"	FileReader rb3 = new FileReader(file);\n" +
754
				"	           ^^^\n" +
755
				"Resource 'rb3' should be managed by try-with-resource\n" +
756
				"----------\n";
757
	this.runNegativeTest(
758
		new String[] {
759
			"X.java",
760
			"import java.io.File;\n" +
761
			"import java.io.FileReader;\n" +
762
			"import java.io.IOException;\n" +
763
			"public class X {\n" +
764
			"    void foo() throws IOException {\n" +
765
			"        int i01, i02, i03, i04, i05, i06, i07, i08, i09,\n" +
766
			"            i11, i12, i13, i14, i15, i16, i17, i18, i19,\n" +
767
			"            i21, i22, i23, i24, i25, i26, i27, i28, i29,\n" +
768
			"            i31, i32, i33, i34, i35, i36, i37, i38, i39,\n" +
769
			"            i41, i42, i43, i44, i45, i46, i47, i48, i49;\n" +
770
			"        File file = new File(\"somefile\");\n" +
771
			"        FileReader ra1 = null, ra2 = null;\n" +
772
			"        try {\n" +
773
			"            ra1 = new FileReader(file);\n" +
774
			"            ra2 = new FileReader(file);\n" +
775
			"            FileReader ra3 = new FileReader(file);\n" +
776
			"            char[] in = new char[50];\n" +
777
			"            ra1.read(in);\n" +
778
			"            ra2.read(in);\n" +
779
			"            ra3.close();\n" +
780
			"        } finally {\n" +
781
			"            ra1.close();\n" +
782
			"        }\n" +
783
			"        int i51, i52, i53, i54, i55, i56, i57, i58, i59, i60;\n" + // beyond this point locals are analyzed using extraBits
784
			"        FileReader rb1 = null, rb2 = null;\n" +
785
			"        try {\n" +
786
			"            rb1 = new FileReader(file);\n" +
787
			"            rb2 = new FileReader(file);\n" +
788
			"            FileReader rb3 = new FileReader(file);\n" +
789
			"            char[] in = new char[50];\n" +
790
			"            rb1.read(in);\n" +
791
			"            rb2.read(in);\n" +
792
			"            rb3.close();\n" +
793
			"        } finally {\n" +
794
			"            rb1.close();\n" +
795
			"        }\n" +
796
			"    }\n" +
797
			"    public static void main(String[] args) throws IOException {\n" +
798
			"        new X().foo();\n" +
799
			"    }\n" +
800
			"}\n"
801
		},
802
		expectedProblems,
803
		null,
804
		true,
805
		options);
806
}
807
// Bug 349326 - [1.7] new warning for missing try-with-resources
808
// various non-problems
809
public void test056l() {
810
	Map options = getCompilerOptions();
811
	options.put(CompilerOptions.OPTION_ReportUnclosedCloseable, CompilerOptions.ERROR);
812
	options.put(CompilerOptions.OPTION_ReportPotentiallyUnclosedCloseable, CompilerOptions.ERROR);
813
	options.put(CompilerOptions.OPTION_ReportExplicitlyClosedAutoCloseable, CompilerOptions.ERROR);
814
	String expectedProblems = this.complianceLevel >= ClassFileConstants.JDK1_7 ?
815
				"----------\n" +
816
				"1. ERROR in X.java (at line 8)\n" +
817
				"	FileReader fileReader = getReader();\n" +
818
				"	           ^^^^^^^^^^\n" +
819
				"Resource 'fileReader' should be managed by try-with-resource\n" +
820
				"----------\n" +
821
				"2. ERROR in X.java (at line 11)\n" +
822
				"	FileReader r3 = getReader();\n" +
823
				"	           ^^\n" +
824
				"Resource 'r3' should be managed by try-with-resource\n" +
825
				"----------\n" +
826
				"3. ERROR in X.java (at line 24)\n" +
827
				"	FileReader r2 = new FileReader(new File(\"inexist\")); // only potential problem: ctor X below might close r2\n" +
828
				"	           ^^\n" +
829
				"Potential resource leak: 'r2' may not be closed\n" +
830
				"----------\n" +
831
				"4. ERROR in X.java (at line 25)\n" +
832
				"	new X(r2).foo(new FileReader(new File(\"notthere\"))); // potential problem: foo may/may not close the new FileReader\n" +
833
				"	              ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^\n" +
834
				"Potential resource leak: \'<unassigned Closeable value>\' may not be closed\n" +
835
				"----------\n"
836
			:
837
				"----------\n" +
838
				"1. ERROR in X.java (at line 24)\n" +
839
				"	FileReader r2 = new FileReader(new File(\"inexist\")); // only potential problem: ctor X below might close r2\n" +
840
				"	           ^^\n" +
841
				"Potential resource leak: 'r2' may not be closed\n" +
842
				"----------\n" +
843
				"2. ERROR in X.java (at line 25)\n" +
844
				"	new X(r2).foo(new FileReader(new File(\"notthere\"))); // potential problem: foo may/may not close the new FileReader\n" +
845
				"	              ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^\n" +
846
				"Potential resource leak: \'<unassigned Closeable value>\' may not be closed\n" +
847
				"----------\n";
848
	this.runNegativeTest(
849
		new String[] {
850
			"X.java",
851
			"import java.io.File;\n" +
852
			"import java.io.FileReader;\n" +
853
			"import java.io.IOException;\n" +
854
			"public class X {\n" +
855
			"    X(FileReader r0) {}\n" + // don't complain against argument
856
			"    FileReader getReader() { return null; }\n" +
857
			"    void foo(FileReader r1) throws IOException {\n" +
858
			"        FileReader fileReader = getReader();\n" +
859
			"        if (fileReader == null)\n" +
860
			"            return;\n" + // don't complain, resource is actually null
861
			"        FileReader r3 = getReader();\n" +
862
			"        if (r3 == null)\n" +
863
			"            r3 = new FileReader(new File(\"absent\"));\n" + // don't complain, previous resource is actually null
864
			"        try {\n" +
865
			"            char[] in = new char[50];\n" +
866
			"            fileReader.read(in);\n" +
867
			"            r1.read(in);\n" +
868
			"        } finally {\n" +
869
			"            fileReader.close();\n" +
870
			"            r3.close();\n" +  // the effect of this close() call might be spoiled by exception in fileReader.close() above, but we ignore exception exits in the analysis
871
			"        }\n" +
872
			"    }\n" +
873
			"    public static void main(String[] args) throws IOException {\n" +
874
			"        FileReader r2 = new FileReader(new File(\"inexist\")); // only potential problem: ctor X below might close r2\n" +
875
			"        new X(r2).foo(new FileReader(new File(\"notthere\"))); // potential problem: foo may/may not close the new FileReader\n" +
876
			"    }\n" +
877
			"}\n"
878
		},
879
		expectedProblems,
880
		null,
881
		true,
882
		options);
883
}
884
// Bug 349326 - [1.7] new warning for missing try-with-resources
885
// nested try with early exit
886
public void test056m() {
887
	Map options = getCompilerOptions();
888
	options.put(CompilerOptions.OPTION_ReportUnclosedCloseable, CompilerOptions.ERROR);
889
	options.put(CompilerOptions.OPTION_ReportPotentiallyUnclosedCloseable, CompilerOptions.ERROR);
890
	this.runConformTest(
891
		new String[] {
892
			"X.java",
893
			"import java.io.File;\n" +
894
			"import java.io.FileReader;\n" +
895
			"import java.io.IOException;\n" +
896
			"public class X {\n" +
897
			"    void foo() {\n" +
898
			"        File file = new File(\"somefile\");" +
899
			"        try {\n" +
900
			"            FileReader fileReader = new FileReader(file);\n" +
901
			"            try {\n" +
902
			"                char[] in = new char[50];\n" +
903
			"                if (fileReader.read(in)==0)\n" +
904
			"                    return;\n" +
905
			"            } finally {\n" +
906
			"		         fileReader.close();\n" +
907
			"            }\n" +
908
			"        } catch (IOException e) {\n" +
909
			"            System.out.println(\"caught\");\n" +
910
			"        }\n" +
911
			"    }\n" +
912
			"    public static void main(String[] args) {\n" +
913
			"        new X().foo();\n" +
914
			"    }\n" +
915
			"}\n"
916
		},
917
		"caught", /*output*/
918
		null/*classLibs*/,
919
		true/*shouldFlush*/,
920
		null/*vmargs*/,
921
		options,
922
		null/*requestor*/);
923
}
924
// Bug 349326 - [1.7] new warning for missing try-with-resources
925
// nested try should not interfere with earlier analysis.
926
public void test056n() {
927
	Map options = getCompilerOptions();
928
	options.put(CompilerOptions.OPTION_ReportUnclosedCloseable, CompilerOptions.ERROR);
929
	options.put(CompilerOptions.OPTION_ReportPotentiallyUnclosedCloseable, CompilerOptions.ERROR);
930
	this.runConformTest(
931
		new String[] {
932
			"X.java",
933
			"import java.io.File;\n" +
934
			"import java.io.FileReader;\n" +
935
			"import java.io.IOException;\n" +
936
			"import java.io.FileNotFoundException;\n" +
937
			"public class X {\n" +
938
			"    void foo(File someFile, char[] buf) throws IOException {\n" +
939
			"		FileReader fr1 = new FileReader(someFile);\n" +
940
			"		try {\n" +
941
			"			fr1.read(buf);\n" +
942
			"		} finally {\n" +
943
			"			fr1.close();\n" +
944
			"		}\n" +
945
			"		try {\n" +
946
			"			FileReader fr3 = new FileReader(someFile);\n" +
947
			"			try {\n" +
948
			"			} finally {\n" +
949
			"				fr3.close();\n" +
950
			"			}\n" +
951
			"		} catch (IOException e) {\n" +
952
			"		}\n" +
953
			"	 }\n" +
954
			"    public static void main(String[] args) throws IOException {\n" +
955
			"        try {\n" +
956
			"            new X().foo(new File(\"missing\"), new char[100]);\n" +
957
			"        } catch (FileNotFoundException e) {\n" +
958
			"            System.out.println(\"caught\");\n" +
959
			"        }\n" +
960
			"    }\n" +
961
			"}\n"
962
		},
963
		"caught", /*output*/
964
		null/*classLibs*/,
965
		true/*shouldFlush*/,
966
		null/*vmargs*/,
967
		options,
968
		null/*requestor*/);
969
}
970
// Bug 349326 - [1.7] new warning for missing try-with-resources
971
// if close is guarded by null check this should still be recognized as definitely closed
972
public void test056o() {
973
	Map options = getCompilerOptions();
974
	options.put(CompilerOptions.OPTION_ReportUnclosedCloseable, CompilerOptions.ERROR);
975
	options.put(CompilerOptions.OPTION_ReportPotentiallyUnclosedCloseable, CompilerOptions.ERROR);
976
	this.runConformTest(
977
		new String[] {
978
			"X.java",
979
			"import java.io.File;\n" +
980
			"import java.io.FileReader;\n" +
981
			"import java.io.IOException;\n" +
982
			"import java.io.FileNotFoundException;\n" +
983
			"public class X {\n" +
984
			"    void foo(File someFile, char[] buf) throws IOException {\n" +
985
			"		FileReader fr1 = null;\n" +
986
			"		try {\n" +
987
			"           fr1 = new FileReader(someFile);" +
988
			"			fr1.read(buf);\n" +
989
			"		} finally {\n" +
990
			"			if (fr1 != null)\n" +
991
			"               try {\n" +
992
			"                   fr1.close();\n" +
993
			"               } catch (IOException e) { /*do nothing*/ }\n" +
994
			"		}\n" +
995
			"	 }\n" +
996
			"    public static void main(String[] args) throws IOException {\n" +
997
			"        try {\n" +
998
			"            new X().foo(new File(\"missing\"), new char[100]);\n" +
999
			"        } catch (FileNotFoundException e) {\n" +
1000
			"            System.out.println(\"caught\");\n" +
1001
			"        }\n" +
1002
			"    }\n" +
1003
			"}\n"
1004
		},
1005
		"caught", /*output*/
1006
		null/*classLibs*/,
1007
		true/*shouldFlush*/,
1008
		null/*vmargs*/,
1009
		options,
1010
		null/*requestor*/);
1011
}
1012
// Bug 349326 - [1.7] new warning for missing try-with-resources
1013
// Bug 362332 - Only report potential leak when closeable not created in the local scope
1014
// a method uses an AutoCloseable without ever closing it, type from a type variable
1015
public void test056p() {
1016
	if (this.complianceLevel < ClassFileConstants.JDK1_5) return; // generics used
1017
	Map options = getCompilerOptions();
1018
	options.put(CompilerOptions.OPTION_ReportUnclosedCloseable, CompilerOptions.ERROR);
1019
	options.put(CompilerOptions.OPTION_ReportPotentiallyUnclosedCloseable, CompilerOptions.ERROR);
1020
	this.runNegativeTest(
1021
		new String[] {
1022
			"X.java",
1023
			"import java.io.File;\n" +
1024
			"import java.io.FileReader;\n" +
1025
			"import java.io.Reader;\n" +
1026
			"import java.io.IOException;\n" +
1027
			"public abstract class X <T extends Reader> {\n" +
1028
			"    void foo() throws IOException {\n" +
1029
			"        File file = new File(\"somefile\");\n" +
1030
			"        T fileReader = newReader(file);\n" +
1031
			"        char[] in = new char[50];\n" +
1032
			"        fileReader.read(in);\n" +
1033
			"    }\n" +
1034
			"    abstract T newReader(File file) throws IOException;\n" +
1035
			"    public static void main(String[] args) throws IOException {\n" +
1036
			"        new X<FileReader>() {\n" +
1037
			"            FileReader newReader(File f) throws IOException { return new FileReader(f); }\n" +
1038
			"        }.foo();\n" +
1039
			"    }\n" +
1040
			"}\n"
1041
		},
1042
		"----------\n" +
1043
		"1. ERROR in X.java (at line 8)\n" +
1044
		"	T fileReader = newReader(file);\n" +
1045
		"	  ^^^^^^^^^^\n" +
1046
		"Potential resource leak: \'fileReader\' may not be closed\n" +
1047
		"----------\n",
1048
		null,
1049
		true,
1050
		options);
1051
}
1052
// Bug 349326 - [1.7] new warning for missing try-with-resources
1053
// closed in dead code
1054
public void test056q() {
1055
	Map options = getCompilerOptions();
1056
	options.put(JavaCore.COMPILER_PB_UNCLOSED_CLOSEABLE, CompilerOptions.ERROR);
1057
	options.put(JavaCore.COMPILER_PB_POTENTIALLY_UNCLOSED_CLOSEABLE, CompilerOptions.WARNING);
1058
	options.put(JavaCore.COMPILER_PB_EXPLICITLY_CLOSED_AUTOCLOSEABLE, CompilerOptions.IGNORE);
1059
	this.runNegativeTest(
1060
		new String[] {
1061
			"X.java",
1062
			"import java.io.File;\n" +
1063
			"import java.io.FileReader;\n" +
1064
			"import java.io.IOException;\n" +
1065
			"public class X {\n" +
1066
			"    void foo() throws IOException {\n" +
1067
			"        File file = new File(\"somefile\");\n" +
1068
			"        FileReader fileReader = new FileReader(file);\n" +
1069
			"        char[] in = new char[50];\n" +
1070
			"        fileReader.read(in);\n" +
1071
			"        if (2*2 == 4)\n" +
1072
			"        	return;\n" +
1073
			"        fileReader.close();\n" +
1074
			"    }\n" +
1075
			"    public static void main(String[] args) throws IOException {\n" +
1076
			"        new X().foo();\n" +
1077
			"    }\n" +
1078
			"}\n"
1079
		},
1080
		"----------\n" +
1081
		"1. ERROR in X.java (at line 7)\n" +
1082
		"	FileReader fileReader = new FileReader(file);\n" +
1083
		"	           ^^^^^^^^^^\n" +
1084
		"Resource leak: 'fileReader' is never closed\n" +
1085
		"----------\n" +
1086
		"2. WARNING in X.java (at line 10)\n" +
1087
		"	if (2*2 == 4)\n" +
1088
		"	    ^^^^^^^^\n" +
1089
		"Comparing identical expressions\n" +
1090
		"----------\n" +
1091
		"3. WARNING in X.java (at line 12)\n" +
1092
		"	fileReader.close();\n" +
1093
		"	^^^^^^^^^^^^^^^^^^\n" +
1094
		"Dead code\n" +
1095
		"----------\n",
1096
		null,
1097
		true,
1098
		options);
1099
}
1100
// Bug 349326 - [1.7] new warning for missing try-with-resources
1101
// properly closed, dead code in between
1102
public void test056r() {
1103
	Map options = getCompilerOptions();
1104
	options.put(JavaCore.COMPILER_PB_UNCLOSED_CLOSEABLE, CompilerOptions.ERROR);
1105
	options.put(JavaCore.COMPILER_PB_POTENTIALLY_UNCLOSED_CLOSEABLE, CompilerOptions.WARNING);
1106
	options.put(JavaCore.COMPILER_PB_EXPLICITLY_CLOSED_AUTOCLOSEABLE, CompilerOptions.IGNORE);
1107
	options.put(JavaCore.COMPILER_PB_DEAD_CODE, CompilerOptions.ERROR);
1108
	this.runNegativeTest(
1109
		new String[] {
1110
			"X.java",
1111
			"import java.io.File;\n" +
1112
			"import java.io.FileReader;\n" +
1113
			"import java.io.IOException;\n" +
1114
			"public class X {\n" +
1115
			"    void foo() throws IOException {\n" +
1116
			"        File file = new File(\"somefile\");\n" +
1117
			"        FileReader fr = new FileReader(file);\n" +
1118
			"  		 Object b = null;\n" +
1119
			"        fr.close();\n" +
1120
			"        if (b != null) {\n" +
1121
			"            fr = new FileReader(file);\n" +
1122
			"            return;\n" +
1123
			"        } else {\n" +
1124
			"            System.out.print(42);\n" +
1125
			"        }\n" +
1126
			"        return;     // Should not complain about fr\n" +
1127
			"    }\n" +
1128
			"    public static void main(String[] args) throws IOException {\n" +
1129
			"        new X().foo();\n" +
1130
			"    }\n" +
1131
			"}\n"
1132
		},
1133
		"----------\n" +
1134
		"1. ERROR in X.java (at line 10)\n" +
1135
		"	if (b != null) {\n" +
1136
		"            fr = new FileReader(file);\n" +
1137
		"            return;\n" +
1138
		"        } else {\n" +
1139
		"	               ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^\n" +
1140
		"Dead code\n" +
1141
		"----------\n" +
1142
		"2. WARNING in X.java (at line 13)\n" +
1143
		"	} else {\n" +
1144
		"            System.out.print(42);\n" +
1145
		"        }\n" +
1146
		"	       ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^\n" +
1147
		"Statement unnecessarily nested within else clause. The corresponding then clause does not complete normally\n" +
1148
		"----------\n",
1149
		null,
1150
		true,
1151
		options);
1152
}
1153
// Bug 349326 - [1.7] new warning for missing try-with-resources
1154
// resource inside t-w-r is re-assigned, shouldn't even record an errorLocation
1155
public void test056s() {
1156
	if (this.complianceLevel < ClassFileConstants.JDK1_7) return; // t-w-r used
1157
	Map options = getCompilerOptions();
1158
	options.put(JavaCore.COMPILER_PB_UNCLOSED_CLOSEABLE, CompilerOptions.ERROR);
1159
	options.put(JavaCore.COMPILER_PB_POTENTIALLY_UNCLOSED_CLOSEABLE, CompilerOptions.WARNING);
1160
	options.put(JavaCore.COMPILER_PB_EXPLICITLY_CLOSED_AUTOCLOSEABLE, CompilerOptions.IGNORE);
1161
	this.runNegativeTest(
1162
		new String[] {
1163
			"X.java",
1164
			"import java.io.File;\n" +
1165
			"import java.io.FileReader;\n" +
1166
			"import java.io.IOException;\n" +
1167
			"public class X {\n" +
1168
			"    void foo() throws IOException {\n" +
1169
			"        File file = new File(\"somefile\");\n" +
1170
			"        try (FileReader fileReader = new FileReader(file);) {\n" +
1171
			"            char[] in = new char[50];\n" +
1172
			"            fileReader.read(in);\n" +
1173
			"            fileReader = new FileReader(file);  // debug here\n" +
1174
			"            fileReader.read(in);\n" +
1175
			"        }\n" +
1176
			"    }\n" +
1177
			"    public static void main(String[] args) throws IOException {\n" +
1178
			"        new X().foo();\n" +
1179
			"    }\n" +
1180
			"}\n"
1181
		},
1182
		"----------\n" +
1183
		"1. ERROR in X.java (at line 10)\n" +
1184
		"	fileReader = new FileReader(file);  // debug here\n" +
1185
		"	^^^^^^^^^^\n" +
1186
		"The resource fileReader of a try-with-resources statement cannot be assigned\n" +
1187
		"----------\n",
1188
		null,
1189
		true,
1190
		options);
1191
}
1192
// Bug 349326 - [1.7] new warning for missing try-with-resources
1193
// resource is closed, dead code follows
1194
public void test056t() {
1195
	Map options = getCompilerOptions();
1196
	options.put(JavaCore.COMPILER_PB_UNCLOSED_CLOSEABLE, CompilerOptions.ERROR);
1197
	options.put(JavaCore.COMPILER_PB_POTENTIALLY_UNCLOSED_CLOSEABLE, CompilerOptions.WARNING);
1198
	options.put(JavaCore.COMPILER_PB_DEAD_CODE, CompilerOptions.ERROR);
1199
	this.runNegativeTest(
1200
		new String[] {
1201
			"X.java",
1202
			"import java.io.FileReader;\n" +
1203
			"import java.io.IOException;\n" +
1204
			"public class X {\n" +
1205
			"    void foo31() throws IOException {\n" +
1206
			"        FileReader reader = new FileReader(\"file\"); //warning\n" +
1207
			"        if (reader != null) {\n" +
1208
			"            reader.close();\n" +
1209
			"        } else {\n" +
1210
			"            // nop\n" +
1211
			"        }\n" +
1212
			"    }\n" +
1213
			"    public static void main(String[] args) throws IOException {\n" +
1214
			"        new X().foo31();\n" +
1215
			"    }\n" +
1216
			"}\n"
1217
		},
1218
		"----------\n" +
1219
		"1. ERROR in X.java (at line 8)\n" +
1220
		"	} else {\n" +
1221
		"            // nop\n" +
1222
		"        }\n" +
1223
		"	       ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^\n" +
1224
		"Dead code\n" +
1225
		"----------\n",
1226
		null,
1227
		true,
1228
		options);
1229
}
1230
// Bug 349326 - [1.7] new warning for missing try-with-resources
1231
// resource is reassigned within t-w-r with different resource
1232
// was initially broken due to https://bugs.eclipse.org/358827
1233
public void test056u() {
1234
	if (this.complianceLevel < ClassFileConstants.JDK1_7) return; // t-w-r used
1235
	Map options = getCompilerOptions();
1236
	options.put(JavaCore.COMPILER_PB_UNCLOSED_CLOSEABLE, CompilerOptions.ERROR);
1237
	options.put(JavaCore.COMPILER_PB_POTENTIALLY_UNCLOSED_CLOSEABLE, CompilerOptions.WARNING);
1238
	options.put(JavaCore.COMPILER_PB_DEAD_CODE, CompilerOptions.ERROR);
1239
	this.runNegativeTest(
1240
		new String[] {
1241
			"X.java",
1242
			"import java.io.FileReader;\n" +
1243
			"public class X {\n" +
1244
			"    void foo() throws Exception {\n" +
1245
			"        FileReader reader1 = new FileReader(\"file1\");\n" +
1246
			"        FileReader reader2 = new FileReader(\"file2\");\n" +
1247
			"        reader2 = reader1;// this disconnects reader 2\n" +
1248
			"        try (FileReader reader3 = new FileReader(\"file3\")) {\n" +
1249
			"            int ch;\n" +
1250
			"            while ((ch = reader2.read()) != -1) {\n" +
1251
			"                System.out.println(ch);\n" +
1252
			"                reader1.read();\n" +
1253
			"            }\n" +
1254
			"            reader2 = reader1; // warning 1 regarding original reader1\n" + // this warning was missing
1255
			"            reader2 = reader1; // warning 2 regarding original reader1\n" +
1256
			"        } finally {\n" +
1257
			"            if (reader2 != null) {\n" +
1258
			"                reader2.close();\n" +
1259
			"            } else {\n" +
1260
			"                System.out.println();\n" +
1261
			"            }\n" +
1262
			"        }\n" +
1263
			"    }\n" +
1264
			"}\n"
1265
		},
1266
		"----------\n" +
1267
		"1. ERROR in X.java (at line 5)\n" +
1268
		"	FileReader reader2 = new FileReader(\"file2\");\n" +
1269
		"	           ^^^^^^^\n" +
1270
		"Resource leak: 'reader2' is never closed\n" +
1271
		"----------\n" +
1272
		"2. ERROR in X.java (at line 13)\n" +
1273
		"	reader2 = reader1; // warning 1 regarding original reader1\n" +
1274
		"	^^^^^^^^^^^^^^^^^\n" +
1275
		"Resource leak: 'reader1' is not closed at this location\n" +
1276
		"----------\n" +
1277
		"3. ERROR in X.java (at line 14)\n" +
1278
		"	reader2 = reader1; // warning 2 regarding original reader1\n" +
1279
		"	^^^^^^^^^^^^^^^^^\n" +
1280
		"Resource leak: 'reader1' is not closed at this location\n" +
1281
		"----------\n",
1282
		null,
1283
		true,
1284
		options);
1285
}
1286
// Bug 349326 - [1.7] new warning for missing try-with-resources
1287
// scope-related pbs reported in https://bugs.eclipse.org/349326#c70 and https://bugs.eclipse.org/349326#c82
1288
public void test056v() {
1289
	Map options = getCompilerOptions();
1290
	options.put(JavaCore.COMPILER_PB_UNCLOSED_CLOSEABLE, CompilerOptions.ERROR);
1291
	options.put(JavaCore.COMPILER_PB_POTENTIALLY_UNCLOSED_CLOSEABLE, CompilerOptions.WARNING);
1292
	options.put(JavaCore.COMPILER_PB_EXPLICITLY_CLOSED_AUTOCLOSEABLE, CompilerOptions.WARNING);
1293
	options.put(JavaCore.COMPILER_PB_DEAD_CODE, CompilerOptions.ERROR);
1294
	String expectedProblems = this.complianceLevel >= ClassFileConstants.JDK1_7 ?
1295
				"----------\n" +
1296
				"1. ERROR in X.java (at line 4)\n" +
1297
				"	FileReader reader = new FileReader(\"file\");\n" +
1298
				"	           ^^^^^^\n" +
1299
				"Resource leak: 'reader' is never closed\n" +
1300
				"----------\n" +
1301
				"2. WARNING in X.java (at line 19)\n" +
1302
				"	FileReader reader111 = new FileReader(\"file2\");\n" +
1303
				"	           ^^^^^^^^^\n" +
1304
				"Resource 'reader111' should be managed by try-with-resource\n" +
1305
				"----------\n" +
1306
				"3. ERROR in X.java (at line 42)\n" +
1307
				"	return;\n" +
1308
				"	^^^^^^^\n" +
1309
				"Resource leak: 'reader2' is not closed at this location\n" +
1310
				"----------\n"
1311
			:
1312
				"----------\n" +
1313
				"1. ERROR in X.java (at line 4)\n" +
1314
				"	FileReader reader = new FileReader(\"file\");\n" +
1315
				"	           ^^^^^^\n" +
1316
				"Resource leak: 'reader' is never closed\n" +
1317
				"----------\n" +
1318
				"2. ERROR in X.java (at line 42)\n" +
1319
				"	return;\n" +
1320
				"	^^^^^^^\n" +
1321
				"Resource leak: 'reader2' is not closed at this location\n" +
1322
				"----------\n";
1323
	this.runNegativeTest(
1324
		new String[] {
1325
			"X.java",
1326
			"import java.io.FileReader;\n" +
1327
			"public class X {\n" +
1328
			"    boolean foo1() throws Exception {\n" +
1329
			"        FileReader reader = new FileReader(\"file\");\n" +
1330
			"        try {\n" +
1331
			"            int ch;\n" +
1332
			"            while ((ch = reader.read()) != -1) {\n" +
1333
			"                System.out.println(ch);\n" +
1334
			"                reader.read();\n" +
1335
			"            }\n" +
1336
			"            if (ch > 10) {\n" +
1337
			"                return true;\n" +
1338
			"            }\n" +
1339
			"            return false;\n" + // return while resource from enclosing scope remains unclosed
1340
			"        } finally {\n" +
1341
			"        }\n" +
1342
			"    }\n" +
1343
			"    void foo111() throws Exception {\n" +
1344
			"        FileReader reader111 = new FileReader(\"file2\");\n" +
1345
			"        try {\n" +
1346
			"            int ch;\n" +
1347
			"            while ((ch = reader111.read()) != -1) {\n" +
1348
			"                System.out.println(ch);\n" +
1349
			"                reader111.read();\n" +
1350
			"            }\n" +
1351
			"            return;\n" + // this shouldn't spoil the warning "should be managed with t-w-r"
1352
			"        } finally {\n" +
1353
			"            if (reader111 != null) {\n" +
1354
			"                reader111.close();\n" +
1355
			"            }\n" +
1356
			"        }\n" +
1357
			"    }\n" +
1358
			"    void foo2() throws Exception {\n" +
1359
			"        FileReader reader2 = new FileReader(\"file\");\n" +
1360
			"        try {\n" +
1361
			"            int ch;\n" +
1362
			"            while ((ch = reader2.read()) != -1) {\n" +
1363
			"                System.out.println(ch);\n" +
1364
			"                reader2.read();\n" +
1365
			"            }\n" +
1366
			"            if (ch > 10) {\n" +
1367
			"                return;\n" + // potential leak
1368
			"            }\n" +
1369
			"        } finally {\n" +
1370
			"        }\n" +
1371
			"        reader2.close();\n" + // due to this close we don't say "never closed"
1372
			"    }\n" +
1373
			"}\n"
1374
		},
1375
		expectedProblems,
1376
		null,
1377
		true,
1378
		options);
1379
}
1380
// Bug 349326 - [1.7] new warning for missing try-with-resources
1381
// end of method is dead end, but before we have both a close() and an early return
1382
public void test056w() {
1383
	Map options = getCompilerOptions();
1384
	options.put(JavaCore.COMPILER_PB_UNCLOSED_CLOSEABLE, CompilerOptions.ERROR);
1385
	options.put(JavaCore.COMPILER_PB_POTENTIALLY_UNCLOSED_CLOSEABLE, CompilerOptions.WARNING);
1386
	options.put(JavaCore.COMPILER_PB_DEAD_CODE, CompilerOptions.ERROR);
1387
	this.runNegativeTest(
1388
		new String[] {
1389
			"X.java",
1390
			"import java.io.FileReader;\n" +
1391
			"public class X {\n" +
1392
			"    boolean foo1() throws Exception {\n" +
1393
			"        FileReader reader = new FileReader(\"file\");\n" +
1394
			"        try {\n" +
1395
			"            int ch;\n" +
1396
			"            while ((ch = reader.read()) != -1) {\n" +
1397
			"                System.out.println(ch);\n" +
1398
			"                reader.read();\n" +
1399
			"            }\n" +
1400
			"            if (ch > 10) {\n" +
1401
			"				 reader.close();\n" +
1402
			"                return true;\n" +
1403
			"            }\n" +
1404
			"            return false;\n" +
1405
			"        } finally {\n" +
1406
			"        }\n" +
1407
			"    }\n" +
1408
			"}\n"
1409
		},
1410
		"----------\n" +
1411
		"1. ERROR in X.java (at line 15)\n" +
1412
		"	return false;\n" +
1413
		"	^^^^^^^^^^^^^\n" +
1414
		"Resource leak: 'reader' is not closed at this location\n" +
1415
		"----------\n",
1416
		null,
1417
		true,
1418
		options);
1419
}
1420
// Bug 349326 - [1.7] new warning for missing try-with-resources
1421
// different early exits, if no close seen report as definitely unclosed
1422
public void test056x() {
1423
	Map options = getCompilerOptions();
1424
	options.put(JavaCore.COMPILER_PB_UNCLOSED_CLOSEABLE, CompilerOptions.ERROR);
1425
	options.put(JavaCore.COMPILER_PB_POTENTIALLY_UNCLOSED_CLOSEABLE, CompilerOptions.WARNING);
1426
	options.put(JavaCore.COMPILER_PB_DEAD_CODE, CompilerOptions.ERROR);
1427
	this.runNegativeTest(
1428
		new String[] {
1429
			"X.java",
1430
			"import java.io.FileReader;\n" +
1431
			"public class X {\n" +
1432
			"    void foo31(boolean b) throws Exception {\n" +
1433
			"        FileReader reader = new FileReader(\"file\");\n" +
1434
			"        if (b) {\n" +
1435
			"            reader.close();\n" +
1436
			"        } else {\n" +
1437
			"            return; // warning\n" +
1438
			"        }\n" +
1439
			"    }\n" +
1440
			"    void foo32(boolean b) throws Exception {\n" +
1441
			"        FileReader reader = new FileReader(\"file\"); // warn here\n" +
1442
			"        return;\n" +
1443
			"    }\n" +
1444
			"}\n"
1445
		},
1446
		"----------\n" +
1447
		"1. ERROR in X.java (at line 8)\n" +
1448
		"	return; // warning\n" +
1449
		"	^^^^^^^\n" +
1450
		"Resource leak: 'reader' is not closed at this location\n" +
1451
		"----------\n" +
1452
		"2. ERROR in X.java (at line 12)\n" +
1453
		"	FileReader reader = new FileReader(\"file\"); // warn here\n" +
1454
		"	           ^^^^^^\n" +
1455
		"Resource leak: 'reader' is never closed\n" +
1456
		"----------\n",
1457
		null,
1458
		true,
1459
		options);
1460
}
1461
// Bug 349326 - [1.7] new warning for missing try-with-resources
1462
// nested method passes the resource to outside code
1463
public void test056y() {
1464
	Map options = getCompilerOptions();
1465
	options.put(JavaCore.COMPILER_PB_UNCLOSED_CLOSEABLE, CompilerOptions.ERROR);
1466
	options.put(JavaCore.COMPILER_PB_POTENTIALLY_UNCLOSED_CLOSEABLE, CompilerOptions.WARNING);
1467
	options.put(JavaCore.COMPILER_PB_DEAD_CODE, CompilerOptions.ERROR);
1468
	this.runNegativeTest(
1469
		new String[] {
1470
			"X.java",
1471
			"import java.io.FileReader;\n" +
1472
			"public class X {\n" +
1473
			"    void foo31(boolean b) throws Exception {\n" +
1474
			"        final FileReader reader31 = new FileReader(\"file\");\n" +
1475
			"        new Runnable() {\n" +
1476
			"            public void run() {\n" +
1477
			"                foo18(reader31);\n" +
1478
			"            }\n" +
1479
			"        }.run();\n" +
1480
			"    }\n" +
1481
			"    void foo18(FileReader r18) {\n" +
1482
			"        // could theoretically close r18;\n" +
1483
			"    }\n" +
1484
			"    abstract class ResourceProvider {\n" +
1485
			"        abstract FileReader provide();" +
1486
			"    }\n" +
1487
			"    ResourceProvider provider;" +
1488
			"    void foo23() throws Exception {\n" +
1489
			"        final FileReader reader23 = new FileReader(\"file\");\n" +
1490
			"        provider = new ResourceProvider() {\n" +
1491
			"            public FileReader provide() {\n" +
1492
			"                return reader23;\n" + // responsibility now lies at the caller of this method
1493
			"            }\n" +
1494
			"        };\n" +
1495
			"    }\n" +
1496
			"}\n"
1497
		},
1498
		"----------\n" +
1499
		"1. WARNING in X.java (at line 4)\n" +
1500
		"	final FileReader reader31 = new FileReader(\"file\");\n" +
1501
		"	                 ^^^^^^^^\n" +
1502
		"Potential resource leak: 'reader31' may not be closed\n" +
1503
		"----------\n",
1504
		null,
1505
		true,
1506
		options);
1507
}
1508
// Bug 349326 - [1.7] new warning for missing try-with-resources
1509
// resource assigned to second local and is (potentially) closed on the latter
1510
public void test056z() {
1511
	Map options = getCompilerOptions();
1512
	options.put(JavaCore.COMPILER_PB_UNCLOSED_CLOSEABLE, CompilerOptions.ERROR);
1513
	options.put(JavaCore.COMPILER_PB_POTENTIALLY_UNCLOSED_CLOSEABLE, CompilerOptions.ERROR);
1514
	options.put(JavaCore.COMPILER_PB_DEAD_CODE, CompilerOptions.ERROR);
1515
	this.runNegativeTest(
1516
		new String[] {
1517
			"X.java",
1518
			"import java.io.FileReader;\n" +
1519
			"public class X {\n" +
1520
			"    void foo17() throws Exception {\n" +
1521
			"        FileReader reader17 = new FileReader(\"file\");\n" +
1522
			"        final FileReader readerCopy = reader17;\n" +
1523
			"        readerCopy.close();\n" +
1524
			"    }\n" +
1525
			"    void foo17a() throws Exception {\n" +
1526
			"        FileReader reader17a = new FileReader(\"file\");\n" +
1527
			"        FileReader readerCopya;" +
1528
			"		 readerCopya = reader17a;\n" +
1529
			"        bar(readerCopya);\n" + // potentially closes
1530
			"    }\n" +
1531
			"    void bar(FileReader r) {}\n" +
1532
			"}\n"
1533
		},
1534
		"----------\n" +
1535
		"1. ERROR in X.java (at line 9)\n" +
1536
		"	FileReader reader17a = new FileReader(\"file\");\n" +
1537
		"	           ^^^^^^^^^\n" +
1538
		"Potential resource leak: 'reader17a' may not be closed\n" +
1539
		"----------\n",
1540
		null,
1541
		true,
1542
		options);
1543
}
1544
// Bug 349326 - [1.7] new warning for missing try-with-resources
1545
// multiple early exists from nested scopes (always closed)
1546
public void test056zz() {
1547
	Map options = getCompilerOptions();
1548
	options.put(JavaCore.COMPILER_PB_UNCLOSED_CLOSEABLE, CompilerOptions.ERROR);
1549
	options.put(JavaCore.COMPILER_PB_POTENTIALLY_UNCLOSED_CLOSEABLE, CompilerOptions.ERROR);
1550
	options.put(JavaCore.COMPILER_PB_EXPLICITLY_CLOSED_AUTOCLOSEABLE, CompilerOptions.ERROR);
1551
	options.put(JavaCore.COMPILER_PB_DEAD_CODE, CompilerOptions.ERROR);
1552
	runTestsExpectingErrorsOnlyIn17(
1553
		new String[] {
1554
			"X.java",
1555
			"import java.io.FileReader;\n" +
1556
			"public class X {\n" +
1557
			"    void foo16() throws Exception {\n" +
1558
			"        FileReader reader16 = new FileReader(\"file\");\n" +
1559
			"        try {\n" +
1560
			"            reader16.close();\n " +
1561
			"            return;\n" +
1562
			"        } catch (RuntimeException re) {\n" +
1563
			"            return;\n" +
1564
			"        } catch (Error e) {\n" +
1565
			"            return;\n" +
1566
			"        } finally {\n" +
1567
			"            reader16.close();\n " +
1568
			"        }\n" +
1569
			"    }\n" +
1570
			"}\n"
1571
		},
1572
		"----------\n" +
1573
		"1. ERROR in X.java (at line 4)\n" +
1574
		"	FileReader reader16 = new FileReader(\"file\");\n" +
1575
		"	           ^^^^^^^^\n" +
1576
		"Resource 'reader16' should be managed by try-with-resource\n" +
1577
		"----------\n",
1578
		options);
1579
}
1580
// Bug 349326 - [1.7] new warning for missing try-with-resources
1581
// multiple early exists from nested scopes (never closed)
1582
public void test056zzz() {
1583
	Map options = getCompilerOptions();
1584
	options.put(JavaCore.COMPILER_PB_UNCLOSED_CLOSEABLE, CompilerOptions.ERROR);
1585
	options.put(JavaCore.COMPILER_PB_POTENTIALLY_UNCLOSED_CLOSEABLE, CompilerOptions.ERROR);
1586
	options.put(JavaCore.COMPILER_PB_EXPLICITLY_CLOSED_AUTOCLOSEABLE, CompilerOptions.ERROR);
1587
	options.put(JavaCore.COMPILER_PB_DEAD_CODE, CompilerOptions.ERROR);
1588
	this.runNegativeTest(
1589
		new String[] {
1590
			"X.java",
1591
			"import java.io.FileReader;\n" +
1592
			"public class X {\n" +
1593
			"    void foo16() throws Exception {\n" +
1594
			"        FileReader reader16 = new FileReader(\"file\");\n" +
1595
			"        try {\n" +
1596
			"            return;\n" +
1597
			"        } catch (RuntimeException re) {\n" +
1598
			"            return;\n" +
1599
			"        } catch (Error e) {\n" +
1600
			"            return;\n" +
1601
			"        } finally {\n" +
1602
			"            System.out.println();\n " +
1603
			"        }\n" +
1604
			"    }\n" +
1605
			"}\n"
1606
		},
1607
		"----------\n" +
1608
		"1. ERROR in X.java (at line 4)\n" +
1609
		"	FileReader reader16 = new FileReader(\"file\");\n" +
1610
		"	           ^^^^^^^^\n" +
1611
		"Resource leak: 'reader16' is never closed\n" +
1612
		"----------\n",
1613
		null,
1614
		true,
1615
		options);
1616
}
1617
// Bug 359334 - Analysis for resource leak warnings does not consider exceptions as method exit points
1618
// explicit throw is a true method exit here
1619
public void test056throw1() {
1620
	Map options = getCompilerOptions();
1621
	options.put(JavaCore.COMPILER_PB_UNCLOSED_CLOSEABLE, CompilerOptions.ERROR);
1622
	options.put(JavaCore.COMPILER_PB_POTENTIALLY_UNCLOSED_CLOSEABLE, CompilerOptions.ERROR);
1623
	options.put(JavaCore.COMPILER_PB_EXPLICITLY_CLOSED_AUTOCLOSEABLE, CompilerOptions.ERROR);
1624
	options.put(JavaCore.COMPILER_PB_DEAD_CODE, CompilerOptions.ERROR);
1625
	this.runNegativeTest(
1626
		new String[] {
1627
			"X.java",
1628
			"import java.io.FileReader;\n" +
1629
			"public class X {\n" +
1630
			"    void foo2(boolean a, boolean b, boolean c) throws Exception {\n" +
1631
			"        FileReader reader = new FileReader(\"file\");\n" +
1632
			"        if(a)\n" +
1633
			"            throw new Exception();    //warning 1\n" +
1634
			"        else if (b)\n" +
1635
			"            reader.close();\n" +
1636
			"        else if(c)\n" +
1637
			"            throw new Exception();    //warning 2\n" +
1638
			"        reader.close();\n" +
1639
			"    }\n" +
1640
			"}\n"
1641
		},
1642
		"----------\n" +
1643
		"1. ERROR in X.java (at line 6)\n" +
1644
		"	throw new Exception();    //warning 1\n" +
1645
		"	^^^^^^^^^^^^^^^^^^^^^^\n" +
1646
		"Resource leak: 'reader' is not closed at this location\n" +
1647
		"----------\n" +
1648
		"2. ERROR in X.java (at line 10)\n" +
1649
		"	throw new Exception();    //warning 2\n" +
1650
		"	^^^^^^^^^^^^^^^^^^^^^^\n" +
1651
		"Resource leak: 'reader' is not closed at this location\n" +
1652
		"----------\n",
1653
		null,
1654
		true,
1655
		options);
1656
}
1657
// Bug 359334 - Analysis for resource leak warnings does not consider exceptions as method exit points
1658
// close() within finally provides protection for throw
1659
public void test056throw2() {
1660
	Map options = getCompilerOptions();
1661
	options.put(JavaCore.COMPILER_PB_UNCLOSED_CLOSEABLE, CompilerOptions.ERROR);
1662
	options.put(JavaCore.COMPILER_PB_POTENTIALLY_UNCLOSED_CLOSEABLE, CompilerOptions.ERROR);
1663
	options.put(JavaCore.COMPILER_PB_EXPLICITLY_CLOSED_AUTOCLOSEABLE, CompilerOptions.ERROR);
1664
	options.put(JavaCore.COMPILER_PB_DEAD_CODE, CompilerOptions.ERROR);
1665
	runTestsExpectingErrorsOnlyIn17(
1666
		new String[] {
1667
			"X.java",
1668
			"import java.io.FileReader;\n" +
1669
					"public class X {\n" +
1670
					"    void foo1() throws Exception {\n" +
1671
					"        FileReader reader = new FileReader(\"file\"); // propose t-w-r\n" +
1672
					"        try {\n" +
1673
					"            reader.read();\n" +
1674
					"            return;\n" +
1675
					"        } catch (Exception e) {\n" +
1676
					"            throw new Exception();\n" +
1677
					"        } finally {\n" +
1678
					"            reader.close();\n" +
1679
					"        }\n" +
1680
					"    }\n" +
1681
					"\n" +
1682
					"    void foo2() throws Exception {\n" +
1683
					"        FileReader reader = new FileReader(\"file\"); // propose t-w-r\n" +
1684
					"        try {\n" +
1685
					"            reader.read();\n" +
1686
					"            throw new Exception(); // should not warn here\n" +
1687
					"        } catch (Exception e) {\n" +
1688
					"            throw new Exception();\n" +
1689
					"        } finally {\n" +
1690
					"            reader.close();\n" +
1691
					"        }\n" +
1692
					"    }\n" +
1693
					"\n" +
1694
					"    void foo3() throws Exception {\n" +
1695
					"        FileReader reader = new FileReader(\"file\"); // propose t-w-r\n" +
1696
					"        try {\n" +
1697
					"            reader.read();\n" +
1698
					"            throw new Exception();\n" +
1699
					"        } finally {\n" +
1700
					"            reader.close();\n" +
1701
					"        }\n" +
1702
					"    }\n" +
1703
					"}\n"
1704
			},
1705
			"----------\n" +
1706
			"1. ERROR in X.java (at line 4)\n" +
1707
			"	FileReader reader = new FileReader(\"file\"); // propose t-w-r\n" +
1708
			"	           ^^^^^^\n" +
1709
			"Resource 'reader' should be managed by try-with-resource\n" +
1710
			"----------\n" +
1711
			"2. ERROR in X.java (at line 16)\n" +
1712
			"	FileReader reader = new FileReader(\"file\"); // propose t-w-r\n" +
1713
			"	           ^^^^^^\n" +
1714
			"Resource 'reader' should be managed by try-with-resource\n" +
1715
			"----------\n" +
1716
			"3. ERROR in X.java (at line 28)\n" +
1717
			"	FileReader reader = new FileReader(\"file\"); // propose t-w-r\n" +
1718
			"	           ^^^^^^\n" +
1719
			"Resource 'reader' should be managed by try-with-resource\n" +
1720
			"----------\n",
1721
			options);
1722
}
1723
// Bug 359334 - Analysis for resource leak warnings does not consider exceptions as method exit points
1724
// close() nested within finally provides protection for throw
1725
public void test056throw3() {
1726
	Map options = getCompilerOptions();
1727
	options.put(JavaCore.COMPILER_PB_UNCLOSED_CLOSEABLE, CompilerOptions.ERROR);
1728
	options.put(JavaCore.COMPILER_PB_POTENTIALLY_UNCLOSED_CLOSEABLE, CompilerOptions.ERROR);
1729
	options.put(JavaCore.COMPILER_PB_EXPLICITLY_CLOSED_AUTOCLOSEABLE, CompilerOptions.ERROR);
1730
	options.put(JavaCore.COMPILER_PB_DEAD_CODE, CompilerOptions.ERROR);
1731
	runTestsExpectingErrorsOnlyIn17(
1732
		new String[] {
1733
			"X.java",
1734
			"import java.io.FileReader;\n" +
1735
			"public class X {\n" +
1736
			"    void foo2x() throws Exception {\n" +
1737
			"        FileReader reader = new FileReader(\"file\"); // propose t-w-r\n" +
1738
			"        try {\n" +
1739
			"            reader.read();\n" +
1740
			"            throw new Exception(); // should not warn here\n" +
1741
			"        } catch (Exception e) {\n" +
1742
			"            throw new Exception();\n" +
1743
			"        } finally {\n" +
1744
			"            if (reader != null)\n" +
1745
			"                 try {\n" +
1746
			"                     reader.close();\n" +
1747
			"                 } catch (java.io.IOException io) {}\n" +
1748
			"        }\n" +
1749
			"    }\n" +
1750
			"}\n"
1751
		},
1752
		"----------\n" +
1753
		"1. ERROR in X.java (at line 4)\n" +
1754
		"	FileReader reader = new FileReader(\"file\"); // propose t-w-r\n" +
1755
		"	           ^^^^^^\n" +
1756
		"Resource 'reader' should be managed by try-with-resource\n" +
1757
		"----------\n",
1758
		options);
1759
}
1760
// Bug 359334 - Analysis for resource leak warnings does not consider exceptions as method exit points
1761
// additional boolean should shed doubt on whether we reach the close() call
1762
public void test056throw4() {
1763
	Map options = getCompilerOptions();
1764
	options.put(JavaCore.COMPILER_PB_UNCLOSED_CLOSEABLE, CompilerOptions.ERROR);
1765
	options.put(JavaCore.COMPILER_PB_POTENTIALLY_UNCLOSED_CLOSEABLE, CompilerOptions.ERROR);
1766
	options.put(JavaCore.COMPILER_PB_EXPLICITLY_CLOSED_AUTOCLOSEABLE, CompilerOptions.ERROR);
1767
	options.put(JavaCore.COMPILER_PB_DEAD_CODE, CompilerOptions.ERROR);
1768
	this.runNegativeTest(
1769
		new String[] {
1770
			"X.java",
1771
			"import java.io.FileReader;\n" +
1772
			"public class X {\n" +
1773
			"    void foo2x(boolean b) throws Exception {\n" +
1774
			"        FileReader reader = new FileReader(\"file\");\n" +
1775
			"        try {\n" +
1776
			"            reader.read();\n" +
1777
			"            throw new Exception(); // should warn here\n" +
1778
			"        } catch (Exception e) {\n" +
1779
			"            throw new Exception(); // should warn here\n" +
1780
			"        } finally {\n" +
1781
			"            if (reader != null && b)\n" + // this condition is too strong to protect reader
1782
			"                 try {\n" +
1783
			"                     reader.close();\n" +
1784
			"                 } catch (java.io.IOException io) {}\n" +
1785
			"        }\n" +
1786
			"    }\n" +
1787
			"}\n"
1788
		},
1789
		"----------\n" +
1790
		"1. ERROR in X.java (at line 7)\n" +
1791
		"	throw new Exception(); // should warn here\n" +
1792
		"	^^^^^^^^^^^^^^^^^^^^^^\n" +
1793
		"Potential resource leak: 'reader' may not be closed at this location\n" +
1794
		"----------\n" +
1795
		"2. ERROR in X.java (at line 9)\n" +
1796
		"	throw new Exception(); // should warn here\n" +
1797
		"	^^^^^^^^^^^^^^^^^^^^^^\n" +
1798
		"Potential resource leak: 'reader' may not be closed at this location\n" +
1799
		"----------\n",
1800
		null,
1801
		true,
1802
		options);
1803
}
1804
// Bug 359334 - Analysis for resource leak warnings does not consider exceptions as method exit points
1805
// similar to test056throw3() but indirectly calling close(), so doubts remain.
1806
public void test056throw5() {
1807
	Map options = getCompilerOptions();
1808
	options.put(JavaCore.COMPILER_PB_UNCLOSED_CLOSEABLE, CompilerOptions.ERROR);
1809
	options.put(JavaCore.COMPILER_PB_POTENTIALLY_UNCLOSED_CLOSEABLE, CompilerOptions.ERROR);
1810
	options.put(JavaCore.COMPILER_PB_EXPLICITLY_CLOSED_AUTOCLOSEABLE, CompilerOptions.ERROR);
1811
	options.put(JavaCore.COMPILER_PB_DEAD_CODE, CompilerOptions.ERROR);
1812
	this.runNegativeTest(
1813
		new String[] {
1814
			"X.java",
1815
			"import java.io.FileReader;\n" +
1816
			"public class X {\n" +
1817
			"    void foo2x() throws Exception {\n" +
1818
			"        FileReader reader = new FileReader(\"file\");\n" +
1819
			"        try {\n" +
1820
			"            reader.read();\n" +
1821
			"            throw new Exception(); // should warn 'may not' here\n" +
1822
			"        } catch (Exception e) {\n" +
1823
			"            throw new Exception(); // should warn 'may not' here\n" +
1824
			"        } finally {\n" +
1825
			"            doClose(reader);\n" +
1826
			"        }\n" +
1827
			"    }\n" +
1828
			"    void doClose(FileReader r) { try { r.close(); } catch (java.io.IOException ex) {}}\n" +
1829
			"}\n"
1830
		},
1831
		"----------\n" +
1832
		"1. ERROR in X.java (at line 7)\n" +
1833
		"	throw new Exception(); // should warn \'may not\' here\n" +
1834
		"	^^^^^^^^^^^^^^^^^^^^^^\n" +
1835
		"Potential resource leak: 'reader' may not be closed at this location\n" +
1836
		"----------\n" +
1837
		"2. ERROR in X.java (at line 9)\n" +
1838
		"	throw new Exception(); // should warn \'may not\' here\n" +
1839
		"	^^^^^^^^^^^^^^^^^^^^^^\n" +
1840
		"Potential resource leak: 'reader' may not be closed at this location\n" +
1841
		"----------\n",
1842
		null,
1843
		true,
1844
		options);
1845
}
1846
// Bug 358903 - Filter practically unimportant resource leak warnings
1847
// Bug 360908 - Avoid resource leak warning when the underlying/chained resource is closed explicitly
1848
// a resource wrapper is not closed but the underlying resource is
1849
public void test061a() {
1850
	Map options = getCompilerOptions();
1851
	options.put(CompilerOptions.OPTION_ReportUnclosedCloseable, CompilerOptions.ERROR);
1852
	options.put(CompilerOptions.OPTION_ReportPotentiallyUnclosedCloseable, CompilerOptions.ERROR);
1853
	this.runConformTest(
1854
		new String[] {
1855
			"X.java",
1856
			"import java.io.File;\n" +
1857
			"import java.io.BufferedInputStream;\n" +
1858
			"import java.io.FileInputStream;\n" +
1859
			"import java.io.IOException;\n" +
1860
			"public class X {\n" +
1861
			"    void foo() throws IOException {\n" +
1862
			"        File file = new File(\"somefile\");\n" +
1863
			"        FileInputStream fileStream  = new FileInputStream(file);\n" +
1864
			"        BufferedInputStream bis = new BufferedInputStream(fileStream);\n" +
1865
			"        BufferedInputStream doubleWrap = new BufferedInputStream(bis);\n" +
1866
			"        System.out.println(bis.available());\n" +
1867
			"        fileStream.close();\n" +
1868
			"    }\n" +
1869
			"    void inline() throws IOException {\n" +
1870
			"        File file = new File(\"somefile\");\n" +
1871
			"        FileInputStream fileStream;\n" +
1872
			"        BufferedInputStream bis = new BufferedInputStream(fileStream = new FileInputStream(file));\n" +
1873
			"        System.out.println(bis.available());\n" +
1874
			"        fileStream.close();\n" +
1875
			"    }\n" +
1876
			"    public static void main(String[] args) throws IOException {\n" +
1877
			"        try {\n" +
1878
			"            new X().foo();\n" +
1879
			"        } catch (IOException ex) {" +
1880
			"            System.out.println(\"Got IO Exception\");\n" +
1881
			"        }\n" +
1882
			"    }\n" +
1883
			"}\n"
1884
		},
1885
		"Got IO Exception",
1886
		null,
1887
		true,
1888
		null,
1889
		options,
1890
		null);
1891
}
1892
// Bug 358903 - Filter practically unimportant resource leak warnings
1893
// a closeable without OS resource is not closed
1894
public void test061b() {
1895
	Map options = getCompilerOptions();
1896
	options.put(CompilerOptions.OPTION_ReportUnclosedCloseable, CompilerOptions.ERROR);
1897
	options.put(CompilerOptions.OPTION_ReportPotentiallyUnclosedCloseable, CompilerOptions.ERROR);
1898
	this.runConformTest(
1899
		new String[] {
1900
			"X.java",
1901
			"import java.io.StringReader;\n" +
1902
			"import java.io.IOException;\n" +
1903
			"public class X {\n" +
1904
			"    void foo() throws IOException {\n" +
1905
			"        StringReader string  = new StringReader(\"content\");\n" +
1906
			"        System.out.println(string.read());\n" +
1907
			"    }\n" +
1908
			"    public static void main(String[] args) throws IOException {\n" +
1909
			"        new X().foo();\n" +
1910
			"    }\n" +
1911
			"}\n"
1912
		},
1913
		"99", // character 'c'
1914
		null,
1915
		true,
1916
		null,
1917
		options,
1918
		null);
1919
}
1920
// Bug 358903 - Filter practically unimportant resource leak warnings
1921
// a resource wrapper is not closed but the underlying closeable is resource-free
1922
public void test061c() {
1923
	Map options = getCompilerOptions();
1924
	options.put(CompilerOptions.OPTION_ReportUnclosedCloseable, CompilerOptions.ERROR);
1925
	options.put(CompilerOptions.OPTION_ReportPotentiallyUnclosedCloseable, CompilerOptions.ERROR);
1926
	this.runConformTest(
1927
		new String[] {
1928
			"X.java",
1929
			"import java.io.BufferedReader;\n" +
1930
			"import java.io.StringReader;\n" +
1931
			"import java.io.IOException;\n" +
1932
			"public class X {\n" +
1933
			"    void foo() throws IOException {\n" +
1934
			"        StringReader input = new StringReader(\"content\");\n" +
1935
			"        BufferedReader br = new BufferedReader(input);\n" +
1936
			"        BufferedReader doubleWrap = new BufferedReader(br);\n" +
1937
			"        System.out.println(br.read());\n" +
1938
			"    }\n" +
1939
			"    void inline() throws IOException {\n" +
1940
			"        BufferedReader br = new BufferedReader(new StringReader(\"content\"));\n" +
1941
			"        System.out.println(br.read());\n" +
1942
			"    }\n" +
1943
			"    public static void main(String[] args) throws IOException {\n" +
1944
			"        new X().foo();\n" +
1945
			"    }\n" +
1946
			"}\n"
1947
		},
1948
		"99",
1949
		null,
1950
		true,
1951
		null,
1952
		options,
1953
		null);
1954
}
1955
// Bug 358903 - Filter practically unimportant resource leak warnings
1956
// a resource wrapper is not closed neither is the underlying resource
1957
public void test061d() {
1958
	Map options = getCompilerOptions();
1959
	options.put(CompilerOptions.OPTION_ReportUnclosedCloseable, CompilerOptions.ERROR);
1960
	options.put(CompilerOptions.OPTION_ReportPotentiallyUnclosedCloseable, CompilerOptions.WARNING);
1961
	this.runNegativeTest(
1962
		new String[] {
1963
			"X.java",
1964
			"import java.io.File;\n" +
1965
			"import java.io.BufferedInputStream;\n" +
1966
			"import java.io.FileInputStream;\n" +
1967
			"import java.io.IOException;\n" +
1968
			"public class X {\n" +
1969
			"    void foo() throws IOException {\n" +
1970
			"        File file = new File(\"somefile\");\n" +
1971
			"        FileInputStream fileStream  = new FileInputStream(file);\n" +
1972
			"        BufferedInputStream bis = new BufferedInputStream(fileStream);\n" +
1973
			"        BufferedInputStream doubleWrap = new BufferedInputStream(bis);\n" +
1974
			"        System.out.println(bis.available());\n" +
1975
			"    }\n" +
1976
			"    void inline() throws IOException {\n" +
1977
			"        File file = new File(\"somefile\");\n" +
1978
			"        BufferedInputStream bis2 = new BufferedInputStream(new FileInputStream(file));\n" +
1979
			"        System.out.println(bis2.available());\n" +
1980
			"    }\n" +
1981
			"    public static void main(String[] args) throws IOException {\n" +
1982
			"        try {\n" +
1983
			"            new X().foo();\n" +
1984
			"        } catch (IOException ex) {" +
1985
			"            System.out.println(\"Got IO Exception\");\n" +
1986
			"        }\n" +
1987
			"    }\n" +
1988
			"}\n"
1989
		},
1990
		"----------\n" +
1991
		"1. ERROR in X.java (at line 10)\n" +
1992
		"	BufferedInputStream doubleWrap = new BufferedInputStream(bis);\n" +
1993
		"	                    ^^^^^^^^^^\n" +
1994
		"Resource leak: \'doubleWrap\' is never closed\n" +
1995
		"----------\n" +
1996
		"2. ERROR in X.java (at line 15)\n" +
1997
		"	BufferedInputStream bis2 = new BufferedInputStream(new FileInputStream(file));\n" +
1998
		"	                    ^^^^\n" +
1999
		"Resource leak: \'bis2\' is never closed\n" +
2000
		"----------\n",
2001
		null,
2002
		true,
2003
		options);
2004
}
2005
// Bug 358903 - Filter practically unimportant resource leak warnings
2006
// Bug 361073 - Avoid resource leak warning when the top level resource is closed explicitly
2007
// a resource wrapper is closed closing also the underlying resource
2008
public void test061e() {
2009
	Map options = getCompilerOptions();
2010
	options.put(CompilerOptions.OPTION_ReportUnclosedCloseable, CompilerOptions.ERROR);
2011
	options.put(CompilerOptions.OPTION_ReportPotentiallyUnclosedCloseable, CompilerOptions.ERROR);
2012
	this.runConformTest(
2013
		new String[] {
2014
			"X.java",
2015
			"import java.io.File;\n" +
2016
			"import java.io.BufferedInputStream;\n" +
2017
			"import java.io.FileInputStream;\n" +
2018
			"import java.io.IOException;\n" +
2019
			"public class X {\n" +
2020
			"    FileInputStream fis;" +
2021
			"    void foo() throws IOException {\n" +
2022
			"        File file = new File(\"somefile\");\n" +
2023
			"        FileInputStream fileStream  = new FileInputStream(file);\n" +
2024
			"        BufferedInputStream bis = new BufferedInputStream(fileStream);\n" +
2025
			"        BufferedInputStream doubleWrap = new BufferedInputStream(bis);\n" +
2026
			"        System.out.println(bis.available());\n" +
2027
			"        bis.close();\n" +
2028
			"    }\n" +
2029
			"    void inline() throws IOException {\n" +
2030
			"        File file = new File(\"somefile\");\n" +
2031
			"        BufferedInputStream bis2 = new BufferedInputStream(fis = new FileInputStream(file));\n" + // field assignment
2032
			"        System.out.println(bis2.available());\n" +
2033
			"        bis2.close();\n" +
2034
			"        FileInputStream fileStream  = null;\n" +
2035
			"        BufferedInputStream bis3 = new BufferedInputStream(fileStream = new FileInputStream(file));\n" +
2036
			"        System.out.println(bis3.available());\n" +
2037
			"        bis3.close();\n" +
2038
			"    }\n" +
2039
			"    public static void main(String[] args) throws IOException {\n" +
2040
			"        try {\n" +
2041
			"            new X().foo();\n" +
2042
			"        } catch (IOException ex) {" +
2043
			"            System.out.println(\"Got IO Exception\");\n" +
2044
			"        }\n" +
2045
			"    }\n" +
2046
			"}\n"
2047
		},
2048
		"Got IO Exception",
2049
		null,
2050
		true,
2051
		null,
2052
		options,
2053
		null);
2054
}
2055
// Bug 358903 - Filter practically unimportant resource leak warnings
2056
// Bug 361073 - Avoid resource leak warning when the top level resource is closed explicitly
2057
// a resource wrapper is closed closing also the underlying resource - original test case
2058
public void test061f() throws IOException {
2059
	Map options = getCompilerOptions();
2060
	options.put(CompilerOptions.OPTION_ReportUnclosedCloseable, CompilerOptions.ERROR);
2061
	options.put(CompilerOptions.OPTION_ReportPotentiallyUnclosedCloseable, CompilerOptions.ERROR);
2062
	URL url = FileLocator.toFileURL(FileLocator.find(Platform.getBundle("org.eclipse.jdt.core.tests.compiler"), new Path("META-INF/MANIFEST.MF"), null));
2063
	this.runConformTest(
2064
		new String[] {
2065
			"X.java",
2066
			"import java.io.InputStream;\n" +
2067
			"import java.io.InputStreamReader;\n" +
2068
			"import java.io.BufferedReader;\n" +
2069
			"import java.io.IOException;\n" +
2070
			"import java.net.URL;\n" +
2071
			"public class X {\n" +
2072
			"    boolean loadURL(final URL url) throws IOException {\n" +
2073
			"        InputStream stream = null;\n" +
2074
			"        BufferedReader reader = null;\n" +
2075
			"        try {\n" +
2076
			"            stream = url.openStream();\n" +
2077
			"            reader = new BufferedReader(new InputStreamReader(stream));\n" +
2078
			"            System.out.println(reader.readLine());\n" +
2079
			"        } finally {\n" +
2080
			"            try {\n" +
2081
			"                if (reader != null)\n" +
2082
			"                    reader.close();\n" +
2083
			"            } catch (IOException x) {\n" +
2084
			"            }\n" +
2085
			"        }\n" +
2086
			"        return false; // 'stream' may not be closed at this location\n" +
2087
			"    }\n" +
2088
			"    public static void main(String[] args) throws IOException {\n" +
2089
			"        try {\n" +
2090
			"            new X().loadURL(new URL(\""+url.toString()+"\"));\n" +
2091
			"        } catch (IOException ex) {\n" +
2092
			"            System.out.println(\"Got IO Exception\"+ex);\n" +
2093
			"        }\n" +
2094
			"    }\n" +
2095
			"}\n"
2096
		},
2097
		"Manifest-Version: 1.0",
2098
		null,
2099
		true,
2100
		null,
2101
		options,
2102
		null);
2103
}
2104
// Bug 358903 - Filter practically unimportant resource leak warnings
2105
// Bug 361073 - Avoid resource leak warning when the top level resource is closed explicitly
2106
// a resource wrapper is closed closing also the underlying resource - from a real-world example
2107
public void test061f2() throws IOException {
2108
	Map options = getCompilerOptions();
2109
	options.put(CompilerOptions.OPTION_ReportUnclosedCloseable, CompilerOptions.ERROR);
2110
	options.put(CompilerOptions.OPTION_ReportPotentiallyUnclosedCloseable, CompilerOptions.ERROR);
2111
	this.runConformTest(
2112
		new String[] {
2113
			"X.java",
2114
			"import java.io.OutputStream;\n" +
2115
			"import java.io.FileOutputStream;\n" +
2116
			"import java.io.BufferedOutputStream;\n" +
2117
			"import java.io.IOException;\n" +
2118
			"public class X {\n" +
2119
			"    void zork() throws IOException {\n" +
2120
			"		try {\n" +
2121
			"			OutputStream os = null;\n" +
2122
			"			try {\n" +
2123
			"				os = new BufferedOutputStream(new FileOutputStream(\"somefile\"));\n" +
2124
			"				String externalForm = \"externalPath\";\n" +
2125
			"			} finally {\n" +
2126
			"				if (os != null)\n" +
2127
			"					os.close();\n" +
2128
			"			}\n" +
2129
			"		} catch (IOException e) {\n" +
2130
			"			e.printStackTrace();\n" +
2131
			"		}\n" +
2132
			"    }\n" +
2133
			"}\n"
2134
		},
2135
		"",
2136
		null,
2137
		true,
2138
		null,
2139
		options,
2140
		null);
2141
}
2142
// Bug 358903 - Filter practically unimportant resource leak warnings
2143
// Bug 361073 - Avoid resource leak warning when the top level resource is closed explicitly
2144
// a resource wrapper is sent to another method affecting also the underlying resource - from a real-world example
2145
public void test061f3() throws IOException {
2146
	Map options = getCompilerOptions();
2147
	options.put(CompilerOptions.OPTION_ReportUnclosedCloseable, CompilerOptions.ERROR);
2148
	options.put(CompilerOptions.OPTION_ReportPotentiallyUnclosedCloseable, CompilerOptions.ERROR);
2149
	this.runNegativeTest(
2150
		new String[] {
2151
			"X.java",
2152
			"import java.io.File;\n" +
2153
			"import java.io.FileInputStream;\n" +
2154
			"import java.io.FileNotFoundException;\n" +
2155
			"import java.io.InputStream;\n" +
2156
			"import java.io.BufferedInputStream;\n" +
2157
			"public class X {\n" +
2158
			"    String loadProfile(File profileFile) {\n" +
2159
			"		try {\n" +
2160
			"			InputStream stream = new BufferedInputStream(new FileInputStream(profileFile));\n" +
2161
			"			return loadProfile(stream);\n" +
2162
			"		} catch (FileNotFoundException e) {\n" +
2163
			"			//null\n" +
2164
			"		}\n" +
2165
			"		return null;\n" +
2166
			"	}\n" +
2167
			"	private String loadProfile(InputStream stream) {\n" +
2168
			"		return null;\n" +
2169
			"	}\n" +
2170
			"}\n"
2171
		},
2172
		"----------\n" +
2173
		"1. ERROR in X.java (at line 10)\n" +
2174
		"	return loadProfile(stream);\n" +
2175
		"	^^^^^^^^^^^^^^^^^^^^^^^^^^^\n" +
2176
		"Potential resource leak: \'stream\' may not be closed at this location\n" +
2177
		"----------\n",
2178
		null,
2179
		true,
2180
		options);
2181
}
2182
// Bug 358903 - Filter practically unimportant resource leak warnings
2183
// Bug 360908 - Avoid resource leak warning when the underlying/chained resource is closed explicitly
2184
// Different points in a resource chain are closed
2185
public void test061g() {
2186
	Map options = getCompilerOptions();
2187
	options.put(CompilerOptions.OPTION_ReportUnclosedCloseable, CompilerOptions.ERROR);
2188
	options.put(CompilerOptions.OPTION_ReportPotentiallyUnclosedCloseable, CompilerOptions.ERROR);
2189
	this.runNegativeTest(
2190
		new String[] {
2191
			"X.java",
2192
			"import java.io.File;\n" +
2193
			"import java.io.BufferedInputStream;\n" +
2194
			"import java.io.FileInputStream;\n" +
2195
			"import java.io.IOException;\n" +
2196
			"public class X {\n" +
2197
			"    void closeMiddle() throws IOException {\n" +
2198
			"        File file = new File(\"somefile\");\n" +
2199
			"        FileInputStream fileStream  = new FileInputStream(file);\n" +
2200
			"        BufferedInputStream bis = new BufferedInputStream(fileStream);\n" +
2201
			"        BufferedInputStream doubleWrap = new BufferedInputStream(bis);\n" +
2202
			"        System.out.println(bis.available());\n" +
2203
			"        bis.close();\n" +
2204
			"    }\n" +
2205
			"    void closeOuter() throws IOException {\n" +
2206
			"        File file2 = new File(\"somefile\");\n" +
2207
			"        FileInputStream fileStream2  = new FileInputStream(file2);\n" +
2208
			"        BufferedInputStream bis2 = new BufferedInputStream(fileStream2);\n" +
2209
			"        BufferedInputStream doubleWrap2 = new BufferedInputStream(bis2);\n" +
2210
			"        System.out.println(bis2.available());\n" +
2211
			"        doubleWrap2.close();\n" +
2212
			"    }\n" +
2213
			"    void neverClosed() throws IOException {\n" +
2214
			"        File file3 = new File(\"somefile\");\n" +
2215
			"        FileInputStream fileStream3  = new FileInputStream(file3);\n" +
2216
			"        BufferedInputStream bis3 = new BufferedInputStream(fileStream3);\n" +
2217
			"        BufferedInputStream doubleWrap3 = new BufferedInputStream(bis3);\n" +
2218
			"        System.out.println(doubleWrap3.available());\n" +
2219
			"    }\n" +
2220
			"}\n"
2221
		},
2222
		"----------\n" +
2223
		"1. ERROR in X.java (at line 26)\n" +
2224
		"	BufferedInputStream doubleWrap3 = new BufferedInputStream(bis3);\n" +
2225
		"	                    ^^^^^^^^^^^\n" +
2226
		"Resource leak: \'doubleWrap3\' is never closed\n" +
2227
		"----------\n",
2228
		null,
2229
		true,
2230
		options);
2231
}
2232
// Bug 358903 - Filter practically unimportant resource leak warnings
2233
// Bug 360908 - Avoid resource leak warning when the underlying/chained resource is closed explicitly
2234
// Different points in a resource chain are potentially closed
2235
public void test061h() {
2236
	Map options = getCompilerOptions();
2237
	options.put(CompilerOptions.OPTION_ReportUnclosedCloseable, CompilerOptions.ERROR);
2238
	options.put(CompilerOptions.OPTION_ReportPotentiallyUnclosedCloseable, CompilerOptions.ERROR);
2239
	this.runNegativeTest(
2240
		new String[] {
2241
			"X.java",
2242
			"import java.io.File;\n" +
2243
			"import java.io.BufferedInputStream;\n" +
2244
			"import java.io.FileInputStream;\n" +
2245
			"import java.io.IOException;\n" +
2246
			"public class X {\n" +
2247
			"    void closeMiddle(boolean b) throws IOException {\n" +
2248
			"        File file = new File(\"somefile\");\n" +
2249
			"        FileInputStream fileStream  = new FileInputStream(file);\n" +
2250
			"        BufferedInputStream bis = new BufferedInputStream(fileStream);\n" +
2251
			"        BufferedInputStream doubleWrap = new BufferedInputStream(bis);\n" +
2252
			"        System.out.println(bis.available());\n" +
2253
			"        if (b)\n" +
2254
			"            bis.close();\n" +
2255
			"    }\n" +
2256
			"    void closeOuter(boolean b) throws IOException {\n" +
2257
			"        File file2 = new File(\"somefile\");\n" +
2258
			"        FileInputStream fileStream2  = new FileInputStream(file2);\n" +
2259
			"        BufferedInputStream dummy;\n" +
2260
			"        BufferedInputStream bis2 = (dummy = new BufferedInputStream(fileStream2));\n" +
2261
			"        BufferedInputStream doubleWrap2 = new BufferedInputStream(bis2);\n" +
2262
			"        System.out.println(bis2.available());\n" +
2263
			"        if (b)\n" +
2264
			"            doubleWrap2.close();\n" +
2265
			"    }\n" +
2266
			"    void potAndDef(boolean b) throws IOException {\n" +
2267
			"        File file3 = new File(\"somefile\");\n" +
2268
			"        FileInputStream fileStream3  = new FileInputStream(file3);\n" +
2269
			"        BufferedInputStream bis3 = new BufferedInputStream(fileStream3);\n" +
2270
			"        BufferedInputStream doubleWrap3 = new BufferedInputStream(bis3);\n" +
2271
			"        System.out.println(doubleWrap3.available());\n" +
2272
			"        if (b) bis3.close();\n" +
2273
			"        fileStream3.close();\n" +
2274
			"    }\n" +
2275
			"}\n"
2276
		},
2277
		"----------\n" +
2278
		"1. ERROR in X.java (at line 10)\n" +
2279
		"	BufferedInputStream doubleWrap = new BufferedInputStream(bis);\n" +
2280
		"	                    ^^^^^^^^^^\n" +
2281
		"Potential resource leak: \'doubleWrap\' may not be closed\n" +
2282
		"----------\n" +
2283
		"2. ERROR in X.java (at line 20)\n" +
2284
		"	BufferedInputStream doubleWrap2 = new BufferedInputStream(bis2);\n" +
2285
		"	                    ^^^^^^^^^^^\n" +
2286
		"Potential resource leak: \'doubleWrap2\' may not be closed\n" +
2287
		"----------\n",
2288
		null,
2289
		true,
2290
		options);
2291
}
2292
// Bug 358903 - Filter practically unimportant resource leak warnings
2293
// local var is re-used for two levels of wrappers
2294
public void test061i() {
2295
	Map options = getCompilerOptions();
2296
	options.put(CompilerOptions.OPTION_ReportUnclosedCloseable, CompilerOptions.ERROR);
2297
	options.put(CompilerOptions.OPTION_ReportPotentiallyUnclosedCloseable, CompilerOptions.ERROR);
2298
	this.runNegativeTest(
2299
		new String[] {
2300
			"X.java",
2301
			"import java.io.File;\n" +
2302
			"import java.io.InputStream;\n" +
2303
			"import java.io.BufferedInputStream;\n" +
2304
			"import java.io.FileInputStream;\n" +
2305
			"import java.io.IOException;\n" +
2306
			"public class X {\n" +
2307
			"    void closeMiddle() throws IOException {\n" +
2308
			"        File file = new File(\"somefile\");\n" +
2309
			"        InputStream stream  = new FileInputStream(file);\n" +
2310
			"        stream = new BufferedInputStream(stream);\n" +
2311
			"        InputStream middle;\n" +
2312
			"        stream = new BufferedInputStream(middle = stream);\n" +
2313
			"        System.out.println(stream.available());\n" +
2314
			"        middle.close();\n" +
2315
			"    }\n" +
2316
			"    void closeOuter() throws IOException {\n" +
2317
			"        File file = new File(\"somefile\");\n" +
2318
			"        InputStream stream2  = new FileInputStream(file);\n" +
2319
			"        stream2 = new BufferedInputStream(stream2);\n" +
2320
			"        stream2 = new BufferedInputStream(stream2);\n" +
2321
			"        System.out.println(stream2.available());\n" +
2322
			"        stream2.close();\n" +
2323
			"    }\n" +
2324
			"    void neverClosed() throws IOException {\n" +
2325
			"        File file = new File(\"somefile\");\n" +
2326
			"        InputStream stream3  = new FileInputStream(file);\n" +
2327
			"        stream3 = new BufferedInputStream(stream3);\n" +
2328
			"        stream3 = new BufferedInputStream(stream3);\n" +
2329
			"        System.out.println(stream3.available());\n" +
2330
			"    }\n" +
2331
			"}\n"
2332
		},
2333
		"----------\n" +
2334
		"1. ERROR in X.java (at line 26)\n" +
2335
		"	InputStream stream3  = new FileInputStream(file);\n" +
2336
		"	            ^^^^^^^\n" +
2337
		"Resource leak: \'stream3\' is never closed\n" +
2338
		"----------\n",
2339
		null,
2340
		true,
2341
		options);
2342
}
2343
// Bug 358903 - Filter practically unimportant resource leak warnings
2344
// self-wrapping a method argument (caused NPE UnconditionalFlowInfo.markAsDefinitelyNull(..)).
2345
public void test061j() {
2346
	Map options = getCompilerOptions();
2347
	options.put(CompilerOptions.OPTION_ReportUnclosedCloseable, CompilerOptions.ERROR);
2348
	options.put(CompilerOptions.OPTION_ReportPotentiallyUnclosedCloseable, CompilerOptions.ERROR);
2349
	this.runConformTest(
2350
		new String[] {
2351
			"X.java",
2352
			"import java.io.InputStream;\n" +
2353
			"import java.io.BufferedInputStream;\n" +
2354
			"import java.io.IOException;\n" +
2355
			"public class X {\n" +
2356
			"    void foo(InputStream stream) throws IOException {\n" +
2357
			"        stream = new BufferedInputStream(stream);\n" +
2358
			"        System.out.println(stream.available());\n" +
2359
			"        stream.close();\n" +
2360
			"    }\n" +
2361
			"    void boo(InputStream stream2) throws IOException {\n" +
2362
			"        stream2 = new BufferedInputStream(stream2);\n" +
2363
			"        System.out.println(stream2.available());\n" +
2364
			"    }\n" +
2365
			"}\n"
2366
		},
2367
		"",
2368
		null,
2369
		true,
2370
		null,
2371
		options,
2372
		null);
2373
}
2374
// Bug 358903 - Filter practically unimportant resource leak warnings
2375
// a wrapper is created in a return statement
2376
public void test061k() throws IOException {
2377
	Map options = getCompilerOptions();
2378
	options.put(CompilerOptions.OPTION_ReportUnclosedCloseable, CompilerOptions.ERROR);
2379
	options.put(CompilerOptions.OPTION_ReportPotentiallyUnclosedCloseable, CompilerOptions.ERROR);
2380
	this.runConformTest(
2381
		new String[] {
2382
			"X.java",
2383
			"import java.io.File;\n" +
2384
			"import java.io.FileInputStream;\n" +
2385
			"import java.io.BufferedInputStream;\n" +
2386
			"import java.io.IOException;\n" +
2387
			"public class X {\n" +
2388
			"    BufferedInputStream getReader(File file) throws IOException {\n" +
2389
			"        FileInputStream stream = new FileInputStream(file);\n" +
2390
			"        return new BufferedInputStream(stream);\n" +
2391
			"    }\n" +
2392
			"}\n"
2393
		},
2394
		"",
2395
		null,
2396
		true,
2397
		null,
2398
		options,
2399
		null);
2400
}
2401
// Bug 358903 - Filter practically unimportant resource leak warnings
2402
// a closeable is assigned to a field
2403
public void test061l() throws IOException {
2404
	Map options = getCompilerOptions();
2405
	options.put(CompilerOptions.OPTION_ReportUnclosedCloseable, CompilerOptions.ERROR);
2406
	options.put(CompilerOptions.OPTION_ReportPotentiallyUnclosedCloseable, CompilerOptions.ERROR);
2407
	this.runConformTest(
2408
		new String[] {
2409
			"X.java",
2410
			"import java.io.File;\n" +
2411
			"import java.io.FileInputStream;\n" +
2412
			"import java.io.BufferedInputStream;\n" +
2413
			"import java.io.IOException;\n" +
2414
			"public class X {\n" +
2415
			"    BufferedInputStream stream;\n" +
2416
			"    void foo(File file) throws IOException {\n" +
2417
			"        FileInputStream s = new FileInputStream(file);\n" +
2418
			"        stream = new BufferedInputStream(s);\n" +
2419
			"    }\n" +
2420
			"}\n"
2421
		},
2422
		"",
2423
		null,
2424
		true,
2425
		null,
2426
		options,
2427
		null);
2428
}
2429
// Bug 361407 - Resource leak warning when resource is assigned to a field outside of constructor
2430
// a closeable is assigned to a field - constructor vs. method
2431
public void test061l2() throws IOException {
2432
	Map options = getCompilerOptions();
2433
	options.put(CompilerOptions.OPTION_ReportUnclosedCloseable, CompilerOptions.ERROR);
2434
	options.put(CompilerOptions.OPTION_ReportPotentiallyUnclosedCloseable, CompilerOptions.ERROR);
2435
	this.runNegativeTest(
2436
		new String[] {
2437
			"xy/Leaks.java",
2438
			"package xy;\n" +
2439
			"\n" +
2440
			"import java.io.FileInputStream;\n" +
2441
			"import java.io.IOException;\n" +
2442
			"\n" +
2443
			"public class Leaks {\n" +
2444
			"    private FileInputStream fInput;\n" +
2445
			"\n" +
2446
			"    Leaks(String name) throws IOException {\n" +
2447
			"        FileInputStream fileInputStream= new FileInputStream(name);\n" +
2448
			"        fInput= fileInputStream;\n" + // warning silenced by field assignment
2449
			"        Objects.hashCode(fInput);\n" +
2450
			"        \n" +
2451
			"        init(name);\n" +
2452
			"    }\n" +
2453
			"    \n" +
2454
			"    Leaks() throws IOException {\n" +
2455
			"        this(new FileInputStream(\"default\")); // potential problem\n" +
2456
			"    }\n" +
2457
			"    \n" +
2458
			"    Leaks(FileInputStream fis) throws IOException {\n" +
2459
			"        fInput= fis;\n" +
2460
			"    }\n" +
2461
			"    void init(String name) throws IOException {\n" +
2462
			"        FileInputStream fileInputStream= new FileInputStream(name);\n" +
2463
			"        fInput= fileInputStream;\n" + // warning silenced by field assignment
2464
			"        Objects.hashCode(fInput);\n" +
2465
			"    }\n" +
2466
			"    \n" +
2467
			"    public void dispose() throws IOException {\n" +
2468
			"        fInput.close();\n" +
2469
			"    }\n" +
2470
			"}\n" +
2471
			"class Objects {\n" + // mock java.util.Objects (@since 1.7).
2472
			"    static int hashCode(Object o) { return 13; }\n" +
2473
			"}\n"
2474
		},
2475
		"----------\n" +
2476
		"1. ERROR in xy\\Leaks.java (at line 18)\n" +
2477
		"	this(new FileInputStream(\"default\")); // potential problem\n" +
2478
		"	     ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^\n" +
2479
		"Potential resource leak: \'<unassigned Closeable value>\' may not be closed\n" +
2480
		"----------\n",
2481
		null,
2482
		true,
2483
		options);
2484
}
2485
// Bug 361407 - Resource leak warning when resource is assigned to a field outside of constructor
2486
// a closeable is not assigned to a field - constructor vs. method
2487
public void test061l3() throws IOException {
2488
	Map options = getCompilerOptions();
2489
	options.put(CompilerOptions.OPTION_ReportUnclosedCloseable, CompilerOptions.ERROR);
2490
	options.put(CompilerOptions.OPTION_ReportPotentiallyUnclosedCloseable, CompilerOptions.ERROR);
2491
	this.runNegativeTest(
2492
		new String[] {
2493
			"xy/Leaks.java",
2494
			"package xy;\n" +
2495
			"\n" +
2496
			"import java.io.FileInputStream;\n" +
2497
			"import java.io.IOException;\n" +
2498
			"\n" +
2499
			"public class Leaks {\n" +
2500
			"\n" +
2501
			"    Leaks(String name) throws IOException {\n" +
2502
			"        FileInputStream fileInputStream= new FileInputStream(name);\n" +
2503
			"        Objects.hashCode(fileInputStream);\n" +
2504
			"        \n" +
2505
			"        init(name);\n" +
2506
			"    }\n" +
2507
			"    void init(String name) throws IOException {\n" +
2508
			"        FileInputStream fileInputStream= new FileInputStream(name);\n" +
2509
			"        Objects.hashCode(fileInputStream);\n" +
2510
			"    }\n" +
2511
			"}\n" +
2512
			"class Objects {\n" + // mock java.util.Objects (@since 1.7).
2513
			"    static int hashCode(Object o) { return 13; }\n" +
2514
			"}\n"
2515
		},
2516
		"----------\n" +
2517
		"1. ERROR in xy\\Leaks.java (at line 9)\n" +
2518
		"	FileInputStream fileInputStream= new FileInputStream(name);\n" +
2519
		"	                ^^^^^^^^^^^^^^^\n" +
2520
		"Potential resource leak: \'fileInputStream\' may not be closed\n" +
2521
		"----------\n" +
2522
		"2. ERROR in xy\\Leaks.java (at line 15)\n" +
2523
		"	FileInputStream fileInputStream= new FileInputStream(name);\n" +
2524
		"	                ^^^^^^^^^^^^^^^\n" +
2525
		"Potential resource leak: \'fileInputStream\' may not be closed\n" +
2526
		"----------\n",
2527
		null,
2528
		true,
2529
		options);
2530
}
2531
// Bug 358903 - Filter practically unimportant resource leak warnings
2532
// a closeable is passed to another method in a return statement
2533
// example constructed after org.eclipse.equinox.internal.p2.artifact.repository.simple.SimpleArtifactRepository#getArtifact(..)
2534
public void test061m() throws IOException {
2535
	Map options = getCompilerOptions();
2536
	options.put(CompilerOptions.OPTION_ReportUnclosedCloseable, CompilerOptions.ERROR);
2537
	options.put(CompilerOptions.OPTION_ReportPotentiallyUnclosedCloseable, CompilerOptions.ERROR);
2538
	this.runNegativeTest(
2539
		new String[] {
2540
			"X.java",
2541
			"import java.io.File;\n" +
2542
			"import java.io.FileInputStream;\n" +
2543
			"import java.io.BufferedInputStream;\n" +
2544
			"import java.io.InputStream;\n" +
2545
			"import java.io.IOException;\n" +
2546
			"public class X {\n" +
2547
			"    BufferedInputStream stream;\n" +
2548
			"    BufferedInputStream foo(File file) throws IOException {\n" +
2549
			"        FileInputStream s = new FileInputStream(file);\n" +
2550
			"        return check(new BufferedInputStream(s));\n" +
2551
			"    }\n" +
2552
			"    BufferedInputStream foo2(FileInputStream s, File file) throws IOException {\n" +
2553
			"        s = new FileInputStream(file);\n" +
2554
			"        return check(s);\n" +
2555
			"    }\n" +
2556
			"    BufferedInputStream foo3(InputStream s) throws IOException {\n" +
2557
			"        s = check(s);\n" +
2558
			"        return check(s);\n" +
2559
			"    }\n" +
2560
			"    BufferedInputStream check(InputStream s) { return null; }\n" +
2561
			"}\n"
2562
		},
2563
		// TODO: also these warnings *might* be avoidable by detecting check(s) as a wrapper creation??
2564
		"----------\n" +
2565
		"1. ERROR in X.java (at line 10)\n" +
2566
		"	return check(new BufferedInputStream(s));\n" +
2567
		"	^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^\n" +
2568
		"Potential resource leak: \'<unassigned Closeable value>\' may not be closed at this location\n" +
2569
		"----------\n" +
2570
		"2. ERROR in X.java (at line 14)\n" +
2571
		"	return check(s);\n" +
2572
		"	^^^^^^^^^^^^^^^^\n" +
2573
		"Potential resource leak: \'s\' may not be closed at this location\n" +
2574
		"----------\n" +
2575
		"3. ERROR in X.java (at line 18)\n" +
2576
		"	return check(s);\n" +
2577
		"	^^^^^^^^^^^^^^^^\n" +
2578
		"Potential resource leak: \'s\' may not be closed at this location\n" +
2579
		"----------\n",
2580
		null,
2581
		true,
2582
		options);
2583
}
2584
// Bug 358903 - Filter practically unimportant resource leak warnings
2585
// a resource wrapper does not wrap any provided resource
2586
public void test061n() {
2587
	Map options = getCompilerOptions();
2588
	options.put(CompilerOptions.OPTION_ReportUnclosedCloseable, CompilerOptions.ERROR);
2589
	options.put(CompilerOptions.OPTION_ReportPotentiallyUnclosedCloseable, CompilerOptions.ERROR);
2590
	this.runNegativeTest(
2591
		new String[] {
2592
			"X.java",
2593
			"import java.io.PrintWriter;\n" +
2594
			"import java.io.IOException;\n" +
2595
			"public class X {\n" +
2596
			"    void foo() throws IOException {\n" +
2597
			"        PrintWriter writer = new PrintWriter(\"filename\");\n" +
2598
			"        writer.write(1);\n" +
2599
			"    }\n" +
2600
			"}\n"
2601
		},
2602
		"----------\n" +
2603
		"1. ERROR in X.java (at line 5)\n" +
2604
		"	PrintWriter writer = new PrintWriter(\"filename\");\n" +
2605
		"	            ^^^^^^\n" +
2606
		"Resource leak: \'writer\' is never closed\n" +
2607
		"----------\n",
2608
		null,
2609
		true,
2610
		options);
2611
}
2612
// Bug 358903 - Filter practically unimportant resource leak warnings
2613
// a resource wrapper is closed only in its local block, underlying resource may leak
2614
public void test061o() {
2615
	Map options = getCompilerOptions();
2616
	options.put(CompilerOptions.OPTION_ReportUnclosedCloseable, CompilerOptions.ERROR);
2617
	options.put(CompilerOptions.OPTION_ReportPotentiallyUnclosedCloseable, CompilerOptions.ERROR);
2618
	this.runNegativeTest(
2619
		new String[] {
2620
			"X.java",
2621
			"import java.io.File;\n" +
2622
			"import java.io.FileInputStream;\n" +
2623
			"import java.io.BufferedInputStream;\n" +
2624
			"import java.io.IOException;\n" +
2625
			"public class X {\n" +
2626
			"    void foo(boolean bar) throws IOException {\n" +
2627
			"        File file = new File(\"somefil\");\n" +
2628
			"        FileInputStream fileStream  = new FileInputStream(file);\n" +
2629
			"        BufferedInputStream bis = new BufferedInputStream(fileStream);   \n" +
2630
			"        if (bar) {\n" +
2631
			"            BufferedInputStream doubleWrap = new BufferedInputStream(bis);\n" +
2632
			"            doubleWrap.close();\n" +
2633
			"        }\n" +
2634
			"    }\n" +
2635
			"}\n"
2636
		},
2637
		"----------\n" +
2638
		"1. ERROR in X.java (at line 9)\n" +
2639
		"	BufferedInputStream bis = new BufferedInputStream(fileStream);   \n" +
2640
		"	                    ^^^\n" +
2641
		"Potential resource leak: \'bis\' may not be closed\n" +
2642
		"----------\n",
2643
		null,
2644
		true,
2645
		options);
2646
}
2647
// Bug 358903 - Filter practically unimportant resource leak warnings
2648
// a resource wrapper is conditionally allocated but not closed - from a real-world example
2649
public void test061f4() throws IOException {
2650
	Map options = getCompilerOptions();
2651
	options.put(CompilerOptions.OPTION_ReportUnclosedCloseable, CompilerOptions.ERROR);
2652
	options.put(CompilerOptions.OPTION_ReportPotentiallyUnclosedCloseable, CompilerOptions.ERROR);
2653
	this.runNegativeTest(
2654
		new String[] {
2655
			"X.java",
2656
			"import java.io.File;\n" +
2657
			"import java.io.FileInputStream;\n" +
2658
			"import java.io.FileNotFoundException;\n" +
2659
			"import java.io.InputStream;\n" +
2660
			"import java.io.BufferedInputStream;\n" +
2661
			"public class X {\n" +
2662
			"    	void foo(File location, String adviceFilePath) throws FileNotFoundException {\n" +
2663
			"		InputStream stream = null;\n" +
2664
			"		if (location.isDirectory()) {\n" +
2665
			"			File adviceFile = new File(location, adviceFilePath);\n" +
2666
			"			stream = new BufferedInputStream(new FileInputStream(adviceFile));\n" +
2667
			"		}\n" +
2668
			"	}\n" +
2669
			"}\n"
2670
		},
2671
		"----------\n" +
2672
		"1. ERROR in X.java (at line 11)\n" +
2673
		"	stream = new BufferedInputStream(new FileInputStream(adviceFile));\n" +
2674
		"	^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^\n" +
2675
		"Potential resource leak: \'stream\' may not be closed\n" + // message could be stronger, but the enclosing if blurs the picture
2676
		"----------\n",
2677
		null,
2678
		true,
2679
		options);
2680
}
2681
// Bug 358903 - Filter practically unimportant resource leak warnings
2682
// a t-w-r wraps an existing resource
2683
public void test061p() {
2684
	if (this.complianceLevel < ClassFileConstants.JDK1_7) return;
2685
	Map options = getCompilerOptions();
2686
	options.put(CompilerOptions.OPTION_ReportUnclosedCloseable, CompilerOptions.ERROR);
2687
	options.put(CompilerOptions.OPTION_ReportPotentiallyUnclosedCloseable, CompilerOptions.ERROR);
2688
	this.runConformTest(
2689
		new String[] {
2690
			"X.java",
2691
			"import java.io.PrintWriter;\n" +
2692
			"import java.io.BufferedWriter;\n" +
2693
			"import java.io.IOException;\n" +
2694
			"public class X {\n" +
2695
			"    void foo() throws IOException {\n" +
2696
			"        PrintWriter writer = new PrintWriter(\"filename\");\n" +
2697
			"        try (BufferedWriter bw = new BufferedWriter(writer)) {\n" +
2698
			"            bw.write(1);\n" +
2699
			"        }\n" +
2700
			"    }\n" +
2701
			"}\n"
2702
		},
2703
		"",
2704
		null,
2705
		true,
2706
		null,
2707
		options,
2708
		null);
2709
}
2710
// Bug 358903 - Filter practically unimportant resource leak warnings
2711
// a t-w-r potentially wraps an existing resource
2712
// DISABLED, fails because we currently don't include t-w-r managed resources in the analysis
2713
public void _test061q() {
2714
	if (this.complianceLevel < ClassFileConstants.JDK1_7) return;
2715
	Map options = getCompilerOptions();
2716
	options.put(CompilerOptions.OPTION_ReportUnclosedCloseable, CompilerOptions.ERROR);
2717
	options.put(CompilerOptions.OPTION_ReportPotentiallyUnclosedCloseable, CompilerOptions.ERROR);
2718
	this.runNegativeTest(
2719
		new String[] {
2720
			"X.java",
2721
			"import java.io.PrintWriter;\n" +
2722
			"import java.io.BufferedWriter;\n" +
2723
			"import java.io.IOException;\n" +
2724
			"public class X {\n" +
2725
			"    void foo(boolean b) throws IOException {\n" +
2726
			"        PrintWriter writer = new PrintWriter(\"filename\");\n" +
2727
			"        if (b)\n" +
2728
			"            try (BufferedWriter bw = new BufferedWriter(writer)) {\n" +
2729
			"                bw.write(1);\n" +
2730
			"            }\n" +
2731
			"    }\n" +
2732
			"}\n"
2733
		},
2734
		"----------\n" +
2735
		"1. ERROR in X.java (at line 6)\n" +
2736
		"	PrintWriter writer = new PrintWriter(\\\"filename\\\");\n" +
2737
		"	^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^\n" +
2738
		"Potential resource leak: \'writer\' may not be closed\n" +
2739
		"----------\n",
2740
		null,
2741
		true,
2742
		options);
2743
}
2744
// Bug 358903 - Filter practically unimportant resource leak warnings
2745
// the inner from a wrapper is returned
2746
public void test061r() {
2747
	Map options = getCompilerOptions();
2748
	options.put(CompilerOptions.OPTION_ReportUnclosedCloseable, CompilerOptions.ERROR);
2749
	options.put(CompilerOptions.OPTION_ReportPotentiallyUnclosedCloseable, CompilerOptions.ERROR);
2750
	this.runConformTest(
2751
		new String[] {
2752
			"X.java",
2753
			"import java.io.FileInputStream;\n" +
2754
			"import java.io.File;\n" +
2755
			"import java.io.BufferedInputStream;\n" +
2756
			"import java.io.IOException;\n" +
2757
			"public class X {\n" +
2758
			"    FileInputStream foo() throws IOException {\n" +
2759
			"        File file = new File(\"somefil\");\n" +
2760
			"        FileInputStream fileStream  = new FileInputStream(file);\n" +
2761
			"        BufferedInputStream bis = new BufferedInputStream(fileStream);   \n" +
2762
			"        return fileStream;\n" +
2763
			"    }\n" +
2764
			"}\n"
2765
		},
2766
		"",
2767
		null,
2768
		true,
2769
		null,
2770
		options,
2771
		null);
2772
}
2773
// Bug 358903 - Filter practically unimportant resource leak warnings
2774
// a wrapper is forgotten, the inner is closed afterwards
2775
public void test061s() {
2776
	Map options = getCompilerOptions();
2777
	options.put(CompilerOptions.OPTION_ReportUnclosedCloseable, CompilerOptions.ERROR);
2778
	options.put(CompilerOptions.OPTION_ReportPotentiallyUnclosedCloseable, CompilerOptions.ERROR);
2779
	this.runConformTest(
2780
		new String[] {
2781
			"X.java",
2782
			"import java.io.FileInputStream;\n" +
2783
			"import java.io.File;\n" +
2784
			"import java.io.BufferedInputStream;\n" +
2785
			"import java.io.IOException;\n" +
2786
			"public class X {\n" +
2787
			"    void foo() throws IOException {\n" +
2788
			"        File file = new File(\"somefil\");\n" +
2789
			"        FileInputStream fileStream  = new FileInputStream(file);\n" +
2790
			"        BufferedInputStream bis = new BufferedInputStream(fileStream);\n" +
2791
			"        bis = null;\n" +
2792
			"        fileStream.close();\n" +
2793
			"    }\n" +
2794
			"}\n"
2795
		},
2796
		"",
2797
		null,
2798
		true,
2799
		null,
2800
		options,
2801
		null);
2802
}
2803
// Bug 362331 - Resource leak not detected when closeable not assigned to variable
2804
// a resource is never assigned
2805
public void test062a() throws IOException {
2806
	Map options = getCompilerOptions();
2807
	options.put(CompilerOptions.OPTION_ReportUnclosedCloseable, CompilerOptions.ERROR);
2808
	options.put(CompilerOptions.OPTION_ReportPotentiallyUnclosedCloseable, CompilerOptions.ERROR);
2809
	this.runNegativeTest(
2810
		new String[] {
2811
			"X.java",
2812
			"import java.io.File;\n" +
2813
			"import java.io.FileOutputStream;\n" +
2814
			"import java.io.IOException;\n" +
2815
			"public class X {\n" +
2816
			"    void foo() throws IOException {\n" +
2817
			"        new FileOutputStream(new File(\"C:\\temp\\foo.txt\")).write(1);\n" +
2818
			"    }\n" +
2819
			"}\n"
2820
		},
2821
		"----------\n" +
2822
		"1. ERROR in X.java (at line 6)\n" +
2823
		"	new FileOutputStream(new File(\"C:\\temp\\foo.txt\")).write(1);\n" +
2824
		"	^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^\n" +
2825
		"Resource leak: \'<unassigned Closeable value>\' is never closed\n" +
2826
		"----------\n",
2827
		null,
2828
		true,
2829
		options);
2830
}
2831
// Bug 362331 - Resource leak not detected when closeable not assigned to variable
2832
// a freshly allocated resource is immediately closed
2833
public void test062b() throws IOException {
2834
	Map options = getCompilerOptions();
2835
	options.put(CompilerOptions.OPTION_ReportUnclosedCloseable, CompilerOptions.ERROR);
2836
	options.put(CompilerOptions.OPTION_ReportPotentiallyUnclosedCloseable, CompilerOptions.ERROR);
2837
	this.runConformTest(
2838
		new String[] {
2839
			"X.java",
2840
			"import java.io.File;\n" +
2841
			"import java.io.FileOutputStream;\n" +
2842
			"import java.io.IOException;\n" +
2843
			"public class X {\n" +
2844
			"    void foo() throws IOException {\n" +
2845
			"        new FileOutputStream(new File(\"C:\\temp\\foo.txt\")).close();\n" +
2846
			"    }\n" +
2847
			"}\n"
2848
		},
2849
		"",
2850
		null,
2851
		true,
2852
		null,
2853
		options,
2854
		null);
2855
}
2856
// Bug 362331 - Resource leak not detected when closeable not assigned to variable
2857
// a resource is directly passed to another method
2858
public void test062c() throws IOException {
2859
	Map options = getCompilerOptions();
2860
	options.put(CompilerOptions.OPTION_ReportUnclosedCloseable, CompilerOptions.ERROR);
2861
	options.put(CompilerOptions.OPTION_ReportPotentiallyUnclosedCloseable, CompilerOptions.ERROR);
2862
	this.runNegativeTest(
2863
		new String[] {
2864
			"X.java",
2865
			"import java.io.File;\n" +
2866
			"import java.io.FileOutputStream;\n" +
2867
			"import java.io.IOException;\n" +
2868
			"public class X {\n" +
2869
			"    void foo() throws IOException {\n" +
2870
			"        writeIt(new FileOutputStream(new File(\"C:\\temp\\foo.txt\")));\n" +
2871
			"    }\n" +
2872
			"    void writeIt(FileOutputStream fos) throws IOException {\n" +
2873
			"        fos.write(1);\n" +
2874
			"        fos.close();\n" +
2875
			"    }\n" +
2876
			"}\n"
2877
		},
2878
		"----------\n" +
2879
		"1. ERROR in X.java (at line 6)\n" +
2880
		"	writeIt(new FileOutputStream(new File(\"C:\\temp\\foo.txt\")));\n" +
2881
		"	        ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^\n" +
2882
		"Potential resource leak: \'<unassigned Closeable value>\' may not be closed\n" +
2883
		"----------\n",
2884
		null,
2885
		true,
2886
		options);
2887
}
2888
// Bug 362331 - Resource leak not detected when closeable not assigned to variable
2889
// a resource is not used
2890
public void test062d() throws IOException {
2891
	Map options = getCompilerOptions();
2892
	options.put(CompilerOptions.OPTION_ReportUnclosedCloseable, CompilerOptions.ERROR);
2893
	options.put(CompilerOptions.OPTION_ReportPotentiallyUnclosedCloseable, CompilerOptions.ERROR);
2894
	this.runNegativeTest(
2895
		new String[] {
2896
			"X.java",
2897
			"import java.io.File;\n" +
2898
			"import java.io.FileOutputStream;\n" +
2899
			"import java.io.IOException;\n" +
2900
			"public class X {\n" +
2901
			"    void foo() throws IOException {\n" +
2902
			"        new FileOutputStream(new File(\"C:\\temp\\foo.txt\"));\n" +
2903
			"    }\n" +
2904
			"}\n"
2905
		},
2906
		"----------\n" +
2907
		"1. ERROR in X.java (at line 6)\n" +
2908
		"	new FileOutputStream(new File(\"C:\\temp\\foo.txt\"));\n" +
2909
		"	^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^\n" +
2910
		"Resource leak: \'<unassigned Closeable value>\' is never closed\n" +
2911
		"----------\n",
2912
		null,
2913
		true,
2914
		options);
2915
}
2916
// Bug 362332 - Only report potential leak when closeable not created in the local scope
2917
// a wrapper is obtained from another method
2918
public void test063a() throws IOException {
2919
	Map options = getCompilerOptions();
2920
	options.put(CompilerOptions.OPTION_ReportUnclosedCloseable, CompilerOptions.ERROR);
2921
	options.put(CompilerOptions.OPTION_ReportPotentiallyUnclosedCloseable, CompilerOptions.ERROR);
2922
	this.runNegativeTest(
2923
		new String[] {
2924
			"X.java",
2925
			"import java.io.File;\n" +
2926
			"import java.io.FileInputStream;\n" +
2927
			"import java.io.BufferedInputStream;\n" +
2928
			"import java.io.IOException;\n" +
2929
			"public class X {\n" +
2930
			"    void read(File file) throws IOException {\n" +
2931
			"        FileInputStream stream = new FileInputStream(file);\n" +
2932
			"        BufferedInputStream bis = new BufferedInputStream(stream); // never since reassigned\n" +
2933
			"        FileInputStream stream2 = new FileInputStream(file); // unsure since passed to method\n" +
2934
			"        bis = getReader(stream2); // unsure since obtained from method\n" +
2935
			"        bis.available();\n" +
2936
			"    }\n" +
2937
			"    BufferedInputStream getReader(FileInputStream stream) throws IOException {\n" +
2938
			"        return new BufferedInputStream(stream);\n" +
2939
			"    }\n" +
2940
			"}\n"
2941
		},
2942
		"----------\n" +
2943
		"1. ERROR in X.java (at line 7)\n" +
2944
		"	FileInputStream stream = new FileInputStream(file);\n" +
2945
		"	                ^^^^^^\n" +
2946
		"Resource leak: \'stream\' is never closed\n" +
2947
		"----------\n" +
2948
		"2. ERROR in X.java (at line 9)\n" +
2949
		"	FileInputStream stream2 = new FileInputStream(file); // unsure since passed to method\n" +
2950
		"	                ^^^^^^^\n" +
2951
		"Potential resource leak: \'stream2\' may not be closed\n" +
2952
		"----------\n" +
2953
		"3. ERROR in X.java (at line 10)\n" +
2954
		"	bis = getReader(stream2); // unsure since obtained from method\n" +
2955
		"	^^^^^^^^^^^^^^^^^^^^^^^^\n" +
2956
		"Potential resource leak: \'bis\' may not be closed\n" +
2957
		"----------\n",
2958
		null,
2959
		true,
2960
		options);
2961
}
2962
// Bug 362332 - Only report potential leak when closeable not created in the local scope
2963
// a wrapper is obtained from a field read
2964
public void test063b() throws IOException {
2965
	Map options = getCompilerOptions();
2966
	options.put(CompilerOptions.OPTION_ReportUnclosedCloseable, CompilerOptions.ERROR);
2967
	options.put(CompilerOptions.OPTION_ReportPotentiallyUnclosedCloseable, CompilerOptions.ERROR);
2968
	this.runConformTest(
2969
		new String[] {
2970
			"X.java",
2971
			"import java.io.FileInputStream;\n" +
2972
			"import java.io.BufferedInputStream;\n" +
2973
			"import java.io.IOException;\n" +
2974
			"public class X {\n" +
2975
			"    FileInputStream stream;\n" +
2976
			"    void read() throws IOException {\n" +
2977
			"        FileInputStream s = this.stream;\n" +
2978
			"        BufferedInputStream bis = new BufferedInputStream(s); // don't complain since s is obtained from a field\n" +
2979
			"        bis.available();\n" +
2980
			"    }\n" +
2981
			"}\n"
2982
		},
2983
		"",
2984
		null,
2985
		true,
2986
		null,
2987
		options,
2988
		null);
2989
}
2990
// Bug 362332 - Only report potential leak when closeable not created in the local scope
2991
// a wrapper is assigned to a field
2992
public void test063c() throws IOException {
2993
	Map options = getCompilerOptions();
2994
	options.put(CompilerOptions.OPTION_ReportUnclosedCloseable, CompilerOptions.ERROR);
2995
	options.put(CompilerOptions.OPTION_ReportPotentiallyUnclosedCloseable, CompilerOptions.ERROR);
2996
	this.runConformTest(
2997
		new String[] {
2998
			"X.java",
2999
			"import java.io.FileInputStream;\n" +
3000
			"import java.io.BufferedInputStream;\n" +
3001
			"import java.io.IOException;\n" +
3002
			"public class X {\n" +
3003
			"    BufferedInputStream stream;\n" +
3004
			"    void read() throws IOException {\n" +
3005
			"        FileInputStream s = new FileInputStream(\"somefile\");\n" +
3006
			"        BufferedInputStream bis = new BufferedInputStream(s);\n" +
3007
			"        this.stream = bis;\n" +
3008
			"    }\n" +
3009
			"}\n"
3010
		},
3011
		"",
3012
		null,
3013
		true,
3014
		null,
3015
		options,
3016
		null);
3017
}
3018
// Bug 362332 - Only report potential leak when closeable not created in the local scope
3019
// a resource is obtained as a method argument and/or assigned with a cast
3020
public void test063d() throws IOException {
3021
	Map options = getCompilerOptions();
3022
	options.put(CompilerOptions.OPTION_ReportUnclosedCloseable, CompilerOptions.ERROR);
3023
	options.put(CompilerOptions.OPTION_ReportPotentiallyUnclosedCloseable, CompilerOptions.ERROR);
3024
	options.put(CompilerOptions.OPTION_ReportExplicitlyClosedAutoCloseable, CompilerOptions.ERROR);
3025
	runTestsExpectingErrorsOnlyIn17(
3026
		new String[] {
3027
			"X.java",
3028
			"import java.io.FileInputStream;\n" +
3029
			"import java.io.BufferedInputStream;\n" +
3030
			"import java.io.InputStream;\n" +
3031
			"import java.io.IOException;\n" +
3032
			"public class X {\n" +
3033
			"    void foo( InputStream input) throws IOException {\n" +
3034
			"        FileInputStream input1  = (FileInputStream)input;\n" +
3035
			"        System.out.println(input1.read());\n" +
3036
			"        input.close();\n" + // don't propose t-w-r for argument
3037
			"    }\n" +
3038
			"    void foo() throws IOException {\n" +
3039
			"        InputStream input = new FileInputStream(\"somefile\");\n" +
3040
			"        FileInputStream input1  = (FileInputStream)input;\n" +
3041
			"        System.out.println(input1.read());\n" +
3042
			"        input.close();\n" + // do propose t-w-r, not from a method argument
3043
			"    }\n" +
3044
			"    void foo3( InputStream input, InputStream input2) throws IOException {\n" +
3045
			"        FileInputStream input1  = (FileInputStream)input;\n" + // still don't claim because obtained from outside
3046
			"        System.out.println(input1.read());\n" +
3047
			"        BufferedInputStream bis = new BufferedInputStream(input2);\n" +
3048
			"        System.out.println(bis.read());\n" +
3049
			"    }\n" +
3050
			"}\n"
3051
		},
3052
		"----------\n" +
3053
		"1. ERROR in X.java (at line 12)\n" +
3054
		"	InputStream input = new FileInputStream(\"somefile\");\n" +
3055
		"	            ^^^^^\n" +
3056
		"Resource \'input\' should be managed by try-with-resource\n" +
3057
		"----------\n",
3058
		options);
3059
}
3060
// Bug 362332 - Only report potential leak when closeable not created in the local scope
3061
// a resource is obtained from a field read, then re-assigned
3062
public void test063e() {
3063
	Map options = getCompilerOptions();
3064
	options.put(CompilerOptions.OPTION_ReportUnclosedCloseable, CompilerOptions.ERROR);
3065
	options.put(CompilerOptions.OPTION_ReportPotentiallyUnclosedCloseable, CompilerOptions.ERROR);
3066
	this.runConformTest(
3067
		new String[] {
3068
			"X.java",
3069
			"import java.io.FileInputStream;\n" +
3070
			"import java.io.IOException;\n" +
3071
			"public class X {\n" +
3072
			"    FileInputStream input1;\n" +
3073
			"    public void foo() throws IOException {\n" +
3074
			"        FileInputStream input = input1;\n" +
3075
			"        input = new FileInputStream(\"adfafd\");\n" +
3076
			"        input.close();\n" +
3077
			"    }\n" +
3078
			"}\n"
3079
		},
3080
		"",
3081
		null,
3082
		true,
3083
		null,
3084
		options,
3085
		null);
3086
}
3087
// Bug 368709 - Endless loop in FakedTrackingVariable.markPassedToOutside
3088
// original test case from jgit
3089
public void testBug368709a() {
3090
	if (this.complianceLevel < ClassFileConstants.JDK1_5) return;
3091
	Map options = getCompilerOptions();
3092
	options.put(CompilerOptions.OPTION_ReportUnclosedCloseable, CompilerOptions.ERROR);
3093
	options.put(CompilerOptions.OPTION_ReportPotentiallyUnclosedCloseable, CompilerOptions.ERROR);
3094
	this.runNegativeTest(
3095
		new String[] {
3096
			"X.java",
3097
			"import java.io.*;\n" +
3098
			"import java.util.zip.*;\n" +
3099
			"public class X {\n" +
3100
			"  Object db, pack;\n" + // mock
3101
			"  int objectOffset, headerLength, type, size;\n" +
3102
			"  public ObjectStream openStream() throws MissingObjectException, IOException {\n" +
3103
			"    WindowCursor wc = new WindowCursor(db);\n" +
3104
			"    InputStream in;\n" +
3105
			"    try\n" +
3106
			"      {\n" +
3107
			"        in = new PackInputStream(pack, (objectOffset + headerLength), wc);\n" +
3108
			"      }\n" +
3109
			"    catch (IOException packGone)\n" +
3110
			"      {\n" +
3111
			"        return wc.open(getObjectId(), type).openStream();\n" +
3112
			"      }\n" +
3113
			"    in = new BufferedInputStream(new InflaterInputStream(in, wc.inflater(), 8192), 8192);\n" +
3114
			"    return new ObjectStream.Filter(type, size, in);\n" +
3115
			"  }\n" +
3116
			"  String getObjectId() { return \"\"; }\n" + // mock
3117
			"}\n" +
3118
			// mock:
3119
			"class WindowCursor {\n" +
3120
			"    WindowCursor(Object db) {}\n" +
3121
			"    ObjectStream open(String id, int type) { return null; }\n" +
3122
			"    Inflater inflater() { return null; }\n" +
3123
			"}\n" +
3124
			"class MissingObjectException extends Exception {\n" +
3125
			"    public static final long serialVersionUID = 13L;\n" +
3126
			"    MissingObjectException() { super();}\n" +
3127
			"}\n" +
3128
			"class PackInputStream extends InputStream {\n" +
3129
			"    PackInputStream(Object pack, int offset, WindowCursor wc) throws IOException {}\n" +
3130
			"    public int read() { return 0; }\n" +
3131
			"}\n" +
3132
			"class ObjectStream extends InputStream {\n" +
3133
			"    static class Filter extends ObjectStream {\n" +
3134
			"        Filter(int type, int size, InputStream in) { }\n" +
3135
			"    }\n" +
3136
			"    ObjectStream openStream() { return this; }\n" +
3137
			"    public int read() { return 0; }\n" +
3138
			"}\n"
3139
		},
3140
		"----------\n" +
3141
		"1. ERROR in X.java (at line 18)\n" +
3142
		"	return new ObjectStream.Filter(type, size, in);\n" +
3143
		"	^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^\n" +
3144
		"Potential resource leak: \'in\' may not be closed at this location\n" +
3145
		"----------\n",
3146
		null,
3147
		true,
3148
		options);
3149
}
3150
// Bug 368709 - Endless loop in FakedTrackingVariable.markPassedToOutside
3151
// minimal test case: constructing an indirect self-wrapper
3152
public void testBug368709b() {
3153
	if (this.complianceLevel < ClassFileConstants.JDK1_5) return;
3154
	Map options = getCompilerOptions();
3155
	options.put(CompilerOptions.OPTION_ReportUnclosedCloseable, CompilerOptions.ERROR);
3156
	options.put(CompilerOptions.OPTION_ReportPotentiallyUnclosedCloseable, CompilerOptions.ERROR);
3157
	this.runNegativeTest(
3158
		new String[] {
3159
			"X.java",
3160
			"import java.io.*;\n" +
3161
			"import java.util.zip.*;\n" +
3162
			"public class X {\n" +
3163
			"  void doit() throws IOException {\n" +
3164
			"    InputStream in = new FileInputStream(\"somefile\");\n" +
3165
			"    in = new BufferedInputStream(new InflaterInputStream(in, inflater(), 8192), 8192);\n" +
3166
			"    process(in);\n" +
3167
			"  }\n" +
3168
			"  Inflater inflater() { return null; }\n" +
3169
			"  void process(InputStream is) { }\n" +
3170
			"}\n"
3171
		},
3172
		"----------\n" +
3173
		"1. ERROR in X.java (at line 5)\n" +
3174
		"	InputStream in = new FileInputStream(\"somefile\");\n" +
3175
		"	            ^^\n" +
3176
		"Potential resource leak: \'in\' may not be closed\n" +
3177
		"----------\n",
3178
		null,
3179
		true,
3180
		options);
3181
}
3182
3183
// Bug 368546 - [compiler][resource] Avoid remaining false positives found when compiling the Eclipse SDK
3184
// example from comment 3
3185
public void test064() {
3186
	Map options = getCompilerOptions();
3187
	options.put(CompilerOptions.OPTION_ReportUnclosedCloseable, CompilerOptions.ERROR);
3188
	options.put(CompilerOptions.OPTION_ReportPotentiallyUnclosedCloseable, CompilerOptions.ERROR);
3189
	this.runNegativeTest(new String[] {
3190
		"Test064.java",
3191
		"import java.io.*;\n" +
3192
		"public class Test064 {\n" +
3193
		"    void foo(File outfile) {\n" + 
3194
		"        OutputStream out= System.out;\n" + 
3195
		"        if (outfile != null) {\n" + 
3196
		"            try {\n" + 
3197
		"                out = new FileOutputStream(outfile);\n" + 
3198
		"            } catch (java.io.IOException e) {\n" + 
3199
		"                throw new RuntimeException(e);\n" + 
3200
		"            }\n" + 
3201
		"        }\n" + 
3202
		"        setOutput(out);\n" + 
3203
		"    }\n" + 
3204
		"    private void setOutput(OutputStream out) { }\n" +
3205
		"}\n"
3206
	},
3207
	"----------\n" + 
3208
	"1. ERROR in Test064.java (at line 7)\n" + 
3209
	"	out = new FileOutputStream(outfile);\n" + 
3210
	"	^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^\n" + 
3211
	"Potential resource leak: \'out\' may not be closed\n" + 
3212
	"----------\n",
3213
	null,
3214
	true,
3215
	options);
3216
}
3217
// Bug 368546 - [compiler][resource] Avoid remaining false positives found when compiling the Eclipse SDK
3218
// example from comment 10
3219
// disabled, because basic null-analysis machinery doesn't support this pattern
3220
// see also Bug 370424 - [compiler][null] throw-catch analysis for null flow could be more precise
3221
public void _test065() {
3222
	Map options = getCompilerOptions();
3223
	options.put(CompilerOptions.OPTION_ReportUnclosedCloseable, CompilerOptions.ERROR);
3224
	options.put(CompilerOptions.OPTION_ReportPotentiallyUnclosedCloseable, CompilerOptions.ERROR);
3225
	options.put(CompilerOptions.OPTION_ReportMissingSerialVersion, CompilerOptions.IGNORE);
3226
	this.runConformTest(new String[] {
3227
		"Test065.java",
3228
		"import java.io.*;\n" +
3229
		"class MyException extends Exception{}\n" + 
3230
		"public class Test065 {\n" +
3231
		"	void foo(String fileName) throws IOException, MyException {\n" + 
3232
		"		FileReader       fileRead   = new FileReader(fileName);\n" + 
3233
		"		BufferedReader   bufRead    = new BufferedReader(fileRead);\n" + 
3234
		"		LineNumberReader lineReader = new LineNumberReader(bufRead);\n" + 
3235
		"		try {\n" + 
3236
		"		while (lineReader.readLine() != null) {\n" + 
3237
		"			bufRead.close();\n" + 
3238
		"			callSome();  // only this can throw MyException\n" + 
3239
		"		}\n" + 
3240
		"		} catch (MyException e) {\n" + 
3241
		"			throw e;  // Pot. leak reported here\n" + 
3242
		"		}\n" + 
3243
		"		bufRead.close(); \n" + 
3244
		"	}\n" + 
3245
		"	private void callSome() throws MyException\n" + 
3246
		"	{\n" + 
3247
		"		\n" + 
3248
		"	}\n" + 
3249
		"}\n"
3250
	},
3251
	"",
3252
	null,
3253
	true,
3254
	null,
3255
	options,
3256
	null);
3257
}
3258
3259
// Bug 368546 - [compiler][resource] Avoid remaining false positives found when compiling the Eclipse SDK
3260
// example from comment 11
3261
public void test066() {
3262
	Map options = getCompilerOptions();
3263
	options.put(CompilerOptions.OPTION_ReportUnclosedCloseable, CompilerOptions.ERROR);
3264
	options.put(CompilerOptions.OPTION_ReportPotentiallyUnclosedCloseable, CompilerOptions.ERROR);
3265
	options.put(CompilerOptions.OPTION_ReportMissingSerialVersion, CompilerOptions.IGNORE);
3266
	this.runNegativeTest(new String[] {
3267
		"Test066.java",
3268
		"import java.io.*;\n" +
3269
		"class MyException extends Exception{}\n" + 
3270
		"public class Test066 {\n" +
3271
		"    void countFileLines(String fileName) throws IOException {\n" + 
3272
		"		FileReader       fileRead   = new FileReader(fileName);\n" + 
3273
		"		BufferedReader   bufRead    = new BufferedReader(fileRead);\n" + 
3274
		"		LineNumberReader lineReader = new LineNumberReader(bufRead);\n" + 
3275
		"		while (lineReader.readLine() != null) {\n" + 
3276
		"			if (lineReader.markSupported())\n" +
3277
		"               throw new IOException();\n" + 
3278
		"			bufRead.close();\n" + 
3279
		"		}\n" + 
3280
		"		bufRead.close();\n" + 
3281
		"	}\n" + 
3282
		"}\n"
3283
	},
3284
	"----------\n" + 
3285
	"1. ERROR in Test066.java (at line 10)\n" + 
3286
	"	throw new IOException();\n" + 
3287
	"	^^^^^^^^^^^^^^^^^^^^^^^^\n" + 
3288
	"Potential resource leak: \'lineReader\' may not be closed at this location\n" + 
3289
	"----------\n",
3290
	null,
3291
	true,
3292
	options);
3293
}
3294
// Bug 368546 - [compiler][resource] Avoid remaining false positives found when compiling the Eclipse SDK
3295
// example from comment 11 - variant with closing top-level resource 
3296
public void test066b() {
3297
	Map options = getCompilerOptions();
3298
	options.put(CompilerOptions.OPTION_ReportUnclosedCloseable, CompilerOptions.ERROR);
3299
	options.put(CompilerOptions.OPTION_ReportPotentiallyUnclosedCloseable, CompilerOptions.ERROR);
3300
	options.put(CompilerOptions.OPTION_ReportMissingSerialVersion, CompilerOptions.IGNORE);
3301
	this.runNegativeTest(new String[] {
3302
		"Test066.java",
3303
		"import java.io.*;\n" +
3304
		"class MyException extends Exception{}\n" + 
3305
		"public class Test066 {\n" +
3306
		"    void countFileLines(String fileName) throws IOException {\n" + 
3307
		"		FileReader       fileRead   = new FileReader(fileName);\n" + 
3308
		"		BufferedReader   bufRead    = new BufferedReader(fileRead);\n" + 
3309
		"		LineNumberReader lineReader = new LineNumberReader(bufRead);\n" + 
3310
		"		while (lineReader.readLine() != null) {\n" + 
3311
		"			if (lineReader.markSupported())\n" +
3312
		"               throw new IOException();\n" + 
3313
		"			lineReader.close();\n" + 
3314
		"		}\n" + 
3315
		"		lineReader.close();\n" + 
3316
		"	}\n" + 
3317
		"}\n"
3318
	},
3319
	"----------\n" + 
3320
	"1. ERROR in Test066.java (at line 10)\n" + 
3321
	"	throw new IOException();\n" + 
3322
	"	^^^^^^^^^^^^^^^^^^^^^^^^\n" + 
3323
	"Potential resource leak: \'lineReader\' may not be closed at this location\n" + 
3324
	"----------\n",
3325
	null,
3326
	true,
3327
	options);
3328
}
3329
3330
// Bug 368546 - [compiler][resource] Avoid remaining false positives found when compiling the Eclipse SDK
3331
// example from comment 12
3332
// disabled because null info after try-catch is too weak,
3333
// see also Bug 370424 - [compiler][null] throw-catch analysis for null flow could be more precise
3334
public void _test067() {
3335
	Map options = getCompilerOptions();
3336
	options.put(CompilerOptions.OPTION_ReportUnclosedCloseable, CompilerOptions.ERROR);
3337
	options.put(CompilerOptions.OPTION_ReportPotentiallyUnclosedCloseable, CompilerOptions.ERROR);
3338
	options.put(CompilerOptions.OPTION_ReportMissingSerialVersion, CompilerOptions.IGNORE);
3339
	this.runConformTest(new String[] {
3340
		"Test067.java",
3341
		"import java.io.*;\n" +
3342
		"public class Test067 {\n" +
3343
		"	public void comment12() throws IOException {\n" + 
3344
		"    	LineNumberReader o = null;\n" + 
3345
		"    	try {\n" + 
3346
		"    		o = new LineNumberReader(null);    		\n" + 
3347
		"    	} catch (NumberFormatException e) {    		\n" + 
3348
		"    	}\n" + 
3349
		"    }\n" + 
3350
		"}\n"
3351
	},
3352
	"",
3353
	null,
3354
	true,
3355
	null,
3356
	options,
3357
	null);
3358
}
3359
3360
// Bug 368546 - [compiler][resource] Avoid remaining false positives found when compiling the Eclipse SDK
3361
// example from comment 12
3362
// disabled because null info after try-catch is too weak,
3363
// see also Bug 370424 - [compiler][null] throw-catch analysis for null flow could be more precise
3364
public void _test067b() {
3365
	Map options = getCompilerOptions();
3366
	options.put(CompilerOptions.OPTION_ReportUnclosedCloseable, CompilerOptions.ERROR);
3367
	options.put(CompilerOptions.OPTION_ReportPotentiallyUnclosedCloseable, CompilerOptions.ERROR);
3368
	options.put(CompilerOptions.OPTION_ReportMissingSerialVersion, CompilerOptions.IGNORE);
3369
	this.runConformTest(new String[] {
3370
		"Test067.java",
3371
		"import java.io.*;\n" +
3372
		"public class Test067 {\n" +
3373
		"	public void comment12b() throws IOException {\n" + 
3374
		"		LineNumberReader o = new LineNumberReader(null);\n" + 
3375
		"    	try {\n" + 
3376
		"    		o.close();\n" + 
3377
		"    	} catch (NumberFormatException e) {\n" + 
3378
		"    	}\n" + 
3379
		"    }\n" + 
3380
		"}\n"
3381
	},
3382
	"",
3383
	null,
3384
	true,
3385
	null,
3386
	options,
3387
	null);
3388
}
3389
3390
// Bug 368546 - [compiler][resource] Avoid remaining false positives found when compiling the Eclipse SDK
3391
// example from comment 13
3392
public void test068() {
3393
	Map options = getCompilerOptions();
3394
	options.put(CompilerOptions.OPTION_ReportUnclosedCloseable, CompilerOptions.ERROR);
3395
	options.put(CompilerOptions.OPTION_ReportPotentiallyUnclosedCloseable, CompilerOptions.ERROR);
3396
	options.put(CompilerOptions.OPTION_ReportMissingSerialVersion, CompilerOptions.IGNORE);
3397
	this.runConformTest(new String[] {
3398
		"Test068.java",
3399
		"import java.io.*;\n" +
3400
		"public class Test068 {\n" +
3401
		"	class ProcessingStep extends OutputStream {\n" + 
3402
		"		public void write(int b) throws IOException {}\n" + 
3403
		"		public OutputStream getDestination() { return null; }\n" + 
3404
		"	}\n" + 
3405
		"	class ArtifactOutputStream  extends OutputStream {\n" + 
3406
		"		public void write(int b) throws IOException {}\n" + 
3407
		"	}" +
3408
		"	ArtifactOutputStream comment13(OutputStream stream) {\n" + 
3409
		"		OutputStream current = stream;\n" + 
3410
		"		while (current instanceof ProcessingStep)\n" + 
3411
		"			current = ((ProcessingStep) current).getDestination();\n" +  // we previously saw a bogus warning here. 
3412
		"		if (current instanceof ArtifactOutputStream)\n" + 
3413
		"			return (ArtifactOutputStream) current;\n" + 
3414
		"		return null;\n" + 
3415
		"	}\n" + 
3416
		"}\n"
3417
	},
3418
	"",
3419
	null,
3420
	true,
3421
	null,
3422
	options,
3423
	null);
3424
}
3425
3426
// Bug 368546 - [compiler][resource] Avoid remaining false positives found when compiling the Eclipse SDK
3427
// example from comment 16
3428
public void test069() {
3429
	if (this.complianceLevel < ClassFileConstants.JDK1_5) return; // generics used
3430
	Map options = getCompilerOptions();
3431
	options.put(CompilerOptions.OPTION_ReportUnclosedCloseable, CompilerOptions.ERROR);
3432
	options.put(CompilerOptions.OPTION_ReportPotentiallyUnclosedCloseable, CompilerOptions.ERROR);
3433
	options.put(CompilerOptions.OPTION_ReportMissingSerialVersion, CompilerOptions.IGNORE);
3434
	this.runConformTest(new String[] {
3435
		"Test069.java",
3436
		"import java.io.*;\n" +
3437
		"import java.util.Collection;\n" +
3438
		"public class Test069 {\n" +
3439
		"	class Profile {}\n" + 
3440
		"	class CoreException extends Exception {}\n" + 
3441
		"	void writeProfilesToStream(Collection<Profile> p, OutputStream s, String enc) {}\n" + 
3442
		"	CoreException createException(IOException ioex, String message) { return new CoreException(); }\n" + 
3443
		"	public void comment16(Collection<Profile> profiles, File file, String encoding) throws CoreException {\n" + 
3444
		"		final OutputStream stream;\n" + 
3445
		"		try {\n" + 
3446
		"			stream= new FileOutputStream(file);\n" + 
3447
		"			try {\n" + 
3448
		"				writeProfilesToStream(profiles, stream, encoding);\n" + 
3449
		"			} finally {\n" + 
3450
		"				try { stream.close(); } catch (IOException e) { /* ignore */ }\n" + 
3451
		"			}\n" + 
3452
		"		} catch (IOException e) {\n" + 
3453
		"			throw createException(e, \"message\"); // should not shout here\n" + 
3454
		"		}\n" + 
3455
		"	}\n" + 
3456
		"}\n"
3457
	},
3458
	"",
3459
	null,
3460
	true,
3461
	null,
3462
	options,
3463
	null);
3464
}
3465
3466
// Bug 368546 - [compiler][resource] Avoid remaining false positives found when compiling the Eclipse SDK
3467
// referenced in array initializer 
3468
public void test070() {
3469
	Map options = getCompilerOptions();
3470
	options.put(CompilerOptions.OPTION_ReportUnclosedCloseable, CompilerOptions.ERROR);
3471
	options.put(CompilerOptions.OPTION_ReportPotentiallyUnclosedCloseable, CompilerOptions.ERROR);
3472
	options.put(CompilerOptions.OPTION_ReportMissingSerialVersion, CompilerOptions.IGNORE);
3473
	this.runNegativeTest(new String[] {
3474
		"Test070.java",
3475
		"import java.io.*;\n" +
3476
		"public class Test070 {\n" +
3477
		"    void storeInArray(String fileName) throws IOException {\n" + 
3478
		"		FileReader       fileRead   = new FileReader(fileName);\n" + 
3479
		"		closeThemAll(new FileReader[] { fileRead });\n" + 
3480
		"	}\n" +
3481
		"   void closeThemAll(FileReader[] readers) { }\n" + 
3482
		"}\n"
3483
	},
3484
	"----------\n" + 
3485
	"1. ERROR in Test070.java (at line 4)\n" + 
3486
	"	FileReader       fileRead   = new FileReader(fileName);\n" + 
3487
	"	                 ^^^^^^^^\n" + 
3488
	"Potential resource leak: \'fileRead\' may not be closed\n" + 
3489
	"----------\n",
3490
	null,
3491
	true,
3492
	options);
3493
}
3494
3495
// Bug 368546 - [compiler][resource] Avoid remaining false positives found when compiling the Eclipse SDK
3496
// referenced in array initializer 
3497
public void test071() {
3498
	Map options = getCompilerOptions();
3499
	options.put(CompilerOptions.OPTION_ReportUnclosedCloseable, CompilerOptions.ERROR);
3500
	options.put(CompilerOptions.OPTION_ReportPotentiallyUnclosedCloseable, CompilerOptions.ERROR);
3501
	options.put(CompilerOptions.OPTION_ReportMissingSerialVersion, CompilerOptions.IGNORE);
3502
	this.runNegativeTest(new String[] {
3503
		"Test071.java",
3504
		"import java.io.*;\n" +
3505
		"public class Test071 {\n" +
3506
		"    class ReaderHolder {\n" + 
3507
		"		FileReader reader;\n" + 
3508
		"	}\n" + 
3509
		"	private FileReader getReader() {\n" + 
3510
		"		return null;\n" + 
3511
		"	}\n" + 
3512
		"	void invokeCompiler(ReaderHolder readerHolder, boolean flag) throws FileNotFoundException {\n" + 
3513
		"		FileReader reader = readerHolder.reader;\n" + 
3514
		"		if (reader == null)\n" + 
3515
		"			reader = getReader();\n" + 
3516
		"		try {\n" + 
3517
		"			return;\n" + 
3518
		"		} finally {\n" + 
3519
		"			try {\n" + 
3520
		"				if (flag)\n" + 
3521
		"					reader.close();\n" + 
3522
		"			} catch (IOException e) {\n" + 
3523
		"				// nop\n" + 
3524
		"			}\n" + 
3525
		"		}\n" + 
3526
		"	}\n" + 
3527
		"}\n"
3528
	},
3529
	"----------\n" + 
3530
	"1. ERROR in Test071.java (at line 14)\n" + 
3531
	"	return;\n" + 
3532
	"	^^^^^^^\n" + 
3533
	"Potential resource leak: \'reader\' may not be closed at this location\n" + 
3534
	"----------\n",
3535
	null,
3536
	true,
3537
	options);
3538
}
3539
3540
// Bug 368546 - [compiler][resource] Avoid remaining false positives found when compiling the Eclipse SDK
3541
// referenced in array initializer
3542
// disabled because it would require correlation analysis between the tracking variable and its original
3543
// need to pass to downstream: either (nonnull & open) or (null)
3544
public void _test071b() {
3545
	Map options = getCompilerOptions();
3546
	options.put(CompilerOptions.OPTION_ReportUnclosedCloseable, CompilerOptions.ERROR);
3547
	options.put(CompilerOptions.OPTION_ReportPotentiallyUnclosedCloseable, CompilerOptions.ERROR);
3548
	options.put(CompilerOptions.OPTION_ReportMissingSerialVersion, CompilerOptions.IGNORE);
3549
	this.runNegativeTest(new String[] {
3550
		"Test071b.java",
3551
		"import java.io.*;\n" +
3552
		"public class Test071b {\n" +
3553
		"   private FileReader getReader() {\n" + 
3554
		"		return null;\n" + 
3555
		"	}\n" + 
3556
		"	void invokeCompiler(boolean flag) throws FileNotFoundException {\n" + 
3557
		"		FileReader reader = null;\n" + 
3558
		"		if (flag)\n" + 
3559
		"			reader = new FileReader(\"file\");\n" + 
3560
		"		if (reader == null)\n" + 
3561
		"			reader = getReader();\n" + 
3562
		"		try {\n" + 
3563
		"			return;\n" + 
3564
		"		} finally {\n" + 
3565
		"			try {\n" + 
3566
		"				if (flag)\n" + 
3567
		"					reader.close();\n" + 
3568
		"			} catch (IOException e) {\n" + 
3569
		"				// nop\n" + 
3570
		"			}\n" + 
3571
		"		}\n" + 
3572
		"	}\n" + 
3573
		"}\n"
3574
	},
3575
	"----------\n" + 
3576
	"1. ERROR in Test071b.java (at line 13)\n" + 
3577
	"	return;\n" + 
3578
	"	^^^^^^^\n" + 
3579
	"Potential resource leak: \'reader\' may not be closed at this location\n" + 
3580
	"----------\n",
3581
	null,
3582
	true,
3583
	options);
3584
}
3585
3586
// Bug 368546 - [compiler][resource] Avoid remaining false positives found when compiling the Eclipse SDK
3587
// throw inside loop inside try - while closed in finally
3588
public void test072() {
3589
	Map options = getCompilerOptions();
3590
	options.put(CompilerOptions.OPTION_ReportUnclosedCloseable, CompilerOptions.ERROR);
3591
	options.put(CompilerOptions.OPTION_ReportPotentiallyUnclosedCloseable, CompilerOptions.ERROR);
3592
	options.put(CompilerOptions.OPTION_ReportMissingSerialVersion, CompilerOptions.IGNORE);
3593
	this.runConformTest(new String[] {
3594
		"Test072.java",
3595
		"import java.io.*;\n" +
3596
		"public class Test072 {\n" +
3597
		"   void readState(File file) {\n" + 
3598
		"		DataInputStream in = null;\n" + 
3599
		"		try {\n" + 
3600
		"			in= new DataInputStream(new BufferedInputStream(new FileInputStream(file)));\n" + 
3601
		"			int sizeOfFlags = in.readInt();\n" + 
3602
		"			for (int i = 0; i < sizeOfFlags; ++i) {\n" + 
3603
		"				String childPath = in.readUTF();\n" + 
3604
		"				if (childPath.length() == 0)\n" + 
3605
		"					throw new IOException();\n" + 
3606
		"			}\n" + 
3607
		"		}\n" + 
3608
		"		catch (IOException ioe) { /* nop */ }\n" + 
3609
		"		finally {\n" + 
3610
		"			if (in != null) {\n" + 
3611
		"				try {in.close();} catch (IOException ioe) {}\n" + 
3612
		"			}\n" + 
3613
		"		}\n" + 
3614
		"	}\n" + 
3615
		"}\n"
3616
	},
3617
	"",
3618
	null,
3619
	true,
3620
	null,
3621
	options,
3622
	null);
3623
}
3624
3625
// Bug 368546 - [compiler][resource] Avoid remaining false positives found when compiling the Eclipse SDK
3626
// unspecific parameter is casted into a resource, yet need to mark as OWNED_BY_OUTSIDE
3627
public void test073() {
3628
	Map options = getCompilerOptions();
3629
	options.put(CompilerOptions.OPTION_ReportUnclosedCloseable, CompilerOptions.ERROR);
3630
	options.put(CompilerOptions.OPTION_ReportPotentiallyUnclosedCloseable, CompilerOptions.ERROR);
3631
	options.put(CompilerOptions.OPTION_ReportMissingSerialVersion, CompilerOptions.IGNORE);
3632
	this.runConformTest(new String[] {
3633
		"Test073.java",
3634
		"import java.io.*;\n" +
3635
		"public class Test073 {\n" +
3636
		"   String getEncoding(Object reader) {\n" + 
3637
		"		if (reader instanceof FileReader) {\n" + 
3638
		"			final FileReader fr = (FileReader) reader;\n" + 
3639
		"			return fr.getEncoding();\n" + 
3640
		"		}\n" + 
3641
		"		return null;\n" + 
3642
		"	}\n" + 
3643
		"}\n"
3644
	},
3645
	"",
3646
	null,
3647
	true,
3648
	null,
3649
	options,
3650
	null);
3651
}
3652
3653
// Bug 368546 - [compiler][resource] Avoid remaining false positives found when compiling the Eclipse SDK
3654
// status after nested try-finally
3655
public void test074() {
3656
	Map options = getCompilerOptions();
3657
	options.put(CompilerOptions.OPTION_ReportUnclosedCloseable, CompilerOptions.ERROR);
3658
	options.put(CompilerOptions.OPTION_ReportPotentiallyUnclosedCloseable, CompilerOptions.ERROR);
3659
	options.put(CompilerOptions.OPTION_ReportMissingSerialVersion, CompilerOptions.IGNORE);
3660
	this.runNegativeTest(new String[] {
3661
		"Test074.java",
3662
		"import java.io.*;\n" +
3663
		"public class Test074 {\n" +
3664
		"   void foo() throws FileNotFoundException {\n" + 
3665
		"		FileOutputStream out = null;\n" + 
3666
		"		try {\n" + 
3667
		"			out = new FileOutputStream(\"outfile\");\n" + 
3668
		"		} finally {\n" + 
3669
		"			try {\n" + 
3670
		"				out.flush();\n" + 
3671
		"				out.close();\n" + 
3672
		"			} catch (IOException e) {\n" + 
3673
		"				e.printStackTrace();\n" + 
3674
		"			}\n" + 
3675
		"			out = null;\n" + // unclosed if exception occurred on flush()
3676
		"		}\n" + 
3677
		"	}\n" + 
3678
		"}\n"
3679
	},
3680
	"----------\n" + 
3681
	"1. ERROR in Test074.java (at line 14)\n" + 
3682
	"	out = null;\n" + 
3683
	"	^^^^^^^^^^\n" + 
3684
	"Potential resource leak: \'out\' may not be closed at this location\n" + 
3685
	"----------\n",
3686
	null,
3687
	true,
3688
	options);
3689
}
3690
// Bug 370639 - [compiler][resource] restore the default for resource leak warnings
3691
// check that the default is warning
3692
public void test075() {
3693
	this.runNegativeTest(
3694
		new String[] {
3695
			"X.java",
3696
			"import java.io.File;\n" +
3697
			"import java.io.FileReader;\n" +
3698
			"import java.io.IOException;\n" +
3699
			"public class X {\n" +
3700
			"    void foo() throws IOException {\n" +
3701
			"        File file = new File(\"somefile\");\n" +
3702
			"        FileReader fileReader = new FileReader(file);\n" +
3703
			"    }\n" +
3704
			"}\n"
3705
		},
3706
		"----------\n" +
3707
		"1. WARNING in X.java (at line 7)\n" +
3708
		"	FileReader fileReader = new FileReader(file);\n" +
3709
		"	           ^^^^^^^^^^\n" +
3710
		"Resource leak: 'fileReader' is never closed\n" +
3711
		"----------\n");
3712
}
3713
}
(-)a/org.eclipse.jdt.core.tests.compiler/src/org/eclipse/jdt/core/tests/compiler/regression/ScannerTest.java (-1 / +17 lines)
Lines 31-37 Link Here
31
	// All specified tests which does not belong to the class are skipped...
31
	// All specified tests which does not belong to the class are skipped...
32
	static {
32
	static {
33
//		TESTS_NAMES = new String[] { "test000" };
33
//		TESTS_NAMES = new String[] { "test000" };
34
//		TESTS_NUMBERS = new int[] { 58 };
34
//		TESTS_NUMBERS = new int[] { 60 };
35
//		TESTS_RANGE = new int[] { 54, -1 };
35
//		TESTS_RANGE = new int[] { 54, -1 };
36
	}
36
	}
37
37
Lines 1290-1293 Link Here
1290
				"----------\n");
1290
				"----------\n");
1291
		}
1291
		}
1292
	}
1292
	}
1293
	//https://bugs.eclipse.org/bugs/show_bug.cgi?id=352553
1294
	public void test060() {
1295
		this.runNegativeTest(
1296
			new String[] {
1297
				"X.java",
1298
				"public class X {\n" + 
1299
				"	public static final String ERROR = \"\\u000Ⅻ\";\n" + 
1300
				"}"
1301
			},
1302
			"----------\n" + 
1303
			"1. ERROR in X.java (at line 2)\n" + 
1304
			"	public static final String ERROR = \"\\u000Ⅻ\";\n" + 
1305
			"	                                    ^^^^^^\n" + 
1306
			"Invalid unicode\n" + 
1307
			"----------\n");
1308
	}
1293
}
1309
}
(-)a/org.eclipse.jdt.core.tests.compiler/src/org/eclipse/jdt/core/tests/compiler/regression/StackMapAttributeTest.java (-2 / +816 lines)
Lines 1-5 Link Here
1
/*******************************************************************************
1
/*******************************************************************************
2
 * Copyright (c) 2006, 2011 IBM Corporation and others.
2
 * Copyright (c) 2006, 2012 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 19-24 Link Here
19
import org.eclipse.jdt.core.ToolFactory;
19
import org.eclipse.jdt.core.ToolFactory;
20
import org.eclipse.jdt.core.tests.util.Util;
20
import org.eclipse.jdt.core.tests.util.Util;
21
import org.eclipse.jdt.core.util.ClassFileBytesDisassembler;
21
import org.eclipse.jdt.core.util.ClassFileBytesDisassembler;
22
import org.eclipse.jdt.internal.compiler.classfmt.ClassFileConstants;
22
23
23
public class StackMapAttributeTest extends AbstractRegressionTest {
24
public class StackMapAttributeTest extends AbstractRegressionTest {
24
	public StackMapAttributeTest(String name) {
25
	public StackMapAttributeTest(String name) {
Lines 33-39 Link Here
33
	// All specified tests which does not belong to the class are skipped...
34
	// All specified tests which does not belong to the class are skipped...
34
	static {
35
	static {
35
//		TESTS_PREFIX = "testBug95521";
36
//		TESTS_PREFIX = "testBug95521";
36
//		TESTS_NAMES = new String[] { "testBug83127a" };
37
//		TESTS_NAMES = new String[] { "testBug359495" };
37
//		TESTS_NUMBERS = new int[] { 53 };
38
//		TESTS_NUMBERS = new int[] { 53 };
38
//		TESTS_RANGE = new int[] { 23 -1,};
39
//		TESTS_RANGE = new int[] { 23 -1,};
39
	}
40
	}
Lines 6802-6805 Link Here
6802
			},
6803
			},
6803
			"SUCCESS");
6804
			"SUCCESS");
6804
	}
6805
	}
6806
	
6807
	// https://bugs.eclipse.org/bugs/show_bug.cgi?id=359495
6808
	public void testBug359495a() throws Exception {
6809
		this.runConformTest(
6810
				new String[] {
6811
					"X.java",
6812
					"import java.util.List;\n" +
6813
					"import java.util.concurrent.locks.Lock;\n" +
6814
					"import java.util.Arrays;\n" +
6815
					"import java.util.concurrent.locks.ReentrantLock;\n" +
6816
					"public class X {\n" +
6817
					"	public static void main(String[] args) {\n" +
6818
					"		final Lock lock = new ReentrantLock();\n" +
6819
					"		final List<String> strings = Arrays.asList(args);\n" +
6820
					"		lock.lock();\n" +
6821
					"		try{\n" +
6822
					"			for (final String string:strings){\n" +
6823
					"				return;\n" +
6824
					"			}\n" +
6825
					"			return;\n" +
6826
					"		} finally {\n" +
6827
					"			lock.unlock();\n" +
6828
					"		}" +
6829
					"	}\n" +
6830
					"}",
6831
				},
6832
				"");
6833
6834
			ClassFileBytesDisassembler disassembler = ToolFactory.createDefaultClassFileBytesDisassembler();
6835
			byte[] classFileBytes = org.eclipse.jdt.internal.compiler.util.Util.getFileByteContent(new File(OUTPUT_DIR + File.separator  +"X.class"));
6836
			String actualOutput =
6837
				disassembler.disassemble(
6838
					classFileBytes,
6839
					"\n",
6840
					ClassFileBytesDisassembler.DETAILED);
6841
6842
			String expectedOutput =
6843
					"  // Method descriptor #15 ([Ljava/lang/String;)V\n" + 
6844
					"  // Stack: 2, Locals: 6\n" + 
6845
					"  public static void main(java.lang.String[] args);\n" + 
6846
					"     0  new java.util.concurrent.locks.ReentrantLock [16]\n" + 
6847
					"     3  dup\n" + 
6848
					"     4  invokespecial java.util.concurrent.locks.ReentrantLock() [18]\n" + 
6849
					"     7  astore_1 [lock]\n" + 
6850
					"     8  aload_0 [args]\n" + 
6851
					"     9  invokestatic java.util.Arrays.asList(java.lang.Object[]) : java.util.List [19]\n" + 
6852
					"    12  astore_2 [strings]\n" + 
6853
					"    13  aload_1 [lock]\n" + 
6854
					"    14  invokeinterface java.util.concurrent.locks.Lock.lock() : void [25] [nargs: 1]\n" + 
6855
					"    19  aload_2 [strings]\n" + 
6856
					"    20  invokeinterface java.util.List.iterator() : java.util.Iterator [30] [nargs: 1]\n" + 
6857
					"    25  astore 4\n" + 
6858
					"    27  aload 4\n" + 
6859
					"    29  invokeinterface java.util.Iterator.hasNext() : boolean [36] [nargs: 1]\n" + 
6860
					"    34  ifeq 55\n" + 
6861
					"    37  aload 4\n" + 
6862
					"    39  invokeinterface java.util.Iterator.next() : java.lang.Object [42] [nargs: 1]\n" + 
6863
					"    44  checkcast java.lang.String [46]\n" + 
6864
					"    47  astore_3 [string]\n" + 
6865
					"    48  aload_1 [lock]\n" + 
6866
					"    49  invokeinterface java.util.concurrent.locks.Lock.unlock() : void [48] [nargs: 1]\n" + 
6867
					"    54  return\n" + 
6868
					"    55  aload_1 [lock]\n" + 
6869
					"    56  invokeinterface java.util.concurrent.locks.Lock.unlock() : void [48] [nargs: 1]\n" + 
6870
					"    61  return\n" + 
6871
					"    62  astore 5\n" + 
6872
					"    64  aload_1 [lock]\n" + 
6873
					"    65  invokeinterface java.util.concurrent.locks.Lock.unlock() : void [48] [nargs: 1]\n" + 
6874
					"    70  aload 5\n" + 
6875
					"    72  athrow\n" + 
6876
					"      Exception Table:\n" + 
6877
					"        [pc: 19, pc: 48] -> 62 when : any\n" + 
6878
					"      Line numbers:\n" + 
6879
					"        [pc: 0, line: 7]\n" + 
6880
					"        [pc: 8, line: 8]\n" + 
6881
					"        [pc: 13, line: 9]\n" + 
6882
					"        [pc: 19, line: 11]\n" + 
6883
					"        [pc: 48, line: 16]\n" + 
6884
					"        [pc: 54, line: 12]\n" + 
6885
					"        [pc: 55, line: 16]\n" + 
6886
					"        [pc: 61, line: 14]\n" + 
6887
					"        [pc: 62, line: 15]\n" + 
6888
					"        [pc: 64, line: 16]\n" + 
6889
					"        [pc: 70, line: 17]\n" + 
6890
					"      Local variable table:\n" + 
6891
					"        [pc: 0, pc: 73] local: args index: 0 type: java.lang.String[]\n" + 
6892
					"        [pc: 8, pc: 73] local: lock index: 1 type: java.util.concurrent.locks.Lock\n" + 
6893
					"        [pc: 13, pc: 73] local: strings index: 2 type: java.util.List\n" + 
6894
					"        [pc: 48, pc: 55] local: string index: 3 type: java.lang.String\n" + 
6895
					"      Local variable type table:\n" + 
6896
					"        [pc: 13, pc: 73] local: strings index: 2 type: java.util.List<java.lang.String>\n" + 
6897
					"      Stack map table: number of frames 2\n" + 
6898
					"        [pc: 55, append: {java.util.concurrent.locks.Lock, java.util.List}]\n" + 
6899
					"        [pc: 62, same_locals_1_stack_item, stack: {java.lang.Throwable}]\n" ;
6900
6901
			int index = actualOutput.indexOf(expectedOutput);
6902
			if (index == -1 || expectedOutput.length() == 0) {
6903
				System.out.println(Util.displayString(actualOutput, 2));
6904
			}
6905
			if (index == -1) {
6906
				assertEquals("Wrong contents", expectedOutput, actualOutput);
6907
			}
6908
	}
6909
	
6910
	// https://bugs.eclipse.org/bugs/show_bug.cgi?id=359495
6911
	public void testBug359495b() throws Exception {
6912
		this.runConformTest(
6913
				new String[] {
6914
					"X.java",
6915
					"import java.util.List;\n" +
6916
					"import java.util.Iterator;\n" +
6917
					"import java.util.concurrent.locks.Lock;\n" +
6918
					"import java.util.Arrays;\n" +
6919
					"import java.util.concurrent.locks.ReentrantLock;\n" +
6920
					"public class X {\n" +
6921
					"	public static void main(String[] args) {\n" +
6922
					"		final Lock lock = new ReentrantLock();\n" +
6923
					"		final List<String> strings = Arrays.asList(args);\n" +
6924
					"		lock.lock();\n" +
6925
					"		try{\n" +
6926
					"			for (Iterator i = strings.iterator(); i.hasNext();){\n" +
6927
					"				return;\n" +
6928
					"			}\n" +
6929
					"			return;\n" +
6930
					"		} finally {\n" +
6931
					"			lock.unlock();\n" +
6932
					"		}" +
6933
					"	}\n" +
6934
					"}",
6935
				},
6936
				"");
6937
6938
			ClassFileBytesDisassembler disassembler = ToolFactory.createDefaultClassFileBytesDisassembler();
6939
			byte[] classFileBytes = org.eclipse.jdt.internal.compiler.util.Util.getFileByteContent(new File(OUTPUT_DIR + File.separator  +"X.class"));
6940
			String actualOutput =
6941
				disassembler.disassemble(
6942
					classFileBytes,
6943
					"\n",
6944
					ClassFileBytesDisassembler.DETAILED);
6945
6946
			String expectedOutput =
6947
					"  // Method descriptor #15 ([Ljava/lang/String;)V\n" + 
6948
					"  // Stack: 2, Locals: 5\n" + 
6949
					"  public static void main(java.lang.String[] args);\n" + 
6950
					"     0  new java.util.concurrent.locks.ReentrantLock [16]\n" + 
6951
					"     3  dup\n" + 
6952
					"     4  invokespecial java.util.concurrent.locks.ReentrantLock() [18]\n" + 
6953
					"     7  astore_1 [lock]\n" + 
6954
					"     8  aload_0 [args]\n" + 
6955
					"     9  invokestatic java.util.Arrays.asList(java.lang.Object[]) : java.util.List [19]\n" + 
6956
					"    12  astore_2 [strings]\n" + 
6957
					"    13  aload_1 [lock]\n" + 
6958
					"    14  invokeinterface java.util.concurrent.locks.Lock.lock() : void [25] [nargs: 1]\n" + 
6959
					"    19  aload_2 [strings]\n" + 
6960
					"    20  invokeinterface java.util.List.iterator() : java.util.Iterator [30] [nargs: 1]\n" + 
6961
					"    25  astore_3 [i]\n" + 
6962
					"    26  aload_3 [i]\n" + 
6963
					"    27  invokeinterface java.util.Iterator.hasNext() : boolean [36] [nargs: 1]\n" + 
6964
					"    32  ifeq 42\n" + 
6965
					"    35  aload_1 [lock]\n" + 
6966
					"    36  invokeinterface java.util.concurrent.locks.Lock.unlock() : void [42] [nargs: 1]\n" + 
6967
					"    41  return\n" + 
6968
					"    42  aload_1 [lock]\n" + 
6969
					"    43  invokeinterface java.util.concurrent.locks.Lock.unlock() : void [42] [nargs: 1]\n" + 
6970
					"    48  return\n" + 
6971
					"    49  astore 4\n" + 
6972
					"    51  aload_1 [lock]\n" + 
6973
					"    52  invokeinterface java.util.concurrent.locks.Lock.unlock() : void [42] [nargs: 1]\n" + 
6974
					"    57  aload 4\n" + 
6975
					"    59  athrow\n" + 
6976
					"      Exception Table:\n" + 
6977
					"        [pc: 19, pc: 35] -> 49 when : any\n" + 
6978
					"      Line numbers:\n" + 
6979
					"        [pc: 0, line: 8]\n" + 
6980
					"        [pc: 8, line: 9]\n" + 
6981
					"        [pc: 13, line: 10]\n" + 
6982
					"        [pc: 19, line: 12]\n" + 
6983
					"        [pc: 35, line: 17]\n" + 
6984
					"        [pc: 41, line: 13]\n" + 
6985
					"        [pc: 42, line: 17]\n" + 
6986
					"        [pc: 48, line: 15]\n" + 
6987
					"        [pc: 49, line: 16]\n" + 
6988
					"        [pc: 51, line: 17]\n" + 
6989
					"        [pc: 57, line: 18]\n" + 
6990
					"      Local variable table:\n" + 
6991
					"        [pc: 0, pc: 60] local: args index: 0 type: java.lang.String[]\n" + 
6992
					"        [pc: 8, pc: 60] local: lock index: 1 type: java.util.concurrent.locks.Lock\n" + 
6993
					"        [pc: 13, pc: 60] local: strings index: 2 type: java.util.List\n" + 
6994
					"        [pc: 26, pc: 42] local: i index: 3 type: java.util.Iterator\n" + 
6995
					"      Local variable type table:\n" + 
6996
					"        [pc: 13, pc: 60] local: strings index: 2 type: java.util.List<java.lang.String>\n" + 
6997
					"      Stack map table: number of frames 2\n" + 
6998
					"        [pc: 42, append: {java.util.concurrent.locks.Lock, java.util.List}]\n" + 
6999
					"        [pc: 49, same_locals_1_stack_item, stack: {java.lang.Throwable}]\n";
7000
7001
			int index = actualOutput.indexOf(expectedOutput);
7002
			if (index == -1 || expectedOutput.length() == 0) {
7003
				System.out.println(Util.displayString(actualOutput, 2));
7004
			}
7005
			if (index == -1) {
7006
				assertEquals("Wrong contents", expectedOutput, actualOutput);
7007
			}
7008
	}
7009
7010
	// https://bugs.eclipse.org/bugs/show_bug.cgi?id=362591
7011
	public void test055() throws Exception {
7012
		this.runConformTest(
7013
				new String[] {
7014
					"X.java",
7015
					"public class X {\n" + 
7016
					"	public static void main(String[] args) {\n" + 
7017
					"		testError(3, 4, \"d\");\n" + 
7018
					"	}\n" + 
7019
					"	public static void testError(Number n0, Number n1, String refValue) {\n" + 
7020
					"		Number result = refValue.equals(\"ttt\") ? n0 : (n1 == null ? null : n1.intValue());\n" + 
7021
					"		System.out.println(String.valueOf(result));\n" + 
7022
					"	}\n" + 
7023
					"}",
7024
				},
7025
				"4");
7026
7027
			ClassFileBytesDisassembler disassembler = ToolFactory.createDefaultClassFileBytesDisassembler();
7028
			byte[] classFileBytes = org.eclipse.jdt.internal.compiler.util.Util.getFileByteContent(new File(OUTPUT_DIR + File.separator  +"X.class"));
7029
			String actualOutput =
7030
				disassembler.disassemble(
7031
					classFileBytes,
7032
					"\n",
7033
					ClassFileBytesDisassembler.DETAILED);
7034
7035
			String expectedOutput =
7036
				"  // Method descriptor #27 (Ljava/lang/Number;Ljava/lang/Number;Ljava/lang/String;)V\n" + 
7037
				"  // Stack: 2, Locals: 4\n" + 
7038
				"  public static void testError(java.lang.Number n0, java.lang.Number n1, java.lang.String refValue);\n" + 
7039
				"     0  aload_2 [refValue]\n" + 
7040
				"     1  ldc <String \"ttt\"> [30]\n" + 
7041
				"     3  invokevirtual java.lang.String.equals(java.lang.Object) : boolean [32]\n" + 
7042
				"     6  ifeq 13\n" + 
7043
				"     9  aload_0 [n0]\n" + 
7044
				"    10  goto 28\n" + 
7045
				"    13  aload_1 [n1]\n" + 
7046
				"    14  ifnonnull 21\n" + 
7047
				"    17  aconst_null\n" + 
7048
				"    18  goto 28\n" + 
7049
				"    21  aload_1 [n1]\n" + 
7050
				"    22  invokevirtual java.lang.Number.intValue() : int [38]\n" + 
7051
				"    25  invokestatic java.lang.Integer.valueOf(int) : java.lang.Integer [16]\n" + 
7052
				"    28  astore_3 [result]\n" + 
7053
				"    29  getstatic java.lang.System.out : java.io.PrintStream [44]\n" + 
7054
				"    32  aload_3 [result]\n" + 
7055
				"    33  invokestatic java.lang.String.valueOf(java.lang.Object) : java.lang.String [50]\n" + 
7056
				"    36  invokevirtual java.io.PrintStream.println(java.lang.String) : void [53]\n" + 
7057
				"    39  return\n" + 
7058
				"      Line numbers:\n" + 
7059
				"        [pc: 0, line: 6]\n" + 
7060
				"        [pc: 29, line: 7]\n" + 
7061
				"        [pc: 39, line: 8]\n" + 
7062
				"      Local variable table:\n" + 
7063
				"        [pc: 0, pc: 40] local: n0 index: 0 type: java.lang.Number\n" + 
7064
				"        [pc: 0, pc: 40] local: n1 index: 1 type: java.lang.Number\n" + 
7065
				"        [pc: 0, pc: 40] local: refValue index: 2 type: java.lang.String\n" + 
7066
				"        [pc: 29, pc: 40] local: result index: 3 type: java.lang.Number\n" + 
7067
				"      Stack map table: number of frames 3\n" + 
7068
				"        [pc: 13, same]\n" + 
7069
				"        [pc: 21, same]\n" + 
7070
				"        [pc: 28, same_locals_1_stack_item, stack: {java.lang.Number}]\n";
7071
7072
			int index = actualOutput.indexOf(expectedOutput);
7073
			if (index == -1 || expectedOutput.length() == 0) {
7074
				System.out.println(Util.displayString(actualOutput, 2));
7075
			}
7076
			if (index == -1) {
7077
				assertEquals("Wrong contents", expectedOutput, actualOutput);
7078
			}
7079
	}
7080
	
7081
	public void test055a() throws Exception {
7082
		this.runConformTest(
7083
				new String[] {
7084
					"X.java",
7085
					"public class X {\n" +
7086
					"    public static void main(String[] args) {\n" +
7087
					"        Object o = args != null ? args : (args == null ? null : args.length);\n" +
7088
					"    }\n" +
7089
					"}\n",
7090
				},
7091
				"");
7092
	}
7093
	//https://bugs.eclipse.org/bugs/show_bug.cgi?id=366999
7094
	public void test056() throws Exception {
7095
		if (this.complianceLevel < ClassFileConstants.JDK1_7) return;
7096
		this.runConformTest(
7097
				new String[] {
7098
					"X.java",
7099
					"import java.io.BufferedReader;\n" + 
7100
					"import java.io.Closeable;\n" + 
7101
					"import java.io.File;\n" + 
7102
					"import java.io.FileReader;\n" + 
7103
					"import java.io.IOException;\n" + 
7104
					"\n" + 
7105
					"public class X {\n" + 
7106
					"\n" + 
7107
					"	static class C implements Closeable {\n" + 
7108
					"		@Override\n" + 
7109
					"		public void close() throws IOException {\n" + 
7110
					"			//\n" + 
7111
					"		}\n" + 
7112
					"	}\n" + 
7113
					"\n" + 
7114
					"	int run() throws IOException {\n" + 
7115
					"		int lcnt = 0;\n" + 
7116
					"		try (C c = new C();) {\n" + 
7117
					"			try (final BufferedReader br = new BufferedReader(new FileReader(\n" + 
7118
					"					new File(\"logging.properties\")))) {\n" + 
7119
					"				String s = null;\n" + 
7120
					"				while ((s = br.readLine()) != null)\n" + 
7121
					"					lcnt++;\n" + 
7122
					"				return lcnt;\n" + 
7123
					"			}\n" + 
7124
					"		} finally {\n" + 
7125
					"			System.out.println(\"read \" + lcnt + \" lines\");\n" + 
7126
					"		}\n" + 
7127
					"	}\n" + 
7128
					"\n" + 
7129
					"	public static void main(final String[] args) throws IOException {\n" + 
7130
					"		System.out.println(\"SUCCESS\");\n" + 
7131
					"	}\n" + 
7132
					"}",
7133
				},
7134
				"SUCCESS");
7135
	}
7136
	// https://bugs.eclipse.org/bugs/show_bug.cgi?id=367023
7137
	public void test057() throws Exception {
7138
		this.runConformTest(
7139
				new String[] {
7140
					"X.java",
7141
					"public class X {\n" +
7142
					"    public void run() {\n" +
7143
					"        String s;\n" +
7144
					"        label1: do {\n" +
7145
					"            for (;;) {\n" +
7146
					"                s = \"\";\n" +
7147
					"                if (s == null) \n" +
7148
					"                    continue label1;\n" +
7149
					"            }\n" +
7150
					"        } while (s != null);\n" +
7151
					"}\n" +
7152
					"    public static void main(String [] args) {\n" +
7153
					"		System.out.println(\"SUCCESS\");\n" +
7154
					"    }\n" +
7155
					"}\n",
7156
				},
7157
				"SUCCESS");
7158
	}
7159
	// https://bugs.eclipse.org/bugs/show_bug.cgi?id=367023
7160
	public void test058() throws Exception {
7161
		this.runConformTest(
7162
				new String[] {
7163
					"X.java",
7164
					"public class X {\n" +
7165
					"    public void run() {\n" +
7166
					"        String s;\n" +
7167
					"        label1: do {\n" +
7168
					"            for (;true;) {\n" +
7169
					"                s = \"\";\n" +
7170
					"                if (s == null) \n" +
7171
					"                    continue label1;\n" +
7172
					"            }\n" +
7173
					"        } while (s != null);\n" +
7174
					"}\n" +
7175
					"    public static void main(String [] args) {\n" +
7176
					"		System.out.println(\"SUCCESS\");\n" +
7177
					"    }\n" +
7178
					"}\n"				},
7179
				"SUCCESS");
7180
	}
7181
	// https://bugs.eclipse.org/bugs/show_bug.cgi?id=367023
7182
	public void test059() throws Exception {
7183
		this.runNegativeTest(
7184
				new String[] {
7185
					"X.java",
7186
					"public class X {\n" +
7187
					"    public void run() {\n" +
7188
					"        String s;\n" +
7189
					"        label1: do {\n" +
7190
					"            for (;false;) {\n" +
7191
					"                s = \"\";\n" +
7192
					"                if (s == null) \n" +
7193
					"                    continue label1;\n" +
7194
					"            }\n" +
7195
					"        } while (s != null);\n" +
7196
					"}\n" +
7197
					"    public static void main(String [] args) {\n" +
7198
					"		System.out.println(\"SUCCESS\");\n" +
7199
					"    }\n" +
7200
					"}\n"				},
7201
					"----------\n" + 
7202
					"1. WARNING in X.java (at line 4)\n" + 
7203
					"	label1: do {\n" + 
7204
					"	^^^^^^\n" + 
7205
					"The label label1 is never explicitly referenced\n" + 
7206
					"----------\n" + 
7207
					"2. ERROR in X.java (at line 5)\n" + 
7208
					"	for (;false;) {\n" + 
7209
					"                s = \"\";\n" + 
7210
					"                if (s == null) \n" + 
7211
					"                    continue label1;\n" + 
7212
					"            }\n" + 
7213
					"	              ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^\n" + 
7214
					"Unreachable code\n" + 
7215
					"----------\n" + 
7216
					"3. ERROR in X.java (at line 10)\n" + 
7217
					"	} while (s != null);\n" + 
7218
					"	         ^\n" + 
7219
					"The local variable s may not have been initialized\n" + 
7220
						"----------\n");
7221
	}	
7222
	// https://bugs.eclipse.org/bugs/show_bug.cgi?id=367023
7223
	public void test060() throws Exception {
7224
		this.runConformTest(
7225
				new String[] {
7226
					"X.java",
7227
					"public class X {\n" +
7228
					"    public void run() {\n" +
7229
					"        String s;\n" +
7230
					"        label1: do {\n" +
7231
					"            for (; 5 < 10;) {\n" +
7232
					"                s = \"\";\n" +
7233
					"                if (s == null) \n" +
7234
					"                    continue label1;\n" +
7235
					"            }\n" +
7236
					"        } while (s != null);\n" +
7237
					"}\n" +
7238
					"    public static void main(String [] args) {\n" +
7239
					"		System.out.println(\"SUCCESS\");\n" +
7240
					"    }\n" +
7241
					"}\n"				},
7242
				"SUCCESS");
7243
	}	
7244
	// https://bugs.eclipse.org/bugs/show_bug.cgi?id=367023
7245
	public void test061() throws Exception {
7246
		this.runNegativeTest(
7247
				new String[] {
7248
					"X.java",
7249
					"public class X {\n" +
7250
					"    public void run() {\n" +
7251
					"        int five = 5, ten = 10;\n" +
7252
					"        String s;\n" +
7253
					"        label1: do {\n" +
7254
					"            for (; five < ten;) {\n" +
7255
					"                s = \"\";\n" +
7256
					"                if (s == null) \n" +
7257
					"                    continue label1;\n" +
7258
					"            }\n" +
7259
					"        } while (s != null);\n" +
7260
					"}\n" +
7261
					"    public static void main(String [] args) {\n" +
7262
					"		System.out.println(\"SUCCESS\");\n" +
7263
					"    }\n" +
7264
					"}\n"				},
7265
					"----------\n" + 
7266
					"1. WARNING in X.java (at line 9)\n" + 
7267
					"	continue label1;\n" + 
7268
					"	^^^^^^^^^^^^^^^^\n" + 
7269
					"Dead code\n" + 
7270
					"----------\n" + 
7271
					"2. ERROR in X.java (at line 11)\n" + 
7272
					"	} while (s != null);\n" + 
7273
					"	         ^\n" + 
7274
					"The local variable s may not have been initialized\n" + 
7275
					"----------\n");
7276
	}
7277
	// https://bugs.eclipse.org/bugs/show_bug.cgi?id=367023
7278
	public void test062() throws Exception {
7279
		this.runConformTest(
7280
			new String[] {
7281
				"X.java",
7282
				"public class X {\n" +
7283
				"    public void run() {\n" +
7284
				"        final int five = 5, ten = 10;\n" +
7285
				"        String s;\n" +
7286
				"        label1: do {\n" +
7287
				"            for (; five < ten;) {\n" +
7288
				"                s = \"\";\n" +
7289
				"                if (s == null) \n" +
7290
				"                    continue label1;\n" +
7291
				"            }\n" +
7292
				"        } while (s != null);\n" +
7293
				"}\n" +
7294
				"    public static void main(String [] args) {\n" +
7295
				"		System.out.println(\"SUCCESS\");\n" +
7296
				"    }\n" +
7297
				"}\n"				},
7298
			"SUCCESS");
7299
	}
7300
	// https://bugs.eclipse.org/bugs/show_bug.cgi?id=367023
7301
	public void test063() throws Exception {
7302
		this.runNegativeTest(
7303
			new String[] {
7304
				"X.java",
7305
				"public class X {\n" +
7306
				"    public void run() {\n" +
7307
				"        final int five = 5, ten = 10;\n" +
7308
				"        String s;\n" +
7309
				"        label1: do {\n" +
7310
				"            for (; five > ten;) {\n" +
7311
				"                s = \"\";\n" +
7312
				"                if (s == null) \n" +
7313
				"                    continue label1;\n" +
7314
				"            }\n" +
7315
				"        } while (s != null);\n" +
7316
				"}\n" +
7317
				"    public static void main(String [] args) {\n" +
7318
				"		System.out.println(\"SUCCESS\");\n" +
7319
				"    }\n" +
7320
				"}\n"				},
7321
				"----------\n" + 
7322
				"1. WARNING in X.java (at line 5)\n" + 
7323
				"	label1: do {\n" + 
7324
				"	^^^^^^\n" + 
7325
				"The label label1 is never explicitly referenced\n" + 
7326
				"----------\n" + 
7327
				"2. ERROR in X.java (at line 6)\n" + 
7328
				"	for (; five > ten;) {\n" + 
7329
				"                s = \"\";\n" + 
7330
				"                if (s == null) \n" + 
7331
				"                    continue label1;\n" + 
7332
				"            }\n" + 
7333
				"	                    ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^\n" + 
7334
				"Unreachable code\n" + 
7335
				"----------\n" + 
7336
				"3. ERROR in X.java (at line 11)\n" + 
7337
				"	} while (s != null);\n" + 
7338
				"	         ^\n" + 
7339
				"The local variable s may not have been initialized\n" + 
7340
				"----------\n");
7341
	}
7342
	// https://bugs.eclipse.org/bugs/show_bug.cgi?id=367023
7343
	public void test064() throws Exception {
7344
		this.runConformTest(
7345
				new String[] {
7346
					"X.java",
7347
					"public class X {\n" +
7348
					"    public void run() {\n" +
7349
					"        String s;\n" +
7350
					"        label1: do {\n" +
7351
					"            while (true) {\n" +
7352
					"                s = \"\";\n" +
7353
					"                if (s == null) \n" +
7354
					"                    continue label1;\n" +
7355
					"            }\n" +
7356
					"        } while (s != null);\n" +
7357
					"}\n" +
7358
					"    public static void main(String [] args) {\n" +
7359
					"		System.out.println(\"SUCCESS\");\n" +
7360
					"    }\n" +
7361
					"}\n",
7362
				},
7363
				"SUCCESS");
7364
	}
7365
	// https://bugs.eclipse.org/bugs/show_bug.cgi?id=367023
7366
	public void test065() throws Exception {
7367
		this.runNegativeTest(
7368
				new String[] {
7369
					"X.java",
7370
					"public class X {\n" +
7371
					"    public void run() {\n" +
7372
					"        String s;\n" +
7373
					"        label1: do {\n" +
7374
					"            while (false) {\n" +
7375
					"                s = \"\";\n" +
7376
					"                if (s == null) \n" +
7377
					"                    continue label1;\n" +
7378
					"            }\n" +
7379
					"        } while (s != null);\n" +
7380
					"}\n" +
7381
					"    public static void main(String [] args) {\n" +
7382
					"		System.out.println(\"SUCCESS\");\n" +
7383
					"    }\n" +
7384
					"}\n"				},
7385
					"----------\n" + 
7386
					"1. WARNING in X.java (at line 4)\n" + 
7387
					"	label1: do {\n" + 
7388
					"	^^^^^^\n" + 
7389
					"The label label1 is never explicitly referenced\n" + 
7390
					"----------\n" + 
7391
					"2. ERROR in X.java (at line 5)\n" + 
7392
					"	while (false) {\n" + 
7393
					"                s = \"\";\n" + 
7394
					"                if (s == null) \n" + 
7395
					"                    continue label1;\n" + 
7396
					"            }\n" + 
7397
					"	              ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^\n" + 
7398
					"Unreachable code\n" + 
7399
					"----------\n" + 
7400
					"3. ERROR in X.java (at line 10)\n" + 
7401
					"	} while (s != null);\n" + 
7402
					"	         ^\n" + 
7403
					"The local variable s may not have been initialized\n" + 
7404
					"----------\n");
7405
	}
7406
	// https://bugs.eclipse.org/bugs/show_bug.cgi?id=367023
7407
	public void test066() throws Exception {
7408
		this.runConformTest(
7409
				new String[] {
7410
					"X.java",
7411
					"public class X {\n" +
7412
					"    public void run() {\n" +
7413
					"        String s;\n" +
7414
					"        label1: do {\n" +
7415
					"            while(5 < 10) {\n" +
7416
					"                s = \"\";\n" +
7417
					"                if (s == null) \n" +
7418
					"                    continue label1;\n" +
7419
					"            }\n" +
7420
					"        } while (s != null);\n" +
7421
					"}\n" +
7422
					"    public static void main(String [] args) {\n" +
7423
					"		System.out.println(\"SUCCESS\");\n" +
7424
					"    }\n" +
7425
					"}\n"				},
7426
				"SUCCESS");
7427
	}	
7428
	// https://bugs.eclipse.org/bugs/show_bug.cgi?id=367023
7429
	public void test067() throws Exception {
7430
		this.runNegativeTest(
7431
				new String[] {
7432
					"X.java",
7433
					"public class X {\n" +
7434
					"    public void run() {\n" +
7435
					"        int five = 5, ten = 10;\n" +
7436
					"        String s;\n" +
7437
					"        label1: do {\n" +
7438
					"            while (five < ten) {\n" +
7439
					"                s = \"\";\n" +
7440
					"                if (s == null) \n" +
7441
					"                    continue label1;\n" +
7442
					"            }\n" +
7443
					"        } while (s != null);\n" +
7444
					"}\n" +
7445
					"    public static void main(String [] args) {\n" +
7446
					"		System.out.println(\"SUCCESS\");\n" +
7447
					"    }\n" +
7448
					"}\n"				},
7449
					"----------\n" + 
7450
					"1. WARNING in X.java (at line 9)\n" + 
7451
					"	continue label1;\n" + 
7452
					"	^^^^^^^^^^^^^^^^\n" + 
7453
					"Dead code\n" + 
7454
					"----------\n" + 
7455
					"2. ERROR in X.java (at line 11)\n" + 
7456
					"	} while (s != null);\n" + 
7457
					"	         ^\n" + 
7458
					"The local variable s may not have been initialized\n" + 
7459
					"----------\n");
7460
	}
7461
	// https://bugs.eclipse.org/bugs/show_bug.cgi?id=367023
7462
	public void test068() throws Exception {
7463
		this.runConformTest(
7464
			new String[] {
7465
				"X.java",
7466
				"public class X {\n" +
7467
				"    public void run() {\n" +
7468
				"        final int five = 5, ten = 10;\n" +
7469
				"        String s;\n" +
7470
				"        label1: do {\n" +
7471
				"            while (five < ten) {\n" +
7472
				"                s = \"\";\n" +
7473
				"                if (s == null) \n" +
7474
				"                    continue label1;\n" +
7475
				"            }\n" +
7476
				"        } while (s != null);\n" +
7477
				"}\n" +
7478
				"    public static void main(String [] args) {\n" +
7479
				"		System.out.println(\"SUCCESS\");\n" +
7480
				"    }\n" +
7481
				"}\n"				},
7482
			"SUCCESS");
7483
	}
7484
	// https://bugs.eclipse.org/bugs/show_bug.cgi?id=367023
7485
	public void test069() throws Exception {
7486
		this.runNegativeTest(
7487
			new String[] {
7488
				"X.java",
7489
				"public class X {\n" +
7490
				"    public void run() {\n" +
7491
				"        final int five = 5, ten = 10;\n" +
7492
				"        String s;\n" +
7493
				"        label1: do {\n" +
7494
				"            while (five > ten) {\n" +
7495
				"                s = \"\";\n" +
7496
				"                if (s == null) \n" +
7497
				"                    continue label1;\n" +
7498
				"            }\n" +
7499
				"        } while (s != null);\n" +
7500
				"}\n" +
7501
				"    public static void main(String [] args) {\n" +
7502
				"		System.out.println(\"SUCCESS\");\n" +
7503
				"    }\n" +
7504
				"}\n"				},
7505
				"----------\n" + 
7506
				"1. WARNING in X.java (at line 5)\n" + 
7507
				"	label1: do {\n" + 
7508
				"	^^^^^^\n" + 
7509
				"The label label1 is never explicitly referenced\n" + 
7510
				"----------\n" + 
7511
				"2. ERROR in X.java (at line 6)\n" + 
7512
				"	while (five > ten) {\n" + 
7513
				"                s = \"\";\n" + 
7514
				"                if (s == null) \n" + 
7515
				"                    continue label1;\n" + 
7516
				"            }\n" + 
7517
				"	                   ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^\n" + 
7518
				"Unreachable code\n" + 
7519
				"----------\n" + 
7520
				"3. ERROR in X.java (at line 11)\n" + 
7521
				"	} while (s != null);\n" + 
7522
				"	         ^\n" + 
7523
				"The local variable s may not have been initialized\n" + 
7524
				"----------\n");
7525
	}
7526
	// https://bugs.eclipse.org/bugs/show_bug.cgi?id=367023
7527
	public void test070() throws Exception {
7528
		this.runConformTest(
7529
			new String[] {
7530
				"X.java",
7531
				"import java.util.ArrayList;\n" +
7532
				"import java.util.Arrays;\n" +
7533
				"import java.util.Iterator;\n" +
7534
				"import java.util.List;\n" +
7535
				"import java.util.Properties;\n" +
7536
				"import org.w3c.dom.*;\n" +
7537
				"public class X extends Object {\n" +
7538
				"        public static void main(String [] args) {\n" +
7539
				"            System.out.println (\"SUCCESS\");\n" +
7540
				"        }\n" +
7541
				"	private static class Handler extends Object {\n" +
7542
				"		public int getStuff() {\n" +
7543
				"			return 1;\n" +
7544
				"		}\n" +
7545
				"		public void handle(Element element) {\n" +
7546
				"			Properties properties = new Properties();\n" +
7547
				"			NamedNodeMap atts = element.getAttributes();\n" +
7548
				"			if (atts != null) {\n" +
7549
				"				for (int a = 0; a < atts.getLength(); a++) {\n" +
7550
				"					Node att = atts.item(a);\n" +
7551
				"					String name = att.getNodeName();\n" +
7552
				"					String value = att.getNodeValue();\n" +
7553
				"					if (\"foo\".equals(name)) {\n" +
7554
				"						name = value;\n" +
7555
				"					} else {\n" +
7556
				"						if (!\"bar\".equals(name))\n" +
7557
				"							continue;\n" +
7558
				"						name = value;\n" +
7559
				"					}\n" +
7560
				"					properties.put(name, value);\n" +
7561
				"				}\n" +
7562
				"			}\n" +
7563
				"			label0: do {\n" +
7564
				"				Node node;\n" +
7565
				"				String nodeName;\n" +
7566
				"				label1: do {\n" +
7567
				"					for (Iterator i = (new ArrayList(1)).iterator(); i\n" +
7568
				"							.hasNext(); members.add(equals(node))) {\n" +
7569
				"						node = (Node) i.next();\n" +
7570
				"						nodeName = \"\" + equals(node.getNodeName());\n" +
7571
				"						if (!\"foo\".equals(nodeName))\n" +
7572
				"							continue label1;\n" +
7573
				"					}\n" +
7574
				"					break label0;\n" +
7575
				"				} while (!\"bar\".equals(nodeName));\n" +
7576
				"				Iterator i = (new ArrayList(1)).iterator();\n" +
7577
				"				while (i.hasNext()) {\n" +
7578
				"					Node n = (Node) i.next();\n" +
7579
				"					String name = toString() + n.getNodeName();\n" +
7580
				"					if (\"wtf\".equals(name)) {\n" +
7581
				"						String propertyName = (toString() + n.getAttributes()\n" +
7582
				"								.getNamedItem(\"broken\")).trim();\n" +
7583
				"						String value = toString() + n;\n" +
7584
				"						properties.put(propertyName, value);\n" +
7585
				"					}\n" +
7586
				"				}\n" +
7587
				"			} while (true);\n" +
7588
				"			propertiesBuilder.equals(properties);\n" +
7589
				"			builder.equals(propertiesBuilder.hashCode());\n" +
7590
				"			builder.equals(members);\n" +
7591
				"		}\n" +
7592
				"		private final Object c;\n" +
7593
				"		private Object builder;\n" +
7594
				"		private List members;\n" +
7595
				"		private Object propertiesBuilder;\n" +
7596
				"		public Handler(Object c) {\n" +
7597
				"			this.c = c;\n" +
7598
				"			builder = Arrays.asList(Object.class);\n" +
7599
				"			builder.equals(\"foo\");\n" +
7600
				"			builder.equals(\"bar\");\n" +
7601
				"			members = new ArrayList();\n" +
7602
				"			propertiesBuilder = Arrays.asList(Object.class);\n" +
7603
				"			Object beanDefinition = propertiesBuilder.toString();\n" +
7604
				"			Object holder = new String(\"stirng\");\n" +
7605
				"			Arrays.asList(holder, c.toString());\n" +
7606
				"		}\n" +
7607
				"	}\n" +
7608
				"	public X() {\n" +
7609
				"	}\n" +
7610
				"	protected Object parseInternal(Element element, Object c) {\n" +
7611
				"		Handler h = new Handler(c);\n" +
7612
				"		h.handle(element);\n" +
7613
				"		return h.getStuff();\n" +
7614
				"	}\n" +
7615
				"}\n"
7616
				},
7617
				"SUCCESS");
7618
	}
6805
}
7619
}
(-)a/org.eclipse.jdt.core.tests.compiler/src/org/eclipse/jdt/core/tests/compiler/regression/StaticImportTest.java (-3 / +360 lines)
Lines 2484-2493 Link Here
2484
				"}\n",
2484
				"}\n",
2485
			},
2485
			},
2486
			"----------\n" + 
2486
			"----------\n" + 
2487
			"1. ERROR in p1\\A.java (at line 7)\n" + 
2487
			"1. ERROR in p1\\A.java (at line 6)\n" + 
2488
			"	int v2 = b.fooC;\n" + 
2488
			"	int v1 = b.fooB;\n" + 
2489
			"	           ^^^^\n" + 
2489
			"	           ^^^^\n" + 
2490
			"fooC cannot be resolved or is not a field\n" + 
2490
			"fooB cannot be resolved or is not a field\n" + 
2491
			"----------\n");
2491
			"----------\n");
2492
	}	
2492
	}	
2493
	//https://bugs.eclipse.org/bugs/show_bug.cgi?id=256375
2493
	//https://bugs.eclipse.org/bugs/show_bug.cgi?id=256375
Lines 2720-2724 Link Here
2720
			"----------\n"
2720
			"----------\n"
2721
		);
2721
		);
2722
	}
2722
	}
2723
	
2724
	// https://bugs.eclipse.org/bugs/show_bug.cgi?id=318401
2725
	public void test081() {
2726
		this.runConformTest(
2727
			new String[] {
2728
				"Test.java",
2729
				"import static p1.Bar.B;\n" +
2730
				"import p3.Foo.*;\n" +
2731
				"public class Test {\n" +
2732
				"	public static void main(String [] args){\n" +
2733
				"		new Test().beginTest();" +
2734
				"	}\n" +
2735
				"	public void beginTest(){\n" +
2736
				"		System.out.print(\"1 + 1 =  \");\n" +
2737
				"		if(alwaysTrue()) System.out.println(\"2\");\n" +
2738
				"		else System.out.println(\"3\"); " +
2739
				"	}\n" +
2740
				"	public boolean alwaysTrue(){\n" +
2741
				"		String myB   =        B.class.getCanonicalName();;\n" +		// refers to p1.Bar.B (class)
2742
				"		String realB = p1.Bar.B.class.getCanonicalName();;\n" +     // refers to p1.Bar.B (class)
2743
				"		B();\n" +				// refers to p1.Bar.B() (method)
2744
				"		return myB.equals(realB);\n" +
2745
				"	}\n" +
2746
				"}\n",
2747
				"p1/Bar.java",
2748
				"package p1;\n" +
2749
				"public class Bar{\n" +
2750
				"	public static class B{}\n" +
2751
				"	final public static String B = new String(\"random\");\n" +
2752
				"	public static void B(){}\n" +
2753
				"}\n",
2754
				"p3/Foo.java",
2755
				"package p3;\n" +
2756
				"public class Foo {\n" +
2757
				"	public class B{\n" +
2758
				"		public int a;\n" +
2759
				"	}\n" +
2760
				"}\n"
2761
			},
2762
			"1 + 1 =  2");
2763
	}
2764
	
2765
	// https://bugs.eclipse.org/bugs/show_bug.cgi?id=318401
2766
	public void test082() {
2767
		this.runNegativeTest(
2768
			new String[] {
2769
				"p1/Bar.java",
2770
				"package p1;\n" +
2771
				"public class Bar{\n" +
2772
				"	public static class B{}\n" +
2773
				"	final public static String B = new String(\"random\");\n" +
2774
				"	public static void B(){}\n" +
2775
				"}\n",
2776
				"p3/Foo.java",
2777
				"package p3;\n" +
2778
				"public class Foo {\n" +
2779
				"	public class B{\n" +
2780
				"		public int a;\n" +
2781
				"	}\n" +
2782
				"}\n",
2783
				"p2/Test.java",
2784
				"package p2;\n" +
2785
				"import static p1.Bar.B;\n" +
2786
				"import p3.Foo.*;\n" +
2787
				"public class Test {\n" +
2788
				"	public static void main(String [] args){\n" +
2789
				"		new Test().beginTest();" +
2790
				"	}\n" +
2791
				"	public void beginTest(){\n" +
2792
				"		System.out.print(\"1 + 1 =  \");\n" +
2793
				"		if(alwaysTrue()) System.out.println(\"2\");\n" +
2794
				"		else System.out.println(\"3\"); " +
2795
				"	}\n" +
2796
				"	public boolean alwaysTrue(){\n" +
2797
				"		B b = null;\n" +		// refers to p1.Bar.B (class)
2798
				"		String realB = B;\n" +  // refers to p1.Bar.B (field)
2799
				"		B();\n" +				// refers to p1.Bar.B() (method)
2800
				"		int abc = b.a;\n;" +	// static import for Bar.B overshadows on demand import Foo.B
2801
				"	}\n" +
2802
				"}\n",
2803
			},
2804
			"----------\n" +
2805
			"1. ERROR in p2\\Test.java (at line 15)\n" + 
2806
			"	int abc = b.a;\n" + 
2807
			"	            ^\n" + 
2808
			"a cannot be resolved or is not a field\n" + 
2809
			"----------\n");
2810
	}
2811
	
2812
	// https://bugs.eclipse.org/bugs/show_bug.cgi?id=318401
2813
	public void test083() {
2814
		this.runConformTest(
2815
			new String[] {
2816
				"Test.java",
2817
				"import static p1.Bar.B;\n" +
2818
				"import p3.Foo.*;\n" +
2819
				"public class Test {\n" +
2820
				"	public static void main(String [] args){\n" +
2821
				"		new Test().test2();" +
2822
				"	}\n" +
2823
				"	public void test2(){\n" +
2824
				"		System.out.println(B.toString());\n" +		// Field obscures class B
2825
				"		System.out.println(p1.Bar.B.toString());\n" +  // Field obscures the class B
2826
				"		System.out.println(B.class.getCanonicalName().toString());\n" +	// the class B
2827
				"		System.out.println(p1.Bar.B.class.getCanonicalName().toString());" +	// class B
2828
				"	}\n" +
2829
				"}\n",
2830
				"p1/Bar.java",
2831
				"package p1;\n" +
2832
				"public class Bar{\n" +
2833
				"	public static class B{}\n" +
2834
				"	final public static String B = new String(\"random\");\n" +
2835
				"	public static void B(){}\n" +
2836
				"}\n",
2837
				"p3/Foo.java",
2838
				"package p3;\n" +
2839
				"public class Foo {\n" +
2840
				"	public class B{\n" +
2841
				"		public int a;\n" +
2842
				"	}\n" +
2843
				"}\n"
2844
			},
2845
			"random\n" + 
2846
			"random\n" + 
2847
			"p1.Bar.B\n" + 
2848
			"p1.Bar.B");
2849
	}
2850
	
2851
	// https://bugs.eclipse.org/bugs/show_bug.cgi?id=318401
2852
	// Check if we're able to find the correct static member type being imported,
2853
	// even though the import originally resolved to the static field of the same name,
2854
	// coming from the supertype
2855
	public void test084() {
2856
		this.runConformTest(
2857
			new String[] {
2858
				"Test.java",
2859
				"import static p1.Bar.B;\n" +
2860
				"import p3.Foo.*;\n" +
2861
				"public class Test {\n" +
2862
				"	public static void main(String [] args){\n" +
2863
				"		new Test().test2();" +
2864
				"	}\n" +
2865
				"	public void test2(){\n" +
2866
				"		System.out.println(B.class.getCanonicalName().toString());\n" +	// the class B
2867
				"		System.out.println(p1.Bar.B.class.getCanonicalName().toString());" +	// class B
2868
				"	}\n" +
2869
				"}\n",
2870
				"p1/Bar.java",
2871
				"package p1;\n" +
2872
				"public class Bar extends SuperBar{\n" +
2873
				"	public static class B{}\n" +
2874
				"	public static void B(){}\n" +
2875
				"}\n",
2876
				"p1/SuperBar.java",
2877
				"package p1;\n" +
2878
				"public class SuperBar {\n" +
2879
				"	final public static String B = new String(\"random\");\n" +
2880
				"}\n",
2881
				"p3/Foo.java",
2882
				"package p3;\n" +
2883
				"public class Foo {\n" +
2884
				"	public class B{\n" +
2885
				"		public int a;\n" +
2886
				"	}\n" +
2887
				"}\n"
2888
			},
2889
			"p1.Bar.B\n" + 
2890
			"p1.Bar.B");
2891
	}
2892
	// https://bugs.eclipse.org/bugs/show_bug.cgi?id=361327
2893
	// To verify that all static members are imported with a single static import statement
2894
	public void test085() {
2895
		this.runNegativeTest(
2896
			new String[] {
2897
				"Test.java",
2898
				"import static p1.Bar.B;\n" +
2899
				"import static p3.Foo.B;\n" +
2900
				"public class Test {\n" +
2901
				"	public static void main(String [] args){\n" +
2902
				"		new Test().test2();" +
2903
				"	}\n" +
2904
				"	public void test2(){\n" +
2905
				"		System.out.println(B.class.getCanonicalName().toString());\n" +
2906
				"		System.out.println(p1.Bar.B.class.getCanonicalName().toString());" +
2907
				"	}\n" +
2908
				"}\n",
2909
				"p1/Bar.java",
2910
				"package p1;\n" +
2911
				"public class Bar{\n" +
2912
				"	public static class B{}\n" +
2913
				"	public static String B = new String(\"random\");\n" +
2914
				"}\n",
2915
				"p3/Foo.java",
2916
				"package p3;\n" +
2917
				"public class Foo {\n" +
2918
				"	public static class B{\n" +
2919
				"	}\n" +
2920
				"}\n"
2921
			},
2922
			"----------\n" + 
2923
			"1. ERROR in Test.java (at line 2)\n" + 
2924
			"	import static p3.Foo.B;\n" + 
2925
			"	              ^^^^^^^^\n" + 
2926
			"The import p3.Foo.B collides with another import statement\n" + 
2927
			"----------\n");
2928
	}
2929
	// https://bugs.eclipse.org/bugs/show_bug.cgi?id=361327
2930
	// To verify that all static members are imported with a single static import statement,
2931
	// even from a supertype
2932
	public void test085a() {
2933
		this.runNegativeTest(
2934
			new String[] {
2935
				"Test.java",
2936
				"import static p1.Bar.B;\n" +
2937
				"import static p3.Foo.B;\n" +
2938
				"public class Test {\n" +
2939
				"	public static void main(String [] args){\n" +
2940
				"		new Test().test2();" +
2941
				"	}\n" +
2942
				"	public void test2(){\n" +
2943
				"		System.out.println(B.class.getCanonicalName().toString());\n" +
2944
				"		System.out.println(p1.Bar.B.class.getCanonicalName().toString());" +
2945
				"	}\n" +
2946
				"}\n",
2947
				"p1/Bar.java",
2948
				"package p1;\n" +
2949
				"public class Bar extends SuperBar{\n" +
2950
				"	public static void B(){}\n" +
2951
				"}\n",
2952
				"p1/SuperBar.java",
2953
				"package p1;\n" +
2954
				"public class SuperBar {\n" +
2955
				"	public static class B{}\n" +
2956
				"	final public static String B = new String(\"random\");\n" +
2957
				"}\n",
2958
				"p3/Foo.java",
2959
				"package p3;\n" +
2960
				"public class Foo {\n" +
2961
				"	public static class B{\n" +
2962
				"	}\n" +
2963
				"}\n"
2964
			},
2965
			"----------\n" + 
2966
			"1. ERROR in Test.java (at line 2)\n" + 
2967
			"	import static p3.Foo.B;\n" + 
2968
			"	              ^^^^^^^^\n" + 
2969
			"The import p3.Foo.B collides with another import statement\n" + 
2970
			"----------\n");
2971
	}
2972
	
2973
	// https://bugs.eclipse.org/bugs/show_bug.cgi?id=361327
2974
	// To verify that all static members are imported with a single static import statement
2975
	// this tests checks collision with single type import
2976
	public void test085b() {
2977
		this.runNegativeTest(
2978
			new String[] {
2979
				"Test.java",
2980
				"import static p1.Bar.B;\n" +
2981
				"import p3.Foo.B;\n" +
2982
				"public class Test {\n" +
2983
				"	public static void main(String [] args){\n" +
2984
				"		new Test().test2();" +
2985
				"	}\n" +
2986
				"	public void test2(){\n" +
2987
				"		System.out.println(B.class.getCanonicalName().toString());\n" +
2988
				"		System.out.println(p1.Bar.B.class.getCanonicalName().toString());" +
2989
				"	}\n" +
2990
				"}\n",
2991
				"p1/Bar.java",
2992
				"package p1;\n" +
2993
				"public class Bar{\n" +
2994
				"	public static class B{}\n" +
2995
				"	public static String B = new String(\"random\");\n" +
2996
				"}\n",
2997
				"p3/Foo.java",
2998
				"package p3;\n" +
2999
				"public class Foo {\n" +
3000
				"	public class B{\n" +
3001
				"	}\n" +
3002
				"}\n"
3003
			},
3004
			"----------\n" + 
3005
			"1. ERROR in Test.java (at line 2)\n" + 
3006
			"	import p3.Foo.B;\n" + 
3007
			"	       ^^^^^^^^\n" + 
3008
			"The import p3.Foo.B collides with another import statement\n" + 
3009
			"----------\n");
3010
	}
3011
	
3012
	// https://bugs.eclipse.org/bugs/show_bug.cgi?id=361327
3013
	// To verify that all static members are imported with a single static import statement
3014
	// this tests checks collision with top level type
3015
	public void test085c() {
3016
		this.runNegativeTest(
3017
			new String[] {
3018
				"Test.java",
3019
				"import static p1.Bar.B;\n" +
3020
				"public class Test {\n" +
3021
				"	public static void main(String [] args){\n" +
3022
				"		new Test().test2();" +
3023
				"	}\n" +
3024
				"	public void test2(){\n" +
3025
				"		System.out.println(B.class.getCanonicalName().toString());\n" +
3026
				"		System.out.println(p1.Bar.B.class.getCanonicalName().toString());" +
3027
				"	}\n" +
3028
				"}\n" +
3029
				"class B{\n" +
3030
				"}\n",
3031
				"p1/Bar.java",
3032
				"package p1;\n" +
3033
				"public class Bar{\n" +
3034
				"	public static class B{}\n" +
3035
				"	public static String B = new String(\"random\");\n" +
3036
				"}\n",
3037
			},
3038
			"----------\n" + 
3039
			"1. ERROR in Test.java (at line 1)\n" + 
3040
			"	import static p1.Bar.B;\n" + 
3041
			"	              ^^^^^^^^\n" + 
3042
			"The import p1.Bar.B conflicts with a type defined in the same file\n" + 
3043
			"----------\n");
3044
	}
3045
	
3046
	// https://bugs.eclipse.org/bugs/show_bug.cgi?id=361327
3047
	// Test obscuring rules defined in JLS 7.5.3
3048
	public void test086() {
3049
		this.runConformTest(
3050
			new String[] {
3051
				"Test.java",
3052
				"import static p1.Bar.B;\n" +
3053
				"import static p3.Foo.*;\n" +
3054
				"public class Test {\n" +
3055
				"	public static void main(String [] args){\n" +
3056
				"		new Test().test2();" +
3057
				"	}\n" +
3058
				"	public void test2(){\n" +
3059
				"       B();\n" + // should be p1.Bar.B() and not p3.Foo.B()
3060
				"		System.out.println(B.toString());\n" + // should be p1.Bar.B
3061
				"	}\n" +
3062
				"}\n",
3063
				"p1/Bar.java",
3064
				"package p1;\n" +
3065
				"public class Bar{\n" +
3066
				"	public static void B(){ System.out.println(\"Bar's method B\");}\n" +
3067
				"	public static String B = new String(\"Bar's field B\");\n" +
3068
				"}\n",
3069
				"p3/Foo.java",
3070
				"package p3;\n" +
3071
				"public class Foo {\n" +
3072
				"	public static void B(){ System.out.println(\"Foo's method B\");}\n" +
3073
				"	public static String B = new String(\"Foo's field B\");\n" +
3074
				"}\n"
3075
			},
3076
			"Bar\'s method B\n" + 
3077
			"Bar\'s field B");
3078
	}
3079
2723
}
3080
}
2724
3081
(-)a/org.eclipse.jdt.core.tests.compiler/src/org/eclipse/jdt/core/tests/compiler/regression/TestAll.java (-1 / +6 lines)
Lines 1-5 Link Here
1
/*******************************************************************************
1
/*******************************************************************************
2
 * Copyright (c) 2000, 2011 IBM Corporation and others.
2
 * Copyright (c) 2000, 2012 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 - Contributions for
11
 *								bug 186342 - [compiler][null] Using annotations for null checking
12
 *								bug 358903 - Filter practically unimportant resource leak warnings
10
 *******************************************************************************/
13
 *******************************************************************************/
11
package org.eclipse.jdt.core.tests.compiler.regression;
14
package org.eclipse.jdt.core.tests.compiler.regression;
12
15
Lines 73-78 Link Here
73
	standardTests.add(ProgrammingProblemsTest.class);
76
	standardTests.add(ProgrammingProblemsTest.class);
74
	standardTests.add(ManifestAnalyzerTest.class);
77
	standardTests.add(ManifestAnalyzerTest.class);
75
	standardTests.add(InitializationTests.class);
78
	standardTests.add(InitializationTests.class);
79
	standardTests.add(ResourceLeakTests.class);
76
80
77
	// add all javadoc tests
81
	// add all javadoc tests
78
	for (int i=0, l=JavadocTest.ALL_CLASSES.size(); i<l; i++) {
82
	for (int i=0, l=JavadocTest.ALL_CLASSES.size(); i<l; i++) {
Lines 96-101 Link Here
96
	since_1_5.add(InnerEmulationTest_1_5.class);
100
	since_1_5.add(InnerEmulationTest_1_5.class);
97
	since_1_5.add(AssignmentTest_1_5.class);
101
	since_1_5.add(AssignmentTest_1_5.class);
98
	since_1_5.add(InnerClass15Test.class);
102
	since_1_5.add(InnerClass15Test.class);
103
	since_1_5.add(NullAnnotationTest.class);
99
104
100
	// Tests to run when compliance is greater than 1.5
105
	// Tests to run when compliance is greater than 1.5
101
	ArrayList since_1_6 = new ArrayList();
106
	ArrayList since_1_6 = new ArrayList();
(-)a/org.eclipse.jdt.core.tests.compiler/src/org/eclipse/jdt/core/tests/compiler/regression/TryStatementTest.java (-1 / +1 lines)
Lines 758-764 Link Here
758
		"1. ERROR in X.java (at line 6)\n" +
758
		"1. ERROR in X.java (at line 6)\n" +
759
		"	} catch(AX e) {\n" +
759
		"	} catch(AX e) {\n" +
760
		"	        ^^\n" +
760
		"	        ^^\n" +
761
		"Unreachable catch block for AX. Only more specific exceptions are thrown and handled by previous catch block(s).\n" +
761
		"Unreachable catch block for AX. Only more specific exceptions are thrown and they are handled by previous catch block(s).\n" +
762
		"----------\n" +
762
		"----------\n" +
763
		"2. WARNING in X.java (at line 10)\n" +
763
		"2. WARNING in X.java (at line 10)\n" +
764
		"	class AX extends Exception {}\n" +
764
		"	class AX extends Exception {}\n" +
(-)a/org.eclipse.jdt.core.tests.compiler/src/org/eclipse/jdt/core/tests/compiler/regression/TryWithResourcesStatementTest.java (-10 / +256 lines)
Lines 1-5 Link Here
1
/*******************************************************************************
1
/*******************************************************************************
2
 * Copyright (c) 2011 IBM Corporation and others.
2
 * Copyright (c) 2011, 2012 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-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 - Contributions for
11
 *     							bug 358827 - [1.7] exception analysis for t-w-r spoils null analysis
12
 *     							bug 349326 - [1.7] new warning for missing try-with-resources
13
 *     							bug 359334 - Analysis for resource leak warnings does not consider exceptions as method exit points
10
 *******************************************************************************/
14
 *******************************************************************************/
11
package org.eclipse.jdt.core.tests.compiler.regression;
15
package org.eclipse.jdt.core.tests.compiler.regression;
12
16
13
import java.util.Map;
17
import java.util.Map;
14
18
15
import org.eclipse.jdt.internal.compiler.impl.CompilerOptions;
16
17
import junit.framework.Test;
19
import junit.framework.Test;
20
21
import org.eclipse.jdt.internal.compiler.impl.CompilerOptions;
18
public class TryWithResourcesStatementTest extends AbstractRegressionTest {
22
public class TryWithResourcesStatementTest extends AbstractRegressionTest {
19
23
20
static {
24
static {
21
//	TESTS_NAMES = new String[] { "test055", "test055a" };
25
//	TESTS_NAMES = new String[] { "test061m"};
22
//	TESTS_NUMBERS = new int[] { 50 };
26
//	TESTS_NUMBERS = new int[] { 50 };
23
//	TESTS_RANGE = new int[] { 11, -1 };
27
//	TESTS_RANGE = new int[] { 11, -1 };
24
}
28
}
Lines 448-453 Link Here
448
}
452
}
449
// Test for unhandled exceptions
453
// Test for unhandled exceptions
450
public void test014() {
454
public void test014() {
455
	Map options = getCompilerOptions();
456
	options.put(CompilerOptions.OPTION_ReportUnclosedCloseable, CompilerOptions.WARNING);
451
	this.runNegativeTest(
457
	this.runNegativeTest(
452
		new String[] {
458
		new String[] {
453
			"X.java",
459
			"X.java",
Lines 485-500 Link Here
485
		"	               ^^\n" + 
491
		"	               ^^\n" + 
486
		"Dead code\n" + 
492
		"Dead code\n" + 
487
		"----------\n" + 
493
		"----------\n" + 
488
		"3. ERROR in X.java (at line 5)\n" + 
494
		"3. WARNING in X.java (at line 5)\n" + 
495
		"	Y why = new Y();\n" + 
496
		"	  ^^^\n" + 
497
		"Resource leak: 'why' is never closed\n" + 
498
		"----------\n" + 
499
		"4. ERROR in X.java (at line 5)\n" + 
489
		"	Y why = new Y();\n" + 
500
		"	Y why = new Y();\n" + 
490
		"	        ^^^^^^^\n" + 
501
		"	        ^^^^^^^\n" + 
491
		"Unhandled exception type WeirdException\n" + 
502
		"Unhandled exception type WeirdException\n" + 
492
		"----------\n" + 
503
		"----------\n" + 
493
		"4. WARNING in X.java (at line 22)\n" + 
504
		"5. WARNING in X.java (at line 22)\n" + 
494
		"	class WeirdException extends Throwable {}\n" + 
505
		"	class WeirdException extends Throwable {}\n" + 
495
		"	      ^^^^^^^^^^^^^^\n" + 
506
		"	      ^^^^^^^^^^^^^^\n" + 
496
		"The serializable class WeirdException does not declare a static final serialVersionUID field of type long\n" + 
507
		"The serializable class WeirdException does not declare a static final serialVersionUID field of type long\n" + 
497
		"----------\n");
508
		"----------\n",
509
		null, true, options);
498
}
510
}
499
// Resource nullness tests
511
// Resource nullness tests
500
public void test015() {
512
public void test015() {
Lines 523-528 Link Here
523
}
535
}
524
// Dead code tests, resource nullness, unhandled exception tests
536
// Dead code tests, resource nullness, unhandled exception tests
525
public void test016() {
537
public void test016() {
538
	Map options = getCompilerOptions();
539
	options.put(CompilerOptions.OPTION_ReportUnclosedCloseable, CompilerOptions.WARNING);
526
	this.runNegativeTest(
540
	this.runNegativeTest(
527
		new String[] {
541
		new String[] {
528
			"X.java",
542
			"X.java",
Lines 558-573 Link Here
558
		"	               ^^\n" + 
572
		"	               ^^\n" + 
559
		"Dead code\n" + 
573
		"Dead code\n" + 
560
		"----------\n" + 
574
		"----------\n" + 
561
		"3. ERROR in X.java (at line 5)\n" + 
575
		"3. WARNING in X.java (at line 5)\n" + 
576
		"	Y why = new Y();\n" + 
577
		"	  ^^^\n" + 
578
		"Resource leak: 'why' is never closed\n" + 
579
		"----------\n" + 
580
		"4. ERROR in X.java (at line 5)\n" + 
562
		"	Y why = new Y();\n" + 
581
		"	Y why = new Y();\n" + 
563
		"	        ^^^^^^^\n" + 
582
		"	        ^^^^^^^\n" + 
564
		"Unhandled exception type WeirdException\n" + 
583
		"Unhandled exception type WeirdException\n" + 
565
		"----------\n" + 
584
		"----------\n" + 
566
		"4. WARNING in X.java (at line 20)\n" + 
585
		"5. WARNING in X.java (at line 20)\n" + 
567
		"	class WeirdException extends Throwable {}\n" + 
586
		"	class WeirdException extends Throwable {}\n" + 
568
		"	      ^^^^^^^^^^^^^^\n" + 
587
		"	      ^^^^^^^^^^^^^^\n" + 
569
		"The serializable class WeirdException does not declare a static final serialVersionUID field of type long\n" + 
588
		"The serializable class WeirdException does not declare a static final serialVersionUID field of type long\n" + 
570
		"----------\n");
589
		"----------\n",
590
		null,
591
		true,
592
		options);
571
}
593
}
572
// Dead code tests
594
// Dead code tests
573
public void test017() {
595
public void test017() {
Lines 3297-3302 Link Here
3297
		"Unhandled exception type IOException\n" + 
3319
		"Unhandled exception type IOException\n" + 
3298
		"----------\n");
3320
		"----------\n");
3299
}
3321
}
3322
// https://bugs.eclipse.org/bugs/show_bug.cgi?id=348705
3323
// Variant of the above, witness for https://bugs.eclipse.org/358827#c6
3324
public void test053a() {
3325
	this.runNegativeTest(
3326
		new String[] {
3327
			"X.java",
3328
			"public class X {\n" +
3329
			"	public void method1(){\n" +
3330
			"		try (Y y = new Y()) { \n" +
3331
			"			y.close();\n" +
3332
			"			System.out.println();\n" +
3333
			"		} catch (RuntimeException e) {\n" +
3334
			"       } finally {\n" +
3335
			"           System.out.println();\n" +
3336
			"		}\n" +
3337
			"	}\n" +
3338
			"}\n" +
3339
			"class Y implements Managed {\n" +
3340
			"	 public Y() throws CloneNotSupportedException {}\n" +
3341
			"    public void close () throws ClassNotFoundException, java.io.IOException {\n" +
3342
			"    }\n" +
3343
			"}\n" +
3344
			"interface Managed extends AutoCloseable {}\n",
3345
		},
3346
		"----------\n" + 
3347
		"1. ERROR in X.java (at line 3)\n" + 
3348
		"	try (Y y = new Y()) { \n" + 
3349
		"	       ^\n" + 
3350
		"Unhandled exception type ClassNotFoundException thrown by automatic close() invocation on y\n" + 
3351
		"----------\n" + 
3352
		"2. ERROR in X.java (at line 3)\n" + 
3353
		"	try (Y y = new Y()) { \n" + 
3354
		"	       ^\n" + 
3355
		"Unhandled exception type IOException thrown by automatic close() invocation on y\n" + 
3356
		"----------\n" + 
3357
		"3. ERROR in X.java (at line 3)\n" + 
3358
		"	try (Y y = new Y()) { \n" + 
3359
		"	           ^^^^^^^\n" + 
3360
		"Unhandled exception type CloneNotSupportedException\n" + 
3361
		"----------\n" + 
3362
		"4. ERROR in X.java (at line 4)\n" + 
3363
		"	y.close();\n" + 
3364
		"	^^^^^^^^^\n" + 
3365
		"Unhandled exception type ClassNotFoundException\n" + 
3366
		"----------\n" + 
3367
		"5. ERROR in X.java (at line 4)\n" + 
3368
		"	y.close();\n" + 
3369
		"	^^^^^^^^^\n" + 
3370
		"Unhandled exception type IOException\n" + 
3371
		"----------\n");
3372
}
3300
// https://bugs.eclipse.org/bugs/show_bug.cgi?id=349862 (NPE when union type is used in the resource section.)
3373
// https://bugs.eclipse.org/bugs/show_bug.cgi?id=349862 (NPE when union type is used in the resource section.)
3301
public void test054() {
3374
public void test054() {
3302
	this.runNegativeTest(
3375
	this.runNegativeTest(
Lines 3380-3385 Link Here
3380
		},
3453
		},
3381
		"Done");
3454
		"Done");
3382
}
3455
}
3456
3457
// Note: test056* have been moved to ResourceLeakTests.java
3458
3459
// https://bugs.eclipse.org/bugs/show_bug.cgi?id=361053
3460
public void test057() {
3461
	this.runConformTest(
3462
		new String[] {
3463
			"X.java",
3464
			"public class X implements AutoCloseable {\n" +
3465
			"	@Override\n" +
3466
			"	public void close() throws Exception {\n" +
3467
			"		throw new Exception();\n" +
3468
			"	}\n" +
3469
			"	public static void main(String[] args) {\n" +
3470
			"		final boolean foo;\n" +
3471
			"		try (X a = new X(); X b = new X()) {\n" +
3472
			"			foo = true;\n" +
3473
			"		} catch (final Exception exception) {\n" +
3474
			"			return;\n" +
3475
			"		}\n" +
3476
			"	}\n" +
3477
			"}\n"
3478
		},  "");	
3479
}
3480
// https://bugs.eclipse.org/bugs/show_bug.cgi?id=364008
3481
public void test058() {
3482
	this.runConformTest(
3483
		new String[] {
3484
			"X.java",
3485
			"import java.io.ByteArrayOutputStream;\n" +
3486
			"import java.io.FileOutputStream;\n" +
3487
			"import java.io.IOException;\n" +
3488
			"\n" +
3489
			"public class X {\n" +
3490
			"\n" +
3491
			"  public static void main(final String[] args) throws IOException {\n" +
3492
			"    byte[] data;\n" +
3493
			"    try (final ByteArrayOutputStream os = new ByteArrayOutputStream();\n" +
3494
			"         final FileOutputStream out = new FileOutputStream(\"test.dat\")) {\n" +
3495
			"      data = os.toByteArray();\n" +
3496
			"    }\n" +
3497
			"  }\n" +
3498
			"}\n"
3499
		},  "");	
3500
}
3501
// https://bugs.eclipse.org/bugs/show_bug.cgi?id=367566 - In try-with-resources statement close() method of resource is not called
3502
public void test059() {
3503
	this.runConformTest(
3504
		new String[] {
3505
			"X.java",
3506
			"import java.io.IOException;\n" +
3507
			"\n" +
3508
			"public class X implements java.lang.AutoCloseable {\n" +
3509
			"  static boolean isOpen = true;\n" +
3510
			"  public static void main(final String[] args) throws IOException {\n" +
3511
			"    foo();\n" +
3512
			"    System.out.println(isOpen);\n" +
3513
			"  }\n" +
3514
			"  static boolean foo() {\n" +
3515
			"    try (final X x = new X()) {\n" +
3516
			"      return x.num() >= 1;\n" +
3517
			"    }\n" +
3518
			"  }\n" +
3519
			"  int num() { return 2; }\n" +
3520
			"  public void close() {\n" +
3521
			"    isOpen = false;\n" +
3522
			"  }\n" +
3523
			"}\n"
3524
		},  
3525
		"false");	
3526
}
3527
3528
// https://bugs.eclipse.org/bugs/show_bug.cgi?id=367566 - In try-with-resources statement close() method of resource is not called
3529
public void test060() {
3530
	this.runConformTest(
3531
		new String[] {
3532
			"X.java",
3533
			"public class X implements AutoCloseable {\n" +
3534
			"	static int num = 10 ;\n" +
3535
			"    public static void main(String [] args) throws Exception { \n" +
3536
			"    	System.out.println(foo(1));\n" +
3537
			"    	System.out.println(foo(2));\n" +
3538
			"    	System.out.println(foo(3));\n" +
3539
			"    }\n" +
3540
			"	private static boolean foo(int where) throws Exception {\n" +
3541
			"		final boolean getOut = true;\n" +
3542
			"    	System.out.println(\"Main\");\n" +
3543
			"    	try (X x1 = new X(); X x2 = new X()) {\n" +
3544
			"    		if (where == 1) {\n" +
3545
			"    			return where == 1;\n" +
3546
			"    		}\n" +
3547
			"            System.out.println(\"Outer Try\");\n" +
3548
			"            while (true) {\n" +
3549
			"            	try (Y y1 = new Y(); Y y2 = new Y()) { \n" +
3550
			"            		if (where == 2) {\n" +
3551
			"            			return where == 2;\n" +
3552
			"            		}		\n" +
3553
			"            		System.out.println(\"Middle Try\");\n" +
3554
			"            		try (Z z1 = new Z(); Z z2 = new Z()) {\n" +
3555
			"            			System.out.println(\"Inner Try\");\n" +
3556
			"            			if (getOut) \n" +
3557
			"            				return num >= 10;\n" +
3558
			"            			else\n" +
3559
			"            				break; \n" +
3560
			"            		}\n" +
3561
			"            	}\n" +
3562
			"            }\n" +
3563
			"            System.out.println(\"Out of while\");\n" +
3564
			"        }\n" +
3565
			"		return false;\n" +
3566
			"	}\n" +
3567
			"    public X() {\n" +
3568
			"        System.out.println(\"X::X\");\n" +
3569
			"    }\n" +
3570
			"    @Override\n" +
3571
			"	public void close() throws Exception {\n" +
3572
			"        System.out.println(\"X::~X\");\n" +
3573
			"    }\n" +
3574
			"}\n" +
3575
			"class Y implements AutoCloseable {\n" +
3576
			"    public Y() {\n" +
3577
			"        System.out.println(\"Y::Y\");\n" +
3578
			"    }\n" +
3579
			"    @Override\n" +
3580
			"	public void close() throws Exception {\n" +
3581
			"        System.out.println(\"Y::~Y\");\n" +
3582
			"    }\n" +
3583
			"}\n" +
3584
			"class Z implements AutoCloseable {\n" +
3585
			"    public Z() {\n" +
3586
			"        System.out.println(\"Z::Z\");\n" +
3587
			"    }\n" +
3588
			"    @Override\n" +
3589
			"	public void close() throws Exception {\n" +
3590
			"        System.out.println(\"Z::~Z\");\n" +
3591
			"    }\n" +
3592
			"}\n"
3593
		}, 
3594
		"Main\n" + 
3595
		"X::X\n" + 
3596
		"X::X\n" + 
3597
		"X::~X\n" + 
3598
		"X::~X\n" + 
3599
		"true\n" + 
3600
		"Main\n" + 
3601
		"X::X\n" + 
3602
		"X::X\n" + 
3603
		"Outer Try\n" + 
3604
		"Y::Y\n" + 
3605
		"Y::Y\n" + 
3606
		"Y::~Y\n" + 
3607
		"Y::~Y\n" + 
3608
		"X::~X\n" + 
3609
		"X::~X\n" + 
3610
		"true\n" + 
3611
		"Main\n" + 
3612
		"X::X\n" + 
3613
		"X::X\n" + 
3614
		"Outer Try\n" + 
3615
		"Y::Y\n" + 
3616
		"Y::Y\n" + 
3617
		"Middle Try\n" + 
3618
		"Z::Z\n" + 
3619
		"Z::Z\n" + 
3620
		"Inner Try\n" + 
3621
		"Z::~Z\n" + 
3622
		"Z::~Z\n" + 
3623
		"Y::~Y\n" + 
3624
		"Y::~Y\n" + 
3625
		"X::~X\n" + 
3626
		"X::~X\n" + 
3627
		"true");
3628
}
3383
public static Class testClass() {
3629
public static Class testClass() {
3384
	return TryWithResourcesStatementTest.class;
3630
	return TryWithResourcesStatementTest.class;
3385
}
3631
}
(-)a/org.eclipse.jdt.core.tests.compiler/src/org/eclipse/jdt/core/tests/compiler/regression/VarargsTest.java (-5 / +259 lines)
Lines 777-783 Link Here
777
	}
777
	}
778
778
779
	public void test015() { // check behaviour of Scope.mostSpecificMethodBinding()
779
	public void test015() { // check behaviour of Scope.mostSpecificMethodBinding()
780
		this.runConformTest(
780
		this.runNegativeTest(
781
			new String[] {
781
			new String[] {
782
				"X.java",
782
				"X.java",
783
				"public class X {\n" +
783
				"public class X {\n" +
Lines 790-796 Link Here
790
				"	public static void count(int[] array, int[] ... values) { System.out.print(2); }\n" +
790
				"	public static void count(int[] array, int[] ... values) { System.out.print(2); }\n" +
791
				"}\n",
791
				"}\n",
792
			},
792
			},
793
			"1"
793
			"----------\n" + 
794
			"1. ERROR in X.java (at line 3)\n" + 
795
			"	Y.count(new int[0]);\n" + 
796
			"	  ^^^^^\n" + 
797
			"The method count(int[], int[]) is ambiguous for the type Y\n" + 
798
			"----------\n"
794
		);
799
		);
795
	}
800
	}
796
801
Lines 1232-1238 Link Here
1232
	}
1237
	}
1233
	//https://bugs.eclipse.org/bugs/show_bug.cgi?id=102631
1238
	//https://bugs.eclipse.org/bugs/show_bug.cgi?id=102631
1234
	public void test033() {
1239
	public void test033() {
1235
		this.runConformTest(
1240
		this.runNegativeTest(
1236
			new String[] {
1241
			new String[] {
1237
				"X.java",
1242
				"X.java",
1238
				"public class X {\n" +
1243
				"public class X {\n" +
Lines 1246-1252 Link Here
1246
				"	}\n" +
1251
				"	}\n" +
1247
				"}\n",
1252
				"}\n",
1248
			},
1253
			},
1249
			"112");
1254
			"----------\n" + 
1255
			"1. ERROR in X.java (at line 6)\n" + 
1256
			"	x.a(true);\n" + 
1257
			"	  ^\n" + 
1258
			"The method a(boolean, Object[]) is ambiguous for the type X\n" + 
1259
			"----------\n" + 
1260
			"2. ERROR in X.java (at line 7)\n" + 
1261
			"	x.a(true, \"foobar\");\n" + 
1262
			"	  ^\n" + 
1263
			"The method a(boolean, Object[]) is ambiguous for the type X\n" + 
1264
			"----------\n");
1250
		this.runNegativeTest(
1265
		this.runNegativeTest(
1251
			new String[] {
1266
			new String[] {
1252
				"X.java",
1267
				"X.java",
Lines 2756-2759 Link Here
2756
			"Type safety: A generic array of Class<? extends Object&Serializable&Comparable<?>> is created for a varargs parameter\n" + 
2771
			"Type safety: A generic array of Class<? extends Object&Serializable&Comparable<?>> is created for a varargs parameter\n" + 
2757
			"----------\n");
2772
			"----------\n");
2758
	}
2773
	}
2759
}
2774
	// https://bugs.eclipse.org/bugs/show_bug.cgi?id=346042
2775
	public void test069() throws Exception {
2776
		if (this.complianceLevel < ClassFileConstants.JDK1_5) return;
2777
		this.runNegativeTest(
2778
			new String[] {
2779
				"p1/B.java",
2780
				"package p1;\n" +
2781
				"class A {\n" +
2782
				"}\n" +
2783
				"public class B extends A {\n" +
2784
				" public void foo(A... args) {\n" +
2785
				" }\n" +
2786
				"}\n",
2787
				"p2/C.java",
2788
				"package p2;\n" +
2789
				"import p1.B;\n" +
2790
				"public class C {\n" +
2791
				"\n" +
2792
				" public static final void main(String[] args) {\n" +
2793
				"   (new B()).foo(new B(), new B());\n" +
2794
				" }\n" +
2795
				"}\n"
2796
			},
2797
			"----------\n" + 
2798
			"1. ERROR in p2\\C.java (at line 6)\n" + 
2799
			"	(new B()).foo(new B(), new B());\n" + 
2800
			"	          ^^^\n" + 
2801
			"The method foo(A...) of type B is not applicable as the formal varargs element type A is not accessible here\n" + 
2802
			"----------\n");
2803
	}
2804
	// https://bugs.eclipse.org/bugs/show_bug.cgi?id=346038
2805
	public void test070() throws Exception {
2806
		if (this.complianceLevel < ClassFileConstants.JDK1_5) return;
2807
		this.runConformTest(
2808
			new String[] {
2809
				"X.java",
2810
				"public class X {\n" +
2811
				"        public static void foo(int ...i) {}\n" +
2812
				"        public static void foo(double...d) {}\n" +
2813
				"        public static void main(String[] args) {\n" +
2814
				"            foo(1, 2, 3);\n" +
2815
				"            System.out.println (\"Done\");\n" +
2816
				"        }\n" +
2817
				"}\n"
2818
			},
2819
			"Done");
2820
	}
2821
	// https://bugs.eclipse.org/bugs/show_bug.cgi?id=346038
2822
	public void test070a() throws Exception {
2823
		if (this.complianceLevel < ClassFileConstants.JDK1_5) return;
2824
		this.runConformTest(
2825
			new String[] {
2826
				"X.java",
2827
				"public class X {\n" +
2828
				"        public static <T> void foo(int ...i) {}\n" +
2829
				"        public static <T> void foo(double...d) {}\n" +
2830
				"        public static void main(String[] args) {\n" +
2831
				"            foo(1, 2, 3);\n" +
2832
				"            System.out.println (\"Done\");\n" +
2833
				"        }\n" +
2834
				"}\n"
2835
			},
2836
			"Done");
2837
	}
2838
	// https://bugs.eclipse.org/bugs/show_bug.cgi?id=346038
2839
	public void test070b() throws Exception {
2840
		if (this.complianceLevel < ClassFileConstants.JDK1_5) return;
2841
		this.runConformTest(
2842
			new String[] {
2843
				"X.java",
2844
				"public class X {\n" +
2845
				"        public static void foo(int ...i) {}\n" +
2846
				"        public static void foo(double d1, double...d) {}\n" +
2847
				"        public static void main(String[] args) {\n" +
2848
				"            foo(1, 2, 3);     // foo NOT flagged ambiguous\n" +
2849
				"        }\n" +
2850
				"}\n" 
2851
			},
2852
			"");
2853
	}
2854
	// https://bugs.eclipse.org/bugs/show_bug.cgi?id=346038
2855
	public void test070c() { // check behaviour of Scope.mostSpecificMethodBinding()
2856
		this.runNegativeTest(
2857
			new String[] {
2858
				"X.java",
2859
				"public class X {\n" +
2860
				"    public static void main(String[] s) {\n" +
2861
				"        count(1);\n" +
2862
				"        count(1, 1);\n" +
2863
				"        count(1, 1, 1);\n" +
2864
				"    }\n" +
2865
				"    public static void count(int ... values) {}\n" +
2866
				"    public static void count(int i, int ... values) {}\n" +
2867
				"}\n",
2868
			},
2869
			"----------\n" + 
2870
			"1. ERROR in X.java (at line 3)\n" + 
2871
			"	count(1);\n" + 
2872
			"	^^^^^\n" + 
2873
			"The method count(int[]) is ambiguous for the type X\n" + 
2874
			"----------\n" + 
2875
			"2. ERROR in X.java (at line 4)\n" + 
2876
			"	count(1, 1);\n" + 
2877
			"	^^^^^\n" + 
2878
			"The method count(int[]) is ambiguous for the type X\n" + 
2879
			"----------\n" + 
2880
			"3. ERROR in X.java (at line 5)\n" + 
2881
			"	count(1, 1, 1);\n" + 
2882
			"	^^^^^\n" + 
2883
			"The method count(int[]) is ambiguous for the type X\n" + 
2884
			"----------\n");
2885
	}
2886
	// https://bugs.eclipse.org/bugs/show_bug.cgi?id=346038
2887
	public void test070d() { // check behaviour of Scope.mostSpecificMethodBinding()
2888
		this.runNegativeTest(
2889
			new String[] {
2890
				"X.java",
2891
				"public class X {\n" +
2892
				"	void b(boolean b, Object... o) {}\n" +
2893
				"	void b(Boolean... o) {}\n" +
2894
				"	void c(boolean b, boolean b2, Object... o) {}\n" +
2895
				"	void c(Boolean b, Object... o) {}\n" +
2896
				"	public static void main(String[] args) {\n" +
2897
				"		X x = new X();\n" +
2898
				"		x.b(true);\n" +
2899
				"		x.b(true, false);\n" +
2900
				"	}\n" +
2901
				"}\n",
2902
			},
2903
			"----------\n" +
2904
			"1. ERROR in X.java (at line 8)\r\n" +
2905
			"	x.b(true);\r\n" +
2906
			"	  ^\n" +
2907
			"The method b(boolean, Object[]) is ambiguous for the type X\n" +
2908
			"----------\n" +
2909
			"2. ERROR in X.java (at line 9)\r\n" +
2910
			"	x.b(true, false);\r\n" +
2911
			"	  ^\n" +
2912
			"The method b(boolean, Object[]) is ambiguous for the type X\n" +
2913
			"----------\n");
2914
	}
2915
	// https://bugs.eclipse.org/bugs/show_bug.cgi?id=346039
2916
	public void test071() { // check behaviour of Scope.mostSpecificMethodBinding()
2917
		this.runConformTest(
2918
			new String[] {
2919
				"X.java",
2920
				"public class X implements IClass{\n" +
2921
				"    X(IClass c, X t, IType... args) {\n" +
2922
				"	     System.out.println (\"1\");\n" +
2923
				"    }\n" +
2924
				"    X(IClass c, IType... args) {\n" +
2925
				"	    System.out.println (\"2\");\n" +
2926
				"    }\n" +
2927
				"    public static void main(String args[]) {\n" +
2928
				"        IClass c = null;\n" +
2929
				"        X t = null;\n" +
2930
				"        X t2 = new X(c, t);     // incorrectly flagged ambiguous\n" +
2931
				"    }\n" +
2932
				"}\n" +
2933
				"interface IType{}\n" +
2934
				"interface IClass extends IType{}\n"
2935
			},
2936
			"1");
2937
	}
2938
	// https://bugs.eclipse.org/bugs/show_bug.cgi?id=364672
2939
	public void test072() {
2940
		this.runConformTest(
2941
			new String[] {
2942
				"X.java",
2943
				"public class X {\n" + 
2944
				"	private class Z {}\n" + 
2945
				"	public void foo() {\n" + 
2946
				"			Z[] zs = null;\n" + 
2947
				"			Y.bar(zs, new Z());\n" + 
2948
				"	}\n" + 
2949
				"	public static void main(String[] args) {}\n" + 
2950
				"}",
2951
				"Y.java",
2952
				"public class Y {\n" + 
2953
				"	public native static <T> void bar(T[] t, T t1, T... t2);\n" + 
2954
				"}"
2955
			},
2956
			"");
2957
	}
2958
	// https://bugs.eclipse.org/bugs/show_bug.cgi?id=364672
2959
	public void test073() {
2960
		this.runConformTest(
2961
			new String[] {
2962
				"X.java",
2963
				"public class X {\n" + 
2964
				"	public static final String CONSTANT = \"\";\n" + 
2965
				"	private static class A {\n" + 
2966
				"		A(String s, String s2, String s3, A... a) {}\n" + 
2967
				"	}\n" + 
2968
				"	private static class B extends A {\n" + 
2969
				"		B(String s, String s2) {\n" + 
2970
				"			super(s, s2, CONSTANT);\n" + 
2971
				"		}\n" + 
2972
				"	}\n" + 
2973
				"	private static void foo(Object o, A ... a) {\n" + 
2974
				"	}\n" + 
2975
				"	private static B bar() {\n" + 
2976
				"		return null;\n" + 
2977
				"	}\n" + 
2978
				"	public static void main(String[] args) {\n" + 
2979
				"		Object o = null;\n" + 
2980
				"		foo(o, bar(), bar());\n" + 
2981
				"	}\n" + 
2982
				"}"
2983
			},
2984
			"");
2985
	}
2986
	// https://bugs.eclipse.org/bugs/show_bug.cgi?id=364672
2987
	public void test074() throws Exception {
2988
		this.runNegativeTest(
2989
			new String[] {
2990
				"p1/B.java",
2991
				"package p1;\n" +
2992
				"class A {}\n" +
2993
				"public class B extends A {\n" +
2994
				" public B(A... args) {}\n" +
2995
				" public B() {}\n" +
2996
				"}\n",
2997
				"p2/C.java",
2998
				"package p2;\n" +
2999
				"import p1.B;\n" +
3000
				"public class C {\n" +
3001
				"	public static final void main(String[] args) {\n" +
3002
				"		new B(new B(), new B());\n" +
3003
				"	}\n" +
3004
				"}\n"
3005
			},
3006
			"----------\n" + 
3007
			"1. ERROR in p2\\C.java (at line 5)\n" + 
3008
			"	new B(new B(), new B());\n" + 
3009
			"	^^^^^^^^^^^^^^^^^^^^^^^\n" + 
3010
			"The constructor B(A...) of type B is not applicable as the formal varargs element type A is not accessible here\n" + 
3011
			"----------\n");
3012
	}
3013
}
(-)a/org.eclipse.jdt.core.tests.compiler/src/org/eclipse/jdt/core/tests/compiler/regression/XLargeTest.java (-1 / +95 lines)
Lines 1-5 Link Here
1
/*******************************************************************************
1
/*******************************************************************************
2
 * Copyright (c) 2005, 2011 IBM Corporation and others.
2
 * Copyright (c) 2005, 2012 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 30-35 Link Here
30
	return buildAllCompliancesTestSuite(testClass());
30
	return buildAllCompliancesTestSuite(testClass());
31
}
31
}
32
32
33
// https://bugs.eclipse.org/bugs/show_bug.cgi?id=368435
34
public void test368435() {
35
	Map settings = getCompilerOptions();
36
	settings.put(CompilerOptions.OPTION_PreserveUnusedLocal, CompilerOptions.OPTIMIZE_OUT);
37
	StringBuffer sourceCode = new StringBuffer(
38
			"public class X {\n" +
39
			"    public static void main(String[] args) {\n" +
40
			"        System.out.println(\"SUCCESS\");\n" +
41
			"    }\n" +
42
			"    public void print() {\n" +
43
			"        int i = 0;\n" +
44
			"        if (System.currentTimeMillis() > 17000L) {\n" +
45
			"            System.out.println(i++);\n");
46
	
47
	for (int i = 0; i < 5000; i++) {
48
		sourceCode.append("\t\t		System.out.println(\"xyz\");\n");
49
	}
50
	sourceCode.append("}\n}\n}\n");
51
	
52
	this.runConformTest(
53
			new String[] {
54
					"X.java",
55
					sourceCode.toString()
56
			},
57
			"SUCCESS",
58
			null,
59
			true,
60
			null,
61
			settings,
62
			null);
63
}
64
// https://bugs.eclipse.org/bugs/show_bug.cgi?id=368435
65
public void test368435b() {
66
	Map settings = getCompilerOptions();
67
	settings.put(CompilerOptions.OPTION_PreserveUnusedLocal, CompilerOptions.OPTIMIZE_OUT);
68
	StringBuffer sourceCode = new StringBuffer(
69
			"public class X {\n" +
70
			"    public static void main(String[] args) {\n" +
71
			"        System.out.println(\"SUCCESS\");\n" +
72
			"    }\n" +
73
			"    public X() {\n" +
74
			"        int i = 0;\n" +
75
			"        if (System.currentTimeMillis() > 17000L) {\n" +
76
			"            System.out.println(i++);\n");
77
	
78
	for (int i = 0; i < 5000; i++) {
79
		sourceCode.append("\t\t		System.out.println(\"xyz\");\n");
80
	}
81
	sourceCode.append("}\n}\n}\n");
82
	
83
	this.runConformTest(
84
			new String[] {
85
					"X.java",
86
					sourceCode.toString()
87
			},
88
			"SUCCESS",
89
			null,
90
			true,
91
			null,
92
			settings,
93
			null);
94
}
95
// https://bugs.eclipse.org/bugs/show_bug.cgi?id=368435
96
public void test368435c() {
97
	Map settings = getCompilerOptions();
98
	settings.put(CompilerOptions.OPTION_PreserveUnusedLocal, CompilerOptions.OPTIMIZE_OUT);
99
	StringBuffer sourceCode = new StringBuffer(
100
			"public class X {\n" +
101
			"    public static void main(String[] args) {\n" +
102
			"        System.out.println(\"SUCCESS\");\n" +
103
			"    }\n" +
104
			"    {\n" +
105
			"        int i = 0;\n" +
106
			"        if (System.currentTimeMillis() > 17000L) {\n" +
107
			"            System.out.println(i++);\n");
108
	
109
	for (int i = 0; i < 5000; i++) {
110
		sourceCode.append("\t\t		System.out.println(\"xyz\");\n");
111
	}
112
	sourceCode.append("}\n}\n}\n");
113
	
114
	this.runConformTest(
115
			new String[] {
116
					"X.java",
117
					sourceCode.toString()
118
			},
119
			"SUCCESS",
120
			null,
121
			true,
122
			null,
123
			settings,
124
			null);
125
}
126
33
public void test001() {
127
public void test001() {
34
	this.runConformTest(
128
	this.runConformTest(
35
		new String[] {
129
		new String[] {
(-)a/org.eclipse.jdt.core.tests.compiler/src/org/eclipse/jdt/core/tests/util/TestVerifier.java (-218 / +239 lines)
Lines 1-5 Link Here
1
/*******************************************************************************
1
/*******************************************************************************
2
 * Copyright (c) 2000, 2010 IBM Corporation and others.
2
 * Copyright (c) 2000, 2011 IBM Corporation and others.
3
 * All rights reserved. This program and the accompanying materials
3
 * All rights reserved. This program and the accompanying materials
4
 * are made available under the terms of the Eclipse Public License v1.0
4
 * are made available under the terms of the Eclipse Public License v1.0
5
 * which accompanies this distribution, and is available at
5
 * which accompanies this distribution, and is available at
Lines 116-122 Link Here
116
	}
116
	}
117
	String fileName = dir + File.separator + simpleName + ".java";
117
	String fileName = dir + File.separator + simpleName + ".java";
118
	Util.writeToFile(getVerifyTestsCode(), fileName);
118
	Util.writeToFile(getVerifyTestsCode(), fileName);
119
	BatchCompiler.compile("\"" + fileName + "\" -d \"" + verifierDir + "\" -classpath \"" + Util.getJavaClassLibsAsString() + "\"", new PrintWriter(System.out), new PrintWriter(System.err), null/*progress*/);
119
	BatchCompiler.compile("\"" + fileName + "\" -d \"" + verifierDir + "\" -warn:-resource -classpath \"" + Util.getJavaClassLibsAsString() + "\"", new PrintWriter(System.out), new PrintWriter(System.err), null/*progress*/);
120
}
120
}
121
public void execute(String className, String[] classpaths) {
121
public void execute(String className, String[] classpaths) {
122
	this.outputBuffer = new StringBuffer();
122
	this.outputBuffer = new StringBuffer();
Lines 145-366 Link Here
145
 */
145
 */
146
private String getVerifyTestsCode() {
146
private String getVerifyTestsCode() {
147
	return
147
	return
148
		"/*******************************************************************************" +
148
		"/*******************************************************************************\n" + 
149
		" * Copyright (c) 2000, 2005 IBM Corporation and others." +
149
		" * Copyright (c) 2000, 2011 IBM Corporation and others.\n" + 
150
		" * All rights reserved. This program and the accompanying materials" +
150
		" * All rights reserved. This program and the accompanying materials\n" + 
151
		" * are made available under the terms of the Eclipse Public License v1.0" +
151
		" * are made available under the terms of the Eclipse Public License v1.0\n" + 
152
		" * which accompanies this distribution, and is available at" +
152
		" * which accompanies this distribution, and is available at\n" + 
153
		" * http://www.eclipse.org/legal/epl-v10.html" +
153
		" * http://www.eclipse.org/legal/epl-v10.html\n" + 
154
		" *" +
154
		" *\n" + 
155
		" * Contributors:" +
155
		" * Contributors:\n" + 
156
		" *     IBM Corporation - initial API and implementation" +
156
		" *     IBM Corporation - initial API and implementation\n" + 
157
		" *******************************************************************************/" +
157
		" *******************************************************************************/\n" + 
158
		"package org.eclipse.jdt.core.tests.util;\n" +
158
		"package org.eclipse.jdt.core.tests.util;\n" + 
159
		"\n" +
159
		"\n" + 
160
		"import java.lang.reflect.*;\n" +
160
		"import java.io.DataInputStream;\n" + 
161
		"import java.io.*;\n" +
161
		"import java.io.DataOutputStream;\n" + 
162
		"import java.net.*;\n" +
162
		"import java.io.File;\n" + 
163
		"import java.util.*;\n" +
163
		"import java.io.FileInputStream;\n" + 
164
		"\n" +
164
		"import java.io.FileNotFoundException;\n" + 
165
		"/******************************************************\n" +
165
		"import java.io.IOException;\n" + 
166
		" * \n" +
166
		"import java.io.InputStream;\n" + 
167
		" * IMPORTANT NOTE: If modifying this class, copy the source to TestVerifier#getVerifyTestsCode()\n" +
167
		"import java.lang.reflect.InvocationTargetException;\n" + 
168
		" * (see this method for details)\n" +
168
		"import java.lang.reflect.Method;\n" + 
169
		" * \n" +
169
		"import java.net.ServerSocket;\n" + 
170
		" ******************************************************/\n" +
170
		"import java.net.Socket;\n" + 
171
		"\n" +
171
		"import java.util.StringTokenizer;\n" + 
172
		"public class VerifyTests {\n" +
172
		"\n" + 
173
		"	int portNumber;\n" +
173
		"/******************************************************\n" + 
174
		"	Socket socket;\n" +
174
		" *\n" + 
175
		"\n" +
175
		" * IMPORTANT NOTE: If modifying this class, copy the source to TestVerifier#getVerifyTestsCode()\n" + 
176
		"/**\n" +
176
		" * (see this method for details)\n" + 
177
		" * NOTE: Code copied from junit.util.TestCaseClassLoader.\n" +
177
		" *\n" + 
178
		" *\n" +
178
		" ******************************************************/\n" + 
179
		" * A custom class loader which enables the reloading\n" +
179
		"\n" + 
180
		" * of classes for each test run. The class loader\n" +
180
		"public class VerifyTests {\n" + 
181
		" * can be configured with a list of package paths that\n" +
181
		"	int portNumber;\n" + 
182
		" * should be excluded from loading. The loading\n" +
182
		"	Socket socket;\n" + 
183
		" * of these packages is delegated to the system class\n" +
183
		"\n" + 
184
		" * loader. They will be shared across test runs.\n" +
184
		"/**\n" + 
185
		" * <p>\n" +
185
		" * NOTE: Code copied from junit.util.TestCaseClassLoader.\n" + 
186
		" * The list of excluded package paths is specified in\n" +
186
		" *\n" + 
187
		" * a properties file \"excluded.properties\" that is located in \n" +
187
		" * A custom class loader which enables the reloading\n" + 
188
		" * the same place as the TestCaseClassLoader class.\n" +
188
		" * of classes for each test run. The class loader\n" + 
189
		" * <p>\n" +
189
		" * can be configured with a list of package paths that\n" + 
190
		" * <b>Known limitation:</b> the VerifyClassLoader cannot load classes\n" +
190
		" * should be excluded from loading. The loading\n" + 
191
		" * from jar files.\n" +
191
		" * of these packages is delegated to the system class\n" + 
192
		" */\n" +
192
		" * loader. They will be shared across test runs.\n" + 
193
		"\n" +
193
		" * <p>\n" + 
194
		"\n" +
194
		" * The list of excluded package paths is specified in\n" + 
195
		"public class VerifyClassLoader extends ClassLoader {\n" +
195
		" * a properties file \"excluded.properties\" that is located in\n" + 
196
		"	/** scanned class path */\n" +
196
		" * the same place as the TestCaseClassLoader class.\n" + 
197
		"	private String[] fPathItems;\n" +
197
		" * <p>\n" + 
198
		"	\n" +
198
		" * <b>Known limitation:</b> the VerifyClassLoader cannot load classes\n" + 
199
		"	/** excluded paths */\n" +
199
		" * from jar files.\n" + 
200
		"	private String[] fExcluded= {};\n" +
200
		" */\n" + 
201
		"\n" +
201
		"\n" + 
202
		"	/**\n" +
202
		"\n" + 
203
		"	 * Constructs a VerifyClassLoader. It scans the class path\n" +
203
		"public class VerifyClassLoader extends ClassLoader {\n" + 
204
		"	 * and the excluded package paths\n" +
204
		"	/** scanned class path */\n" + 
205
		"	 */\n" +
205
		"	private String[] pathItems;\n" + 
206
		"	public VerifyClassLoader() {\n" +
206
		"\n" + 
207
		"		super();\n" +
207
		"	/** excluded paths */\n" + 
208
		"		String classPath= System.getProperty(\"java.class.path\");\n" +
208
		"	private String[] excluded= {};\n" + 
209
		"		String separator= System.getProperty(\"path.separator\");\n" +
209
		"\n" + 
210
		"		\n" +
210
		"	/**\n" + 
211
		"		// first pass: count elements\n" +
211
		"	 * Constructs a VerifyClassLoader. It scans the class path\n" + 
212
		"		StringTokenizer st= new StringTokenizer(classPath, separator);\n" +
212
		"	 * and the excluded package paths\n" + 
213
		"		int i= 0;\n" +
213
		"	 */\n" + 
214
		"		while (st.hasMoreTokens()) {\n" +
214
		"	public VerifyClassLoader() {\n" + 
215
		"			st.nextToken();\n" +
215
		"		super();\n" + 
216
		"			i++;\n" +
216
		"		String classPath= System.getProperty(\"java.class.path\");\n" + 
217
		"		}\n" +
217
		"		String separator= System.getProperty(\"path.separator\");\n" + 
218
		"		// second pass: split\n" +
218
		"\n" + 
219
		"		fPathItems= new String[i];\n" +
219
		"		// first pass: count elements\n" + 
220
		"		st= new StringTokenizer(classPath, separator);\n" +
220
		"		StringTokenizer st= new StringTokenizer(classPath, separator);\n" + 
221
		"		i= 0;\n" +
221
		"		int i= 0;\n" + 
222
		"		while (st.hasMoreTokens()) {\n" +
222
		"		while (st.hasMoreTokens()) {\n" + 
223
		"			fPathItems[i++]= st.nextToken();\n" +
223
		"			st.nextToken();\n" + 
224
		"		}\n" +
224
		"			i++;\n" + 
225
		"\n" +
225
		"		}\n" + 
226
		"	}\n" +
226
		"		// second pass: split\n" + 
227
		"	public java.net.URL getResource(String name) {\n" +
227
		"		this.pathItems= new String[i];\n" + 
228
		"		return ClassLoader.getSystemResource(name);\n" +
228
		"		st= new StringTokenizer(classPath, separator);\n" + 
229
		"	}\n" +
229
		"		i= 0;\n" + 
230
		"	public InputStream getResourceAsStream(String name) {\n" +
230
		"		while (st.hasMoreTokens()) {\n" + 
231
		"		return ClassLoader.getSystemResourceAsStream(name);\n" +
231
		"			this.pathItems[i++]= st.nextToken();\n" + 
232
		"	}\n" +
232
		"		}\n" + 
233
		"	protected boolean isExcluded(String name) {\n" +
233
		"\n" + 
234
		"		// exclude the \"java\" packages.\n" +
234
		"	}\n" + 
235
		"		// They always need to be excluded so that they are loaded by the system class loader\n" +
235
		"	public java.net.URL getResource(String name) {\n" + 
236
		"		if (name.startsWith(\"java\"))\n" +
236
		"		return ClassLoader.getSystemResource(name);\n" + 
237
		"			return true;\n" +
237
		"	}\n" + 
238
		"			\n" +
238
		"	public InputStream getResourceAsStream(String name) {\n" + 
239
		"		// exclude the user defined package paths\n" +
239
		"		return ClassLoader.getSystemResourceAsStream(name);\n" + 
240
		"		for (int i= 0; i < fExcluded.length; i++) {\n" +
240
		"	}\n" + 
241
		"			if (name.startsWith(fExcluded[i])) {\n" +
241
		"	protected boolean isExcluded(String name) {\n" + 
242
		"				return true;\n" +
242
		"		// exclude the \"java\" packages.\n" + 
243
		"			}\n" +
243
		"		// They always need to be excluded so that they are loaded by the system class loader\n" + 
244
		"		}\n" +
244
		"		if (name.startsWith(\"java\"))\n" + 
245
		"		return false;	\n" +
245
		"			return true;\n" + 
246
		"	}\n" +
246
		"\n" + 
247
		"	public synchronized Class loadClass(String name, boolean resolve)\n" +
247
		"		// exclude the user defined package paths\n" + 
248
		"		throws ClassNotFoundException {\n" +
248
		"		for (int i= 0; i < this.excluded.length; i++) {\n" + 
249
		"			\n" +
249
		"			if (name.startsWith(this.excluded[i])) {\n" + 
250
		"		Class c= findLoadedClass(name);\n" +
250
		"				return true;\n" + 
251
		"		if (c != null)\n" +
251
		"			}\n" + 
252
		"			return c;\n" +
252
		"		}\n" + 
253
		"		//\n" +
253
		"		return false;\n" + 
254
		"		// Delegate the loading of excluded classes to the\n" +
254
		"	}\n" + 
255
		"		// standard class loader.\n" +
255
		"	public synchronized Class loadClass(String name, boolean resolve)\n" + 
256
		"		//\n" +
256
		"		throws ClassNotFoundException {\n" + 
257
		"		if (isExcluded(name)) {\n" +
257
		"\n" + 
258
		"			try {\n" +
258
		"		Class c= findLoadedClass(name);\n" + 
259
		"				c= findSystemClass(name);\n" +
259
		"		if (c != null)\n" + 
260
		"				return c;\n" +
260
		"			return c;\n" + 
261
		"			} catch (ClassNotFoundException e) {\n" +
261
		"		//\n" + 
262
		"				// keep searching\n" +
262
		"		// Delegate the loading of excluded classes to the\n" + 
263
		"			}\n" +
263
		"		// standard class loader.\n" + 
264
		"		}\n" +
264
		"		//\n" + 
265
		"		File file= locate(name);\n" +
265
		"		if (isExcluded(name)) {\n" + 
266
		"		if (file == null)\n" +
266
		"			try {\n" + 
267
		"			throw new ClassNotFoundException();\n" +
267
		"				c= findSystemClass(name);\n" + 
268
		"		byte data[]= loadClassData(file);\n" +
268
		"				return c;\n" + 
269
		"		c= defineClass(name, data, 0, data.length);\n" +
269
		"			} catch (ClassNotFoundException e) {\n" + 
270
		"		if (resolve) \n" +
270
		"				// keep searching\n" + 
271
		"			resolveClass(c);\n" +
271
		"			}\n" + 
272
		"		return c;\n" +
272
		"		}\n" + 
273
		"	}\n" +
273
		"		File file= locate(name);\n" + 
274
		"	private byte[] loadClassData(File f) throws ClassNotFoundException {\n" +
274
		"		if (file == null)\n" + 
275
		"		try {\n" +
275
		"			throw new ClassNotFoundException();\n" + 
276
		"			//System.out.println(\"loading: \"+f.getPath());\n" +
276
		"		byte data[]= loadClassData(file);\n" + 
277
		"			FileInputStream stream= new FileInputStream(f);\n" +
277
		"		c= defineClass(name, data, 0, data.length);\n" + 
278
		"			\n" +
278
		"		if (resolve)\n" + 
279
		"			try {\n" +
279
		"			resolveClass(c);\n" + 
280
		"				byte[] b= new byte[stream.available()];\n" +
280
		"		return c;\n" + 
281
		"				stream.read(b);\n" +
281
		"	}\n" + 
282
		"				stream.close();\n" +
282
		"	private byte[] loadClassData(File f) throws ClassNotFoundException {\n" + 
283
		"				return b;\n" +
283
		"		FileInputStream stream = null;\n" + 
284
		"			}\n" +
284
		"		try {\n" + 
285
		"			catch (IOException e) {\n" +
285
		"			//System.out.println(\"loading: \"+f.getPath());\n" + 
286
		"				throw new ClassNotFoundException();\n" +
286
		"			stream = new FileInputStream(f);\n" + 
287
		"			}\n" +
287
		"\n" + 
288
		"		}\n" +
288
		"			try {\n" + 
289
		"		catch (FileNotFoundException e) {\n" +
289
		"				byte[] b= new byte[stream.available()];\n" + 
290
		"			throw new ClassNotFoundException();\n" +
290
		"				stream.read(b);\n" + 
291
		"		}\n" +
291
		"				return b;\n" + 
292
		"	}\n" +
292
		"			}\n" + 
293
		"	/**\n" +
293
		"			catch (IOException e) {\n" + 
294
		"	 * Locate the given file.\n" +
294
		"				throw new ClassNotFoundException();\n" + 
295
		"	 * @return Returns null if file couldn\'t be found.\n" +
295
		"			}\n" + 
296
		"	 */\n" +
296
		"		}\n" + 
297
		"	private File locate(String fileName) { \n" +
297
		"		catch (FileNotFoundException e) {\n" + 
298
		"		if (fileName != null) {\n" +
298
		"			throw new ClassNotFoundException();\n" + 
299
		"		  fileName= fileName.replace(\'.\', \'/\')+\".class\";\n" +
299
		"		} finally {\n" + 
300
		"		  File path= null;\n" +
300
		"			if (stream != null) {\n" + 
301
		"			for (int i= 0; i < fPathItems.length; i++) {\n" +
301
		"				try {\n" + 
302
		"				path= new File(fPathItems[i], fileName);\n" +
302
		"					stream.close();\n" + 
303
		"				if (path.exists())\n" +
303
		"				} catch (IOException e) {\n" + 
304
		"					return path;\n" +
304
		"					/* ignore */\n" + 
305
		"			}\n" +
305
		"				}\n" + 
306
		"		}\n" +
306
		"			}\n" + 
307
		"		return null;\n" +
307
		"		}\n" + 
308
		"	}\n" +
308
		"	}\n" + 
309
		"}\n" +
309
		"	/**\n" + 
310
		"	\n" +
310
		"	 * Locate the given file.\n" + 
311
		"public void loadAndRun(String className) throws Throwable {\n" +
311
		"	 * @return Returns null if file couldn't be found.\n" + 
312
		"	//System.out.println(\"Loading \" + className + \"...\");\n" +
312
		"	 */\n" + 
313
		"	Class testClass = new VerifyClassLoader().loadClass(className);\n" +
313
		"	private File locate(String fileName) {\n" + 
314
		"	//System.out.println(\"Loaded \" + className);\n" +
314
		"		if (fileName != null) {\n" + 
315
		"	try {\n" +
315
		"			fileName= fileName.replace('.', '/')+\".class\";\n" + 
316
		"		Method main = testClass.getMethod(\"main\", new Class[] {String[].class});\n" +
316
		"			File path= null;\n" + 
317
		"		//System.out.println(\"Running \" + className);\n" +
317
		"			for (int i= 0; i < this.pathItems.length; i++) {\n" + 
318
		"		main.invoke(null, new Object[] {new String[] {}});\n" +
318
		"				path= new File(this.pathItems[i], fileName);\n" + 
319
		"		//System.out.println(\"Finished running \" + className);\n" +
319
		"				if (path.exists())\n" + 
320
		"	} catch (NoSuchMethodException e) {\n" +
320
		"					return path;\n" + 
321
		"		return;\n" +
321
		"			}\n" + 
322
		"	} catch (InvocationTargetException e) {\n" +
322
		"		}\n" + 
323
		"		throw e.getTargetException();\n" +
323
		"		return null;\n" + 
324
		"	}\n" +
324
		"	}\n" + 
325
		"}\n" +
325
		"}\n" + 
326
		"public static void main(String[] args) throws IOException {\n" +
326
		"\n" + 
327
		"	VerifyTests verify = new VerifyTests();\n" +
327
		"public void loadAndRun(String className) throws Throwable {\n" + 
328
		"	verify.portNumber = Integer.parseInt(args[0]);\n" +
328
		"	//System.out.println(\"Loading \" + className + \"...\");\n" + 
329
		"	verify.run();\n" +
329
		"	Class testClass = new VerifyClassLoader().loadClass(className);\n" + 
330
		"}\n" +
330
		"	//System.out.println(\"Loaded \" + className);\n" + 
331
		"public void run() throws IOException {\n" +
331
		"	try {\n" + 
332
		"	ServerSocket server = new ServerSocket(this.portNumber);\n" +
332
		"		Method main = testClass.getMethod(\"main\", new Class[] {String[].class});\n" + 
333
		"	this.socket = server.accept();\n" +
333
		"		//System.out.println(\"Running \" + className);\n" + 
334
		"	this.socket.setTcpNoDelay(true);\n" +
334
		"		main.invoke(null, new Object[] {new String[] {}});\n" + 
335
		"	server.close();\n" +
335
		"		//System.out.println(\"Finished running \" + className);\n" + 
336
		"\n" +
336
		"	} catch (NoSuchMethodException e) {\n" + 
337
		"	DataInputStream in = new DataInputStream(this.socket.getInputStream());\n" +
337
		"		return;\n" + 
338
		"	final DataOutputStream out = new DataOutputStream(this.socket.getOutputStream());\n" +
338
		"	} catch (InvocationTargetException e) {\n" + 
339
		"	while (true) {\n" +
339
		"		throw e.getTargetException();\n" + 
340
		"		final String className = in.readUTF();\n" +
340
		"	}\n" + 
341
		"		Thread thread = new Thread() {\n" +
341
		"}\n" + 
342
		"			public void run() {\n" +
342
		"public static void main(String[] args) throws IOException {\n" + 
343
		"				try {\n" +
343
		"	VerifyTests verify = new VerifyTests();\n" + 
344
		"					loadAndRun(className);\n" +
344
		"	verify.portNumber = Integer.parseInt(args[0]);\n" + 
345
		"					out.writeBoolean(true);\n" +
345
		"	verify.run();\n" + 
346
		"					System.err.println(VerifyTests.class.getName());\n" +
346
		"}\n" + 
347
		"					System.out.println(VerifyTests.class.getName());\n" +
347
		"public void run() throws IOException {\n" + 
348
		"				} catch (Throwable e) {\n" +
348
		"	ServerSocket server = new ServerSocket(this.portNumber);\n" + 
349
		"					e.printStackTrace();\n" +
349
		"	this.socket = server.accept();\n" + 
350
		"					try {\n" +
350
		"	this.socket.setTcpNoDelay(true);\n" + 
351
		"						System.err.println(VerifyTests.class.getName());\n" +
351
		"	server.close();\n" + 
352
		"						System.out.println(VerifyTests.class.getName());\n" +
352
		"\n" + 
353
		"						out.writeBoolean(false);\n" +
353
		"	DataInputStream in = new DataInputStream(this.socket.getInputStream());\n" + 
354
		"					} catch (IOException e1) {\n" +
354
		"	final DataOutputStream out = new DataOutputStream(this.socket.getOutputStream());\n" + 
355
		"						// ignore\n" +
355
		"	while (true) {\n" + 
356
		"					}\n" +
356
		"		final String className = in.readUTF();\n" + 
357
		"				}\n" +
357
		"		Thread thread = new Thread() {\n" + 
358
		"			}\n" +
358
		"			public void run() {\n" + 
359
		"		};\n" +
359
		"				try {\n" + 
360
		"		thread.start();\n" +
360
		"					loadAndRun(className);\n" + 
361
		"	}\n" +
361
		"					out.writeBoolean(true);\n" + 
362
		"}\n" +
362
		"					System.err.println(VerifyTests.class.getName());\n" + 
363
		"}\n";
363
		"					System.out.println(VerifyTests.class.getName());\n" + 
364
		"				} catch (Throwable e) {\n" + 
365
		"					e.printStackTrace();\n" + 
366
		"					try {\n" + 
367
		"						System.err.println(VerifyTests.class.getName());\n" + 
368
		"						System.out.println(VerifyTests.class.getName());\n" + 
369
		"						out.writeBoolean(false);\n" + 
370
		"					} catch (IOException e1) {\n" + 
371
		"						e1.printStackTrace();\n" + 
372
		"					}\n" + 
373
		"				}\n" + 
374
		"				try {\n" + 
375
		"					out.flush();\n" + 
376
		"				} catch (IOException e) {\n" + 
377
		"					e.printStackTrace();\n" + 
378
		"				}\n" + 
379
		"			}\n" + 
380
		"		};\n" + 
381
		"		thread.start();\n" + 
382
		"	}\n" + 
383
		"}\n" + 
384
		"}";
364
}
385
}
365
private void launchAndRun(String className, String[] classpaths, String[] programArguments, String[] vmArguments) {
386
private void launchAndRun(String className, String[] classpaths, String[] programArguments, String[] vmArguments) {
366
	// we won't reuse the vm, shut the existing one if running
387
	// we won't reuse the vm, shut the existing one if running
(-)a/org.eclipse.jdt.core.tests.compiler/src/org/eclipse/jdt/core/tests/util/Util.java (+28 lines)
Lines 1348-1353 Link Here
1348
        }
1348
        }
1349
    }
1349
    }
1350
}
1350
}
1351
1352
/**
1353
 * Zips the given files into the given jar. All the files are kept at the root of the zip. 
1354
 */
1355
public static void zipFiles(File[] files, String zipPath) throws IOException {
1356
	File zipFile = new File(zipPath);
1357
	if (zipFile.exists()) {
1358
		if (!delete(zipFile))
1359
			throw new IOException("Could not delete " + zipPath);
1360
		// ensure the new zip file has a different timestamp than the previous one
1361
		int timeToWait = 1000; // some platform (like Linux) have a 1s granularity)
1362
		waitAtLeast(timeToWait);
1363
	} else {
1364
		zipFile.getParentFile().mkdirs();
1365
	}
1366
	ZipOutputStream zip = new ZipOutputStream(new FileOutputStream(zipFile));
1367
	try {
1368
		for (int i = 0, length = files.length; i < length; i++) {
1369
			File file = files[i];
1370
			ZipEntry entry = new ZipEntry(file.getName());
1371
			zip.putNextEntry(entry);
1372
			zip.write(org.eclipse.jdt.internal.compiler.util.Util.getFileByteContent(file));
1373
			zip.closeEntry();
1374
		}
1375
	} finally {
1376
		zip.close();
1377
	}
1378
}
1351
/**
1379
/**
1352
 * Returns the compilation errors / warnings for the given CompilationResult.
1380
 * Returns the compilation errors / warnings for the given CompilationResult.
1353
 *
1381
 *
(-)a/org.eclipse.jdt.core.tests.compiler/src/org/eclipse/jdt/core/tests/util/VerifyTests.java (-5 / +13 lines)
Lines 1-5 Link Here
1
/*******************************************************************************
1
/*******************************************************************************
2
 * Copyright (c) 2000, 2010 IBM Corporation and others.
2
 * Copyright (c) 2000, 2011 IBM Corporation and others.
3
 * All rights reserved. This program and the accompanying materials
3
 * All rights reserved. This program and the accompanying materials
4
 * are made available under the terms of the Eclipse Public License v1.0
4
 * are made available under the terms of the Eclipse Public License v1.0
5
 * which accompanies this distribution, and is available at
5
 * which accompanies this distribution, and is available at
Lines 10-19 Link Here
10
 *******************************************************************************/
10
 *******************************************************************************/
11
package org.eclipse.jdt.core.tests.util;
11
package org.eclipse.jdt.core.tests.util;
12
12
13
import java.lang.reflect.*;
13
import java.io.DataInputStream;
14
import java.io.*;
14
import java.io.DataOutputStream;
15
import java.net.*;
15
import java.io.File;
16
import java.util.*;
16
import java.io.FileInputStream;
17
import java.io.FileNotFoundException;
18
import java.io.IOException;
19
import java.io.InputStream;
20
import java.lang.reflect.InvocationTargetException;
21
import java.lang.reflect.Method;
22
import java.net.ServerSocket;
23
import java.net.Socket;
24
import java.util.StringTokenizer;
17
25
18
/******************************************************
26
/******************************************************
19
 *
27
 *
(-)a/org.eclipse.jdt.core.tests.compiler/test.xml (-3 / +4 lines)
Lines 1-6 Link Here
1
<?xml version="1.0"?>
1
<?xml version="1.0" encoding="UTF-8"?>
2
<!--
2
3
    Copyright (c) 2002, 2009 IBM Corporation and others.
3
<!--
4
    Copyright (c) 2002, 2011 IBM Corporation and others.
4
    All rights reserved. This program and the accompanying materials
5
    All rights reserved. This program and the accompanying materials
5
    are made available under the terms of the Eclipse Public License v1.0
6
    are made available under the terms of the Eclipse Public License v1.0
6
    which accompanies this distribution, and is available at
7
    which accompanies this distribution, and is available at
(-)a/org.eclipse.jdt.core.tests.model/.cvsignore (-1 lines)
Added Link Here
1
bin
(-)a/org.eclipse.jdt.core.tests.model/.settings/org.eclipse.core.runtime.prefs (+2 lines)
Added Link Here
1
eclipse.preferences.version=1
2
line.separator=\n
(-)a/org.eclipse.jdt.core.tests.model/META-INF/MANIFEST.MF (-2 / +3 lines)
Lines 2-8 Link Here
2
Bundle-ManifestVersion: 2
2
Bundle-ManifestVersion: 2
3
Bundle-Name: %pluginName
3
Bundle-Name: %pluginName
4
Bundle-SymbolicName: org.eclipse.jdt.core.tests.model;singleton:=true
4
Bundle-SymbolicName: org.eclipse.jdt.core.tests.model;singleton:=true
5
Bundle-Version: 3.8.0.qualifier
5
Bundle-Version: 3.8.1.qualifier
6
Bundle-ClassPath: jdtcoretestsmodel.jar
6
Bundle-ClassPath: jdtcoretestsmodel.jar
7
Bundle-Vendor: %providerName
7
Bundle-Vendor: %providerName
8
Bundle-Localization: plugin
8
Bundle-Localization: plugin
Lines 23-27 Link Here
23
 org.eclipse.team.core;bundle-version="[3.2.0,4.0.0)",
23
 org.eclipse.team.core;bundle-version="[3.2.0,4.0.0)",
24
 org.eclipse.text;bundle-version="[3.2.0,4.0.0)",
24
 org.eclipse.text;bundle-version="[3.2.0,4.0.0)",
25
 com.ibm.icu;bundle-version="3.4.4",
25
 com.ibm.icu;bundle-version="3.4.4",
26
 org.eclipse.core.filesystem;bundle-version="[1.2.0,2.0.0)"
26
 org.eclipse.core.filesystem;bundle-version="[1.2.0,2.0.0)",
27
 org.eclipse.jdt.annotation;bundle-version="[1.0.0,2.0.0)"
27
Bundle-RequiredExecutionEnvironment: J2SE-1.4
28
Bundle-RequiredExecutionEnvironment: J2SE-1.4
(-)a/org.eclipse.jdt.core.tests.model/plugin.xml (-1 / +2 lines)
Lines 1-5 Link Here
1
<?xml version="1.0" encoding="UTF-8"?>
1
<?xml version="1.0" encoding="UTF-8"?>
2
<?eclipse version="3.0"?>
<!--
2
<?eclipse version="3.0"?>
3
<!--
3
    Copyright (c) 2002, 2009 IBM Corporation and others.
4
    Copyright (c) 2002, 2009 IBM Corporation and others.
4
    All rights reserved. This program and the accompanying materials
5
    All rights reserved. This program and the accompanying materials
5
    are made available under the terms of the Eclipse Public License v1.0
6
    are made available under the terms of the Eclipse Public License v1.0
(-)a/org.eclipse.jdt.core.tests.model/src/org/eclipse/jdt/core/tests/dom/ASTConverter15JLS4Test.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 186342 - [compiler][null] Using annotations for null checking
10
 *******************************************************************************/
11
 *******************************************************************************/
11
package org.eclipse.jdt.core.tests.dom;
12
package org.eclipse.jdt.core.tests.dom;
12
13
Lines 7475-7481 Link Here
7475
    	assertTrue("Not assignement compatible", typeBinding.isAssignmentCompatible(typeBinding2));
7476
    	assertTrue("Not assignement compatible", typeBinding.isAssignmentCompatible(typeBinding2));
7476
    	assertTrue("Not assignement compatible", typeBinding.isAssignmentCompatible(collectionTypeBinding));
7477
    	assertTrue("Not assignement compatible", typeBinding.isAssignmentCompatible(collectionTypeBinding));
7477
	}
7478
	}
7478
7479
	/*
7479
	/*
7480
	 * https://bugs.eclipse.org/bugs/show_bug.cgi?id=156352
7480
	 * https://bugs.eclipse.org/bugs/show_bug.cgi?id=156352
7481
	 */
7481
	 */
Lines 7494-7499 Link Here
7494
				buffer.append(typeBinding.getAnnotations().length);
7494
				buffer.append(typeBinding.getAnnotations().length);
7495
				typeBinding= typeBinding.getSuperclass();
7495
				typeBinding= typeBinding.getSuperclass();
7496
			}
7496
			}
7497
			// the right outcome would be "020", but depending on the strategy when exactly
7498
			// annotations are resolved the annotations on Test2 are (not) present when
7499
			// traversing the super-class chain.
7500
			// The patch in https://bugs.eclipse.org/186342#c196 produced "020" but
7501
			// the previous behavior ("000") was restored in https://bugs.eclipse.org/365387
7502
			// (see the change in SourceTypeBinding.resolveTypesFor(..))
7497
			assertEquals("Wrong number of annotations", "000", String.valueOf(buffer));
7503
			assertEquals("Wrong number of annotations", "000", String.valueOf(buffer));
7498
		}
7504
		}
7499
	}
7505
	}
(-)a/org.eclipse.jdt.core.tests.model/src/org/eclipse/jdt/core/tests/dom/ASTConverter15Test.java (-2 / +106 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 342671 - ClassCastException: org.eclipse.jdt.internal.compiler.lookup.SourceTypeBinding cannot be cast to org.eclipse.jdt.internal.compiler.lookup.ArrayBinding
10
 *     Stephan Herrmann - Contributions for 
11
 *     							Bug 342671 - ClassCastException: org.eclipse.jdt.internal.compiler.lookup.SourceTypeBinding cannot be cast to org.eclipse.jdt.internal.compiler.lookup.ArrayBinding
12
 *     							Bug 353474 - type converters should include more annotations
13
 *     							Bug 186342 - [compiler][null] Using annotations for null checking
11
 *******************************************************************************/
14
 *******************************************************************************/
12
package org.eclipse.jdt.core.tests.dom;
15
package org.eclipse.jdt.core.tests.dom;
13
16
Lines 50-56 Link Here
50
	static {
53
	static {
51
//		TESTS_NUMBERS = new int[] { 353 };
54
//		TESTS_NUMBERS = new int[] { 353 };
52
//		TESTS_RANGE = new int[] { 325, -1 };
55
//		TESTS_RANGE = new int[] { 325, -1 };
53
//		TESTS_NAMES = new String[] {"test0204"};
56
//		TESTS_NAMES = new String[] {"testBug353474"};
54
	}
57
	}
55
	public static Test suite() {
58
	public static Test suite() {
56
		return buildModelTestSuite(ASTConverter15Test.class);
59
		return buildModelTestSuite(ASTConverter15Test.class);
Lines 7495-7500 Link Here
7495
				buffer.append(typeBinding.getAnnotations().length);
7498
				buffer.append(typeBinding.getAnnotations().length);
7496
				typeBinding= typeBinding.getSuperclass();
7499
				typeBinding= typeBinding.getSuperclass();
7497
			}
7500
			}
7501
			// the right outcome would be "020", but depending on the strategy when exactly
7502
			// annotations are resolved the annotations on Test2 are (not) present when
7503
			// traversing the super-class chain.
7504
			// The patch in https://bugs.eclipse.org/186342#c196 produced "020" but
7505
			// the previous behavior ("000") was restored in https://bugs.eclipse.org/365387
7506
			// (see the change in SourceTypeBinding.resolveTypesFor(..))
7498
			assertEquals("Wrong number of annotations", "000", String.valueOf(buffer));
7507
			assertEquals("Wrong number of annotations", "000", String.valueOf(buffer));
7499
		}
7508
		}
7500
	}
7509
	}
Lines 11348-11352 Link Here
11348
        rhsType = ((Assignment)((ExpressionStatement)((Statement) statements.get(1))).getExpression()).getRightHandSide().resolveTypeBinding();
11357
        rhsType = ((Assignment)((ExpressionStatement)((Statement) statements.get(1))).getExpression()).getRightHandSide().resolveTypeBinding();
11349
        assertFalse("Assignement compatible", rhsType.isAssignmentCompatible(assignmentType));
11358
        assertFalse("Assignement compatible", rhsType.isAssignmentCompatible(assignmentType));
11350
	}
11359
	}
11360
	// Bug 353474 - type converters should include more annotations
11361
	public void testBug353474() throws CoreException {
11362
		
11363
		this.createFolder("/Converter15/src/testBug353474/annot");
11364
		String contents =	
11365
			"package testBug353474.annot;\n" +
11366
			"import static java.lang.annotation.ElementType.*;\n" + 
11367
			"import java.lang.annotation.*;\n" + 
11368
			"@Retention(RetentionPolicy.CLASS)\n" + 
11369
			"@Target({METHOD,PARAMETER,LOCAL_VARIABLE})\n" + 
11370
			"public @interface Nullable {\n" + 
11371
			"}\n";
11372
		getWorkingCopy("/Converter15/src/testBug353474/annot/Nullable.java", contents, true/*resolve*/);
11373
11374
		this.createFolder("/Converter15/src/testBug353474/p1");
11375
		contents =	
11376
			"package testBug353474.p1;\n" +
11377
			"import testBug353474.annot.*;\n" +
11378
			"public class C1 {\n" +
11379
			"	 public @Nullable String foo(@Nullable Object arg) {\n" +
11380
			"		return \"\";\n" +
11381
			"	 }\n" +
11382
			"}\n";
11383
		getWorkingCopy("/Converter15/src/testBug353474/p1/C1.java", contents, true/*resolve*/);
11384
11385
		this.workingCopy = getWorkingCopy("/Converter15/src/testBug353474/p1/C2.java", true/*resolve*/);
11386
		contents =
11387
			"package testBug353474.p1;\n" +
11388
			"public class C2 {\n" +
11389
			"	 public String bar(C1 c1) {\n" +
11390
			"        return c1.foo(null);\n" +
11391
			"    }\n" +
11392
			"}\n";
11393
		ASTNode node = buildAST(
11394
				contents,
11395
				this.workingCopy,
11396
				true);
11397
		assertNotNull("No node", node);
11398
		assertEquals("Not a compilation unit", ASTNode.COMPILATION_UNIT, node.getNodeType());
11399
		CompilationUnit compilationUnit = (CompilationUnit) node;
11400
		TypeDeclaration c2 = (TypeDeclaration) compilationUnit.types().get(0);
11401
		MethodDeclaration bar = (MethodDeclaration) c2.bodyDeclarations().get(0);
11402
		ReturnStatement returnStat = (ReturnStatement) bar.getBody().statements().get(0);
11403
		MethodInvocation fooCall = (MethodInvocation) returnStat.getExpression();
11404
		IMethodBinding resolvedFoo = fooCall.resolveMethodBinding();
11405
		IAnnotationBinding[] parameterAnnotations0 = resolvedFoo.getParameterAnnotations(0);
11406
		assertNotNull("Parameter annotation should not be null", parameterAnnotations0);
11407
		assertEquals("Should have exactly one annotation", 1, parameterAnnotations0.length);
11408
		assertEquals("Unexpected annotation name", "Nullable", parameterAnnotations0[0].getName());
11409
		
11410
		IAnnotationBinding[] returnAnnotations = resolvedFoo.getAnnotations();
11411
		assertNotNull("Return annotation should not be null", returnAnnotations);
11412
		assertEquals("Should have exactly one return annotation", 1, returnAnnotations.length);
11413
		assertEquals("Unexpected annotation name", "Nullable", returnAnnotations[0].getName());
11414
		deleteFolder("/Converter15/src/testBug353474");
11415
	}
11416
	// Bug 353474 - type converters should include more annotations
11417
	// secondary type comes from binary
11418
	public void testBug353474a() throws CoreException {
11419
		String jarLocation = getWorkspacePath()+"Converter15/bins/bug353474.jar";
11420
		IJavaProject jp = createJavaProject("Bug353464a", new String[]{"src"}, new String[]{"CONVERTER_JCL15_LIB", jarLocation}, "bin", "1.5");
11421
		try {
11422
			this.workingCopy = getWorkingCopy("/Bug353464a/src/testBug353474/p1/C2.java", true/*resolve*/);
11423
			String contents =
11424
				"package testBug353474.p1;\n" +
11425
				"public class C2 {\n" +
11426
				"	 public String bar(C1a c1) {\n" +
11427
				"        return c1.foo(null);\n" +
11428
				"    }\n" +
11429
				"}\n";
11430
			ASTNode node = buildAST(
11431
					contents,
11432
					this.workingCopy,
11433
					true);
11434
			assertNotNull("No node", node);
11435
			assertEquals("Not a compilation unit", ASTNode.COMPILATION_UNIT, node.getNodeType());
11436
			CompilationUnit compilationUnit = (CompilationUnit) node;
11437
			TypeDeclaration c2 = (TypeDeclaration) compilationUnit.types().get(0);
11438
			MethodDeclaration bar = (MethodDeclaration) c2.bodyDeclarations().get(0);
11439
			ReturnStatement returnStat = (ReturnStatement) bar.getBody().statements().get(0);
11440
			MethodInvocation fooCall = (MethodInvocation) returnStat.getExpression();
11441
			IMethodBinding resolvedFoo = fooCall.resolveMethodBinding();
11442
			IAnnotationBinding[] parameterAnnotations0 = resolvedFoo.getParameterAnnotations(0);
11443
			assertNotNull("Parameter annotation should not be null", parameterAnnotations0);
11444
			assertEquals("Should have exactly one annotation", 1, parameterAnnotations0.length);
11445
			assertEquals("Unexpected annotation name", "Nullable", parameterAnnotations0[0].getName());
11446
			
11447
			IAnnotationBinding[] returnAnnotations = resolvedFoo.getAnnotations();
11448
			assertNotNull("Return annotation should not be null", returnAnnotations);
11449
			assertEquals("Should have exactly one return annotation", 1, returnAnnotations.length);
11450
			assertEquals("Unexpected annotation name", "Nullable", returnAnnotations[0].getName());
11451
		} finally {
11452
			deleteProject(jp);
11453
		}
11454
	}
11351
11455
11352
}
11456
}
(-)a/org.eclipse.jdt.core.tests.model/src/org/eclipse/jdt/core/tests/dom/ASTConverterJavadocTest.java (-10 / +8 lines)
Lines 275-285 Link Here
275
				int c1, c2, c3, c4;
275
				int c1, c2, c3, c4;
276
				charLength++;
276
				charLength++;
277
				while (source[idx+charLength] == 'u') charLength++;
277
				while (source[idx+charLength] == 'u') charLength++;
278
				if (((c1 = ScannerHelper.getNumericValue(source[idx+charLength++])) > 15
278
				if (((c1 = ScannerHelper.getHexadecimalValue(source[idx+charLength++])) > 15 || c1 < 0)
279
					|| c1 < 0)
279
					|| ((c2 = ScannerHelper.getHexadecimalValue(source[idx+charLength++])) > 15 || c2 < 0)
280
					|| ((c2 = ScannerHelper.getNumericValue(source[idx+charLength++])) > 15 || c2 < 0)
280
					|| ((c3 = ScannerHelper.getHexadecimalValue(source[idx+charLength++])) > 15 || c3 < 0)
281
					|| ((c3 = ScannerHelper.getNumericValue(source[idx+charLength++])) > 15 || c3 < 0)
281
					|| ((c4 = ScannerHelper.getHexadecimalValue(source[idx+charLength++])) > 15 || c4 < 0)) {
282
					|| ((c4 = ScannerHelper.getNumericValue(source[idx+charLength++])) > 15 || c4 < 0)) {
283
					return ch;
282
					return ch;
284
				}
283
				}
285
				ch = (char) (((c1 * 16 + c2) * 16 + c3) * 16 + c4);
284
				ch = (char) (((c1 * 16 + c2) * 16 + c3) * 16 + c4);
Lines 474-484 Link Here
474
				int c1, c2, c3, c4;
473
				int c1, c2, c3, c4;
475
				unicodeSource[u++] = source[i];
474
				unicodeSource[u++] = source[i];
476
				unicodeSource[u++] = source[++i];
475
				unicodeSource[u++] = source[++i];
477
				if (((c1 = ScannerHelper.getNumericValue(source[i+1])) > 15
476
				if (((c1 = ScannerHelper.getHexadecimalValue(source[i+1])) > 15 || c1 < 0)
478
					|| c1 < 0)
477
					|| ((c2 = ScannerHelper.getHexadecimalValue(source[i+2])) > 15 || c2 < 0)
479
					|| ((c2 = ScannerHelper.getNumericValue(source[i+2])) > 15 || c2 < 0)
478
					|| ((c3 = ScannerHelper.getHexadecimalValue(source[i+3])) > 15 || c3 < 0)
480
					|| ((c3 = ScannerHelper.getNumericValue(source[i+3])) > 15 || c3 < 0)
479
					|| ((c4 = ScannerHelper.getHexadecimalValue(source[i+4])) > 15 || c4 < 0)) {
481
					|| ((c4 = ScannerHelper.getNumericValue(source[i+4])) > 15 || c4 < 0)) {
482
					throw new RuntimeException("Invalid unicode in source at "+i);
480
					throw new RuntimeException("Invalid unicode in source at "+i);
483
				}
481
				}
484
				for (int j=0; j<4; j++) unicodeSource[u++] = source[++i];
482
				for (int j=0; j<4; j++) unicodeSource[u++] = source[++i];
(-)a/org.eclipse.jdt.core.tests.model/src/org/eclipse/jdt/core/tests/dom/ASTConverterTestAST3_2.java (+18 lines)
Lines 10613-10616 Link Here
10613
		assertEquals("wrong tag name", "@literal", element.getTagName());
10613
		assertEquals("wrong tag name", "@literal", element.getTagName());
10614
		checkSourceRange((TextElement) element.fragments().get(0), " stars**** ", source);
10614
		checkSourceRange((TextElement) element.fragments().get(0), " stars**** ", source);
10615
	}
10615
	}
10616
	// https://bugs.eclipse.org/bugs/show_bug.cgi?id=361938
10617
	public void test0722() throws JavaModelException {
10618
		String source = "public class X {\n" +
10619
						"  X(){\n" +
10620
						"    try {\n" +
10621
						"    }\n" +
10622
						"  finally {\n" +
10623
						"    }\n" +
10624
						"  }\n" +
10625
						"}\n";
10626
		
10627
		ASTParser parser = ASTParser.newParser(AST.JLS3);
10628
		parser.setKind(ASTParser.K_COMPILATION_UNIT);
10629
		parser.setSource(source.toCharArray());
10630
		CompilationUnit resultCompilationUnit = (CompilationUnit) parser.createAST(null);
10631
		Object o = resultCompilationUnit.types().get(0);
10632
		assertEquals(o.toString(), source);
10633
	}
10616
}
10634
}
(-)a/org.eclipse.jdt.core.tests.model/src/org/eclipse/jdt/core/tests/dom/ASTConverterTestAST4_2.java (-1 / +87 lines)
Lines 122-128 Link Here
122
	static {
122
	static {
123
//		TESTS_NAMES = new String[] {"test0602"};
123
//		TESTS_NAMES = new String[] {"test0602"};
124
//		TESTS_RANGE = new int[] { 721, -1 };
124
//		TESTS_RANGE = new int[] { 721, -1 };
125
//		TESTS_NUMBERS =  new int[] { 721, 722, 723, 724, 725 };
125
//		TESTS_NUMBERS =  new int[] { 725 };
126
	}
126
	}
127
	public static Test suite() {
127
	public static Test suite() {
128
		return buildModelTestSuite(ASTConverterTestAST4_2.class);
128
		return buildModelTestSuite(ASTConverterTestAST4_2.class);
Lines 10641-10644 Link Here
10641
			}
10641
			}
10642
		}
10642
		}
10643
	}
10643
	}
10644
	/**
10645
	 * https://bugs.eclipse.org/bugs/show_bug.cgi?id=347396
10646
	 */
10647
	public void test0723() {
10648
		ASTParser parser = ASTParser.newParser(AST.JLS4);
10649
		parser.setKind (ASTParser.K_STATEMENTS);
10650
		String src = "int j;\nfor {};\nj=1000;";
10651
		char[] source = src.toCharArray();
10652
		parser.setStatementsRecovery(true);
10653
		parser.setSource(source);
10654
		ASTNode result = parser.createAST (null);
10655
		assertNotNull("no result", result);
10656
		assertEquals("Wrong type", ASTNode.BLOCK, result.getNodeType());
10657
		Block block = (Block) result;
10658
		List statements = block.statements();
10659
		assertNotNull("No statements", statements);
10660
		assertEquals("Wrong size", 3, statements.size());
10661
		assertFalse(isRecovered((ASTNode) statements.get(0)));
10662
		assertFalse(isRecovered((ASTNode) statements.get(1)));
10663
		assertFalse(isRecovered((ASTNode) statements.get(2)));
10664
	}
10665
10666
	/**
10667
	 * https://bugs.eclipse.org/bugs/show_bug.cgi?id=347396
10668
	 */
10669
	public void test0724() {
10670
		ASTParser parser = ASTParser.newParser(AST.JLS4);
10671
		parser.setKind (ASTParser.K_COMPILATION_UNIT);
10672
		String src = "public class X { void foo() {int j;\nfor {};\nj=1000;}}";
10673
		char[] source = src.toCharArray();
10674
		parser.setStatementsRecovery(true);
10675
		parser.setSource(source);
10676
		ASTNode result = parser.createAST (null);
10677
		assertNotNull("no result", result);
10678
		assertEquals("Wrong type", ASTNode.COMPILATION_UNIT, result.getNodeType());
10679
		Block block = ((MethodDeclaration) getASTNode((CompilationUnit) result, 0, 0)).getBody();
10680
		List statements = block.statements();
10681
		assertNotNull("No statements", statements);
10682
		assertEquals("Wrong size", 3, statements.size());
10683
		assertFalse(isRecovered((ASTNode) statements.get(0)));
10684
		assertFalse(isRecovered((ASTNode) statements.get(1)));
10685
		assertFalse(isRecovered((ASTNode) statements.get(2)));
10686
	}
10687
	/*
10688
	 * https://bugs.eclipse.org/bugs/show_bug.cgi?id=357471
10689
	 */
10690
	public void test0725() throws JavaModelException {
10691
		ICompilationUnit workingCopy = null;
10692
		try {
10693
			String contents =
10694
				"package one.two;\n" +
10695
				"public class one {}";
10696
			workingCopy = getWorkingCopy("/Converter/src/one/two/one.java", true/*resolve*/);
10697
			CompilationUnit unit = (CompilationUnit) buildAST(
10698
				AST.JLS3,
10699
				contents,
10700
				workingCopy,
10701
				true,
10702
				true,
10703
				true);
10704
			PackageDeclaration packageDeclaration = unit.getPackage();
10705
			IPackageBinding packageBinding = packageDeclaration.resolveBinding();
10706
			assertNotNull("No binding", packageBinding);
10707
			assertEquals("Wrong name", "one.two", packageBinding.getName());
10708
			Name packageName = packageDeclaration.getName();
10709
			IBinding binding = packageName.resolveBinding();
10710
			assertEquals("Wrong type", IBinding.PACKAGE, binding.getKind());
10711
			packageBinding = (IPackageBinding) binding;
10712
			assertEquals("Wrong name", "one.two", packageBinding.getName());
10713
			packageName = ((QualifiedName) packageName).getQualifier();
10714
			binding = packageName.resolveBinding();
10715
			assertEquals("Wrong type", IBinding.PACKAGE, binding.getKind());
10716
			packageBinding = (IPackageBinding) binding;
10717
			assertEquals("Wrong name", "one", packageBinding.getName());
10718
			packageName = packageDeclaration.getName();
10719
			packageName = ((QualifiedName) packageName).getName();
10720
			binding = packageName.resolveBinding();
10721
			assertEquals("Wrong type", IBinding.PACKAGE, binding.getKind());
10722
			packageBinding = (IPackageBinding) binding;
10723
			assertEquals("Wrong name", "one.two", packageBinding.getName());
10724
		} finally {
10725
			if (workingCopy != null) {
10726
				workingCopy.discardWorkingCopy();
10727
			}
10728
		}
10729
	}
10644
}
10730
}
(-)a/org.eclipse.jdt.core.tests.model/src/org/eclipse/jdt/core/tests/dom/ASTTest.java (-1 / +29 lines)
Lines 1-5 Link Here
1
/*******************************************************************************
1
/*******************************************************************************
2
 * Copyright (c) 2000, 2011 IBM Corporation and others.
2
 * Copyright (c) 2000, 2012 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 2092-2097 Link Here
2092
2092
2093
		assertTrue(x.getDimensions() == 5);
2093
		assertTrue(x.getDimensions() == 5);
2094
		assertTrue(x.getElementType().isPrimitiveType());
2094
		assertTrue(x.getElementType().isPrimitiveType());
2095
		final ArrayType x3 = this.ast.newArrayType(x, 2);
2096
		assertTrue(x3.getDimensions() == 7);
2097
		
2098
		try {
2099
			this.ast.newArrayType(null, 2);
2100
		} catch(IllegalArgumentException e) {
2101
			// ignore - expected
2102
		}
2103
		try {
2104
			this.ast.newArrayType(x, 0);
2105
		} catch(IllegalArgumentException e) {
2106
			// ignore - expected
2107
		}
2108
		try {
2109
			this.ast.newArrayType(x, 100000);
2110
		} catch(IllegalArgumentException e) {
2111
			// ignore - expected
2112
		}
2095
	}
2113
	}
2096
2114
2097
	/** @deprecated using deprecated code */
2115
	/** @deprecated using deprecated code */
Lines 5247-5252 Link Here
5247
	 * @deprecated (Uses getLeadingComment() which is deprecated)
5265
	 * @deprecated (Uses getLeadingComment() which is deprecated)
5248
	 */
5266
	 */
5249
	public void testTryStatement() {
5267
	public void testTryStatement() {
5268
		if (this.ast.apiLevel() <= AST.JLS3) {
5269
			// node type introduced in 4.0 API
5270
			try {
5271
				final TryStatement x = this.ast.newTryStatement();
5272
				x.resources();
5273
				assertTrue("should not be reached if jls level <= JLS3", false);
5274
			} catch (UnsupportedOperationException e) {
5275
				// pass
5276
			}
5277
		}
5250
		long previousCount = this.ast.modificationCount();
5278
		long previousCount = this.ast.modificationCount();
5251
		final TryStatement x = this.ast.newTryStatement();
5279
		final TryStatement x = this.ast.newTryStatement();
5252
		assertTrue(this.ast.modificationCount() > previousCount);
5280
		assertTrue(this.ast.modificationCount() > previousCount);
(-)a/org.eclipse.jdt.core.tests.model/src/org/eclipse/jdt/core/tests/formatter/FormatterRegressionTests.java (-1 / +19 lines)
Lines 62-68 Link Here
62
	Map formatterOptions;
62
	Map formatterOptions;
63
63
64
	static {
64
	static {
65
//		TESTS_NUMBERS = new int[] { 776, 777, 778, 779,780,781 };
65
//		TESTS_NUMBERS = new int[] { 783 };
66
//		TESTS_RANGE = new int[] { 734, -1 };
66
//		TESTS_RANGE = new int[] { 734, -1 };
67
	}
67
	}
68
	public static Test suite() {
68
	public static Test suite() {
Lines 12861-12864 Link Here
12861
		"}"
12861
		"}"
12862
	);
12862
	);
12863
}
12863
}
12864
//https://bugs.eclipse.org/bugs/show_bug.cgi?id=359646
12865
public void test783() throws Exception {
12866
	this.formatterPrefs = null;
12867
	String source =
12868
		"public class X {public static void main(String[] args) {\n" + 
12869
		"  	long x = 0x8000000000000000L;\n" + 
12870
		"  	System.out.println(x);\n" + 
12871
		"  }\n" + 
12872
		"}";
12873
	formatSource(source,
12874
		"public class X {\n" + 
12875
		"	public static void main(String[] args) {\n" + 
12876
		"		long x = 0x8000000000000000L;\n" + 
12877
		"		System.out.println(x);\n" + 
12878
		"	}\n" + 
12879
		"}"
12880
	);
12881
}
12864
}
12882
}
(-)a/org.eclipse.jdt.core.tests.model/src/org/eclipse/jdt/core/tests/model/AbstractJavaModelTests.java (-21 / +1 lines)
Lines 1-5 Link Here
1
/*******************************************************************************
1
/*******************************************************************************
2
 * Copyright (c) 2000, 2011 IBM Corporation and others.
2
 * Copyright (c) 2000, 2012 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 2922-2934 Link Here
2922
		return org.eclipse.jdt.core.tests.util.Util.toString(strings, false/*don't add extra new line*/);
2922
		return org.eclipse.jdt.core.tests.util.Util.toString(strings, false/*don't add extra new line*/);
2923
	}
2923
	}
2924
	protected void tearDown() throws Exception {
2924
	protected void tearDown() throws Exception {
2925
		if (JavaModelManager.DEBUG_302850) {
2926
			System.out.println("	- Options before tear down:");
2927
			System.out.println("		+ Task tags:           " + JavaCore.getOption(JavaCore.COMPILER_TASK_TAGS));
2928
			System.out.println("		+ Task priorities:     " + JavaCore.getOption(JavaCore.COMPILER_TASK_PRIORITIES));
2929
			System.out.println("		+ Forbidden reference: " + JavaCore.getOption(JavaCore.COMPILER_PB_FORBIDDEN_REFERENCE));
2930
			System.out.println(org.eclipse.jdt.core.tests.util.Util.indentString(new CompilerOptions(JavaCore.getOptions()).toString(), 2));
2931
		}
2932
2925
2933
		super.tearDown();
2926
		super.tearDown();
2934
		if (this.workingCopies != null) {
2927
		if (this.workingCopies != null) {
Lines 2937-2953 Link Here
2937
		}
2930
		}
2938
		this.wcOwner = null;
2931
		this.wcOwner = null;
2939
2932
2940
		if (JavaModelManager.DEBUG_302850) {
2941
			System.out.println("	- Options before comparison with defaults:");
2942
			System.out.println("		+ Task tags:           " + JavaCore.getOption(JavaCore.COMPILER_TASK_TAGS));
2943
			System.out.println("		+ Task priorities:     " + JavaCore.getOption(JavaCore.COMPILER_TASK_PRIORITIES));
2944
			System.out.println("		+ Forbidden reference: " + JavaCore.getOption(JavaCore.COMPILER_PB_FORBIDDEN_REFERENCE));
2945
			System.out.println(org.eclipse.jdt.core.tests.util.Util.indentString(new CompilerOptions(JavaCore.getOptions()).toString(), 2));
2946
			System.out.println("	- Default Options before comparison:");
2947
			System.out.println(org.eclipse.jdt.core.tests.util.Util.indentString(new CompilerOptions(JavaCore.getDefaultOptions()).toString(), 2));
2948
			System.out.println("================================================================================");
2949
		}
2950
2951
		// ensure workspace options have been restored to their default
2933
		// ensure workspace options have been restored to their default
2952
		Hashtable options = JavaCore.getOptions();
2934
		Hashtable options = JavaCore.getOptions();
2953
		Hashtable defaultOptions = JavaCore.getDefaultOptions();
2935
		Hashtable defaultOptions = JavaCore.getDefaultOptions();
Lines 2955-2962 Link Here
2955
			"Workspace options should be back to their default",
2937
			"Workspace options should be back to their default",
2956
			new CompilerOptions(defaultOptions).toString(),
2938
			new CompilerOptions(defaultOptions).toString(),
2957
			new CompilerOptions(options).toString());
2939
			new CompilerOptions(options).toString());
2958
		
2959
		JavaModelManager.DEBUG_302850 = false;
2960
	}
2940
	}
2961
2941
2962
	/**
2942
	/**
(-)a/org.eclipse.jdt.core.tests.model/src/org/eclipse/jdt/core/tests/model/AllJavaModelTests.java (-1 / +7 lines)
Lines 1-5 Link Here
1
/*******************************************************************************
1
/*******************************************************************************
2
 * Copyright (c) 2000, 2010 IBM Corporation and others.
2
 * Copyright (c) 2000, 2012 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 130-135 Link Here
130
		// Access restrictions tests
130
		// Access restrictions tests
131
		AccessRestrictionsTests.class,
131
		AccessRestrictionsTests.class,
132
132
133
		// Ignore optional problems from source folders tests
134
		IgnoreOptionalProblemsFromSourceFoldersTests.class,
135
133
		// Signature tests
136
		// Signature tests
134
		SignatureTests.class,
137
		SignatureTests.class,
135
138
Lines 185-190 Link Here
185
		UtilTests.class,
188
		UtilTests.class,
186
		
189
		
187
		JavaCoreOptionsTests.class,
190
		JavaCoreOptionsTests.class,
191
		
192
		// Tests regarding null-annotations:
193
		NullAnnotationModelTests.class,
188
	};
194
	};
189
195
190
	Class[] deprecatedClasses = getDeprecatedJDOMTestClasses();
196
	Class[] deprecatedClasses = getDeprecatedJDOMTestClasses();
(-)a/org.eclipse.jdt.core.tests.model/src/org/eclipse/jdt/core/tests/model/AttachSourceTests.java (-1 / +31 lines)
Lines 10-15 Link Here
10
 *******************************************************************************/
10
 *******************************************************************************/
11
package org.eclipse.jdt.core.tests.model;
11
package org.eclipse.jdt.core.tests.model;
12
12
13
import java.io.BufferedInputStream;
13
import java.io.File;
14
import java.io.File;
14
import java.io.FileOutputStream;
15
import java.io.FileOutputStream;
15
import java.io.IOException;
16
import java.io.IOException;
Lines 50-55 Link Here
50
import org.eclipse.jdt.internal.compiler.classfmt.ClassFileConstants;
51
import org.eclipse.jdt.internal.compiler.classfmt.ClassFileConstants;
51
import org.eclipse.jdt.internal.core.ExternalFoldersManager;
52
import org.eclipse.jdt.internal.core.ExternalFoldersManager;
52
import org.eclipse.jdt.internal.core.JarPackageFragmentRoot;
53
import org.eclipse.jdt.internal.core.JarPackageFragmentRoot;
54
import org.eclipse.jdt.internal.core.JavaModelManager;
53
import org.eclipse.jdt.internal.core.JavaProject;
55
import org.eclipse.jdt.internal.core.JavaProject;
54
import org.eclipse.jdt.internal.core.util.Util;
56
import org.eclipse.jdt.internal.core.util.Util;
55
57
Lines 499-509 Link Here
499
				"}"
501
				"}"
500
			};
502
			};
501
		org.eclipse.jdt.core.tests.util.Util.createSourceDir(pathsAndContents, externalFolder + "/src228639/src");
503
		org.eclipse.jdt.core.tests.util.Util.createSourceDir(pathsAndContents, externalFolder + "/src228639/src");
504
502
		createExternalFolder("externalFolder/src228639/META-INF");
505
		createExternalFolder("externalFolder/src228639/META-INF");
503
		createExternalFolder("externalFolder/lib/META-INF");
506
		createExternalFolder("externalFolder/lib/META-INF");
504
507
505
		String externalLib = externalFolder + "/lib";
508
		String externalLib = externalFolder + "/lib";
506
		IJavaProject javaProject = createJavaProject("P", new String[0], new String[] {externalLib}, "");
509
		IJavaProject javaProject = null;
510
		try {
511
			javaProject = createJavaProject("P", new String[0], new String[] {externalLib}, "");
512
		}
513
		catch (Exception e) {
514
			IFolder folder = getFolder(externalLib);
515
			System.out.println("----------  This information is logged for debugging purposes as this test fails sporadically.---------");
516
			System.out.println("Failing when creating Link folder for: " + externalFolder);
517
			System.out.println("Existing? " + folder.exists());
518
			IProject externalFolderProject = JavaModelManager.getExternalManager().getExternalFoldersProject();
519
			IFile externalProjectFile = externalFolderProject.getFile(".project");
520
			if (externalProjectFile.exists()) {
521
				System.out.println("External Folder Project exists with following content:");
522
				BufferedInputStream bs = new BufferedInputStream(externalProjectFile.getContents());
523
				int available = 0;
524
				while ((available = bs.available()) > 0) {
525
					byte[] contents = new byte[available];
526
					bs.read(contents);
527
					System.out.println(new String(contents));
528
				}
529
				bs.close();
530
			}
531
			else {
532
				System.out.println("External folders project doesn't exist.");
533
			}
534
			System.out.println("----------  Debug information ends ---------");
535
			throw e;
536
		}
507
		IPackageFragmentRoot root = javaProject.getPackageFragmentRoot(externalLib);
537
		IPackageFragmentRoot root = javaProject.getPackageFragmentRoot(externalLib);
508
		attachSource(root, externalFolder + "/src228639", "");
538
		attachSource(root, externalFolder + "/src228639", "");
509
		IType type = root.getPackageFragment("p").getClassFile("X.class").getType();
539
		IType type = root.getPackageFragment("p").getClassFile("X.class").getType();
(-)a/org.eclipse.jdt.core.tests.model/src/org/eclipse/jdt/core/tests/model/AttachedJavadocTests.java (+40 lines)
Lines 86-91 Link Here
86
		suite.addTest(new AttachedJavadocTests("testBug334652_3"));
86
		suite.addTest(new AttachedJavadocTests("testBug334652_3"));
87
		suite.addTest(new AttachedJavadocTests("testBug334652_4"));
87
		suite.addTest(new AttachedJavadocTests("testBug334652_4"));
88
		suite.addTest(new AttachedJavadocTests("testBug354766"));
88
		suite.addTest(new AttachedJavadocTests("testBug354766"));
89
		suite.addTest(new AttachedJavadocTests("testBug354766_2"));
89
		return suite;
90
		return suite;
90
	}
91
	}
91
92
Lines 1004-1007 Link Here
1004
			this.project.setRawClasspath(entries, null);
1005
			this.project.setRawClasspath(entries, null);
1005
		}
1006
		}
1006
	}
1007
	}
1008
	//https://bugs.eclipse.org/bugs/show_bug.cgi?id=354766
1009
	public void testBug354766_2() throws CoreException, IOException {
1010
		IClasspathEntry[] entries = this.project.getRawClasspath();
1011
1012
		try {
1013
			IClasspathAttribute attribute =
1014
					JavaCore.newClasspathAttribute(
1015
							IClasspathAttribute.JAVADOC_LOCATION_ATTRIBUTE_NAME,
1016
							"jar:platform:/resource/AttachedJavadocProject/bug354766_doc.zip!/");
1017
					IClasspathEntry newEntry = JavaCore.newLibraryEntry(new Path("/AttachedJavadocProject/bug354766.jar"), null, null, null, new IClasspathAttribute[] { attribute}, false);
1018
			this.project.setRawClasspath(new IClasspathEntry[]{newEntry}, null);
1019
			this.project.getResolvedClasspath(false);
1020
1021
			IPackageFragmentRoot jarRoot = this.project.getPackageFragmentRoot(getFile("/AttachedJavadocProject/bug354766.jar"));
1022
			final IType type = jarRoot.getPackageFragment("com.test").getClassFile("PublicAbstractClass$InnerFinalException.class").getType();
1023
			IMethod method = type.getMethod("InnerFinalException", new String[] { "Lcom.test.PublicAbstractClass;"});
1024
			assertNotNull(method);
1025
			assertTrue("Does not exist", method.exists());
1026
1027
			String javadoc = method.getAttachedJavadoc(null);
1028
			assertNotNull(javadoc);
1029
			assertEquals(
1030
					"Wrong contents",
1031
					"<H3>\r\n" + 
1032
					"PublicAbstractClass.InnerFinalException</H3>\r\n" + 
1033
					"<PRE>\r\n" + 
1034
					"public <B>PublicAbstractClass.InnerFinalException</B>()</PRE>\r\n" + 
1035
					"<DL>\r\n" + 
1036
					"<DD>javadoc for InnerFinalException()\r\n" + 
1037
					"<P>\r\n" + 
1038
					"</DL>\r\n" + 
1039
					"\r\n" + 
1040
					"<!-- ============ METHOD DETAIL ========== -->\r\n" + 
1041
					"\r\n",
1042
					javadoc);
1043
		} finally {
1044
			this.project.setRawClasspath(entries, null);
1045
		}
1046
	}
1007
}
1047
}
(-)a/org.eclipse.jdt.core.tests.model/src/org/eclipse/jdt/core/tests/model/ClasspathTests.java (-1 / +231 lines)
Lines 1-5 Link Here
1
/*******************************************************************************
1
/*******************************************************************************
2
 * Copyright (c) 2000, 2011 IBM Corporation and others.
2
 * Copyright (c) 2000, 2012 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
 *     Terry Parker <tparker@google.com> - DeltaProcessor misses state changes in archive files, see https://bugs.eclipse.org/bugs/show_bug.cgi?id=357425,
11
 *     									   Fup of 357425: ensure all reported regressions are witnessed by tests, see https://bugs.eclipse.org/bugs/show_bug.cgi?id=361922
10
 *******************************************************************************/
12
 *******************************************************************************/
11
package org.eclipse.jdt.core.tests.model;
13
package org.eclipse.jdt.core.tests.model;
12
14
Lines 67-75 Link Here
67
import org.eclipse.jdt.internal.core.JavaModelManager;
69
import org.eclipse.jdt.internal.core.JavaModelManager;
68
import org.eclipse.jdt.internal.core.JavaProject;
70
import org.eclipse.jdt.internal.core.JavaProject;
69
import org.eclipse.jdt.internal.core.UserLibraryClasspathContainer;
71
import org.eclipse.jdt.internal.core.UserLibraryClasspathContainer;
72
import org.eclipse.jdt.internal.core.builder.State;
70
import org.eclipse.team.core.RepositoryProvider;
73
import org.eclipse.team.core.RepositoryProvider;
71
74
72
public class ClasspathTests extends ModifyingResourceTests {
75
public class ClasspathTests extends ModifyingResourceTests {
76
	private static final IClasspathAttribute ATTR_IGNORE_OPTIONAL_PROBLEMS_TRUE = JavaCore.newClasspathAttribute(IClasspathAttribute.IGNORE_OPTIONAL_PROBLEMS, "true");
77
	private static final IClasspathAttribute ATTR_IGNORE_OPTIONAL_PROBLEMS_FALSE = JavaCore.newClasspathAttribute(IClasspathAttribute.IGNORE_OPTIONAL_PROBLEMS, "false");
73
78
74
	public class TestContainer implements IClasspathContainer {
79
	public class TestContainer implements IClasspathContainer {
75
		IPath path;
80
		IPath path;
Lines 249-254 Link Here
249
	suite.addTest(new ClasspathTests("testInvalidClasspath2"));
254
	suite.addTest(new ClasspathTests("testInvalidClasspath2"));
250
	suite.addTest(new ClasspathTests("testInvalidExternalClassFolder"));
255
	suite.addTest(new ClasspathTests("testInvalidExternalClassFolder"));
251
	suite.addTest(new ClasspathTests("testInvalidExternalJar"));
256
	suite.addTest(new ClasspathTests("testInvalidExternalJar"));
257
	suite.addTest(new ClasspathTests("testTransitionFromInvalidToValidJar"));
252
	suite.addTest(new ClasspathTests("testInvalidInternalJar1"));
258
	suite.addTest(new ClasspathTests("testInvalidInternalJar1"));
253
	suite.addTest(new ClasspathTests("testInvalidInternalJar2"));
259
	suite.addTest(new ClasspathTests("testInvalidInternalJar2"));
254
	suite.addTest(new ClasspathTests("testInvalidSourceFolder"));
260
	suite.addTest(new ClasspathTests("testInvalidSourceFolder"));
Lines 334-339 Link Here
334
	suite.addTest(new ClasspathTests("testBug321170"));
340
	suite.addTest(new ClasspathTests("testBug321170"));
335
	suite.addTest(new ClasspathTests("testBug229042"));
341
	suite.addTest(new ClasspathTests("testBug229042"));
336
	suite.addTest(new ClasspathTests("testBug274737"));
342
	suite.addTest(new ClasspathTests("testBug274737"));
343
	suite.addTest(new ClasspathTests("testBug357425"));
344
	suite.addTest(new ClasspathTests("testBug287164"));
345
	suite.addTest(new ClasspathTests("testBug220928a"));
346
	suite.addTest(new ClasspathTests("testBug220928b"));
337
	return suite;
347
	return suite;
338
}
348
}
339
public void setUpSuite() throws Exception {
349
public void setUpSuite() throws Exception {
Lines 2020-2025 Link Here
2020
public void testClasspathValidation22() throws CoreException {
2030
public void testClasspathValidation22() throws CoreException {
2021
	try {
2031
	try {
2022
		IJavaProject proj =  this.createJavaProject("P", new String[] {}, "");
2032
		IJavaProject proj =  this.createJavaProject("P", new String[] {}, "");
2033
		proj.setOption(JavaCore.CORE_OUTPUT_LOCATION_OVERLAPPING_ANOTHER_SOURCE, JavaCore.ERROR);
2023
		IClasspathEntry[] originalCP = proj.getRawClasspath();
2034
		IClasspathEntry[] originalCP = proj.getRawClasspath();
2024
2035
2025
		IClasspathEntry[] newCP = new IClasspathEntry[originalCP.length+2];
2036
		IClasspathEntry[] newCP = new IClasspathEntry[originalCP.length+2];
Lines 2045-2050 Link Here
2045
public void testClasspathValidation23() throws CoreException {
2056
public void testClasspathValidation23() throws CoreException {
2046
	try {
2057
	try {
2047
		IJavaProject proj =  this.createJavaProject("P", new String[] {}, "");
2058
		IJavaProject proj =  this.createJavaProject("P", new String[] {}, "");
2059
		proj.setOption(JavaCore.CORE_OUTPUT_LOCATION_OVERLAPPING_ANOTHER_SOURCE, JavaCore.IGNORE);
2048
		IClasspathEntry[] originalCP = proj.getRawClasspath();
2060
		IClasspathEntry[] originalCP = proj.getRawClasspath();
2049
2061
2050
		IClasspathEntry[] newCP = new IClasspathEntry[originalCP.length+2];
2062
		IClasspathEntry[] newCP = new IClasspathEntry[originalCP.length+2];
Lines 4197-4202 Link Here
4197
			"Project 'P' is missing required library: \'" + jarPath + "\'",
4209
			"Project 'P' is missing required library: \'" + jarPath + "\'",
4198
			proj);
4210
			proj);
4199
	} finally {
4211
	} finally {
4212
		deleteProject("P");
4213
	}
4214
}
4215
/*
4216
 * Ensures that validateClasspathEntry() sees a transition from an invalid/missing jar to a valid jar.
4217
 */
4218
public void testTransitionFromInvalidToValidJar() throws CoreException, IOException {
4219
	String transitioningJarName = "transitioningJar.jar";
4220
	String transitioningJar = getExternalPath() + transitioningJarName;
4221
	String invalidJar = getExternalPath() + "invalidJar.jar";
4222
	IClasspathEntry transitioningEntry = JavaCore.newLibraryEntry(new Path(transitioningJar), null, null);
4223
	IClasspathEntry nonExistingEntry = JavaCore.newLibraryEntry(new Path(invalidJar), null, null);
4224
4225
	try {
4226
		Util.createFile(transitioningJar, "");
4227
		Util.createFile(invalidJar, "");
4228
		IJavaProject proj = createJavaProject("P", new String[] {}, new String[] {transitioningJar, invalidJar}, "bin");
4229
		
4230
		IJavaModelStatus status1 = ClasspathEntry.validateClasspathEntry(proj, transitioningEntry, false, false);
4231
		IJavaModelStatus status2 = ClasspathEntry.validateClasspathEntry(proj, nonExistingEntry, false, false);
4232
		assertFalse("Non-existing jar should be invalid", status1.isOK());
4233
		assertFalse("Non-existing jar should be invalid", status2.isOK());
4234
4235
		Util.createJar(	
4236
			new String[0],
4237
			new String[] {
4238
				"META-INF/MANIFEST.MF",
4239
				"Manifest-Version: 1.0\n"
4240
			},
4241
			transitioningJar,
4242
			JavaCore.VERSION_1_4);
4243
		status1 = ClasspathEntry.validateClasspathEntry(proj, transitioningEntry, false, false);
4244
		status2 = ClasspathEntry.validateClasspathEntry(proj, nonExistingEntry, false, false);
4245
		assertTrue("Existing jar should be valid", status1.isOK());
4246
		assertFalse("Non-existing jar should be invalid", status2.isOK());
4247
	} finally {
4248
		deleteExternalResource(transitioningJarName);
4200
		deleteProject("P");
4249
		deleteProject("P");
4201
	}
4250
	}
4202
}
4251
}
Lines 7190-7193 Link Here
7190
	}
7239
	}
7191
}
7240
}
7192
7241
7242
/*
7243
 * Ensures that the correct delta is reported when changing the Class-Path: clause 
7244
 * of an external jar from not containing a chained jar to containing a chained jar.
7245
 * (regression test for https://bugs.eclipse.org/bugs/show_bug.cgi?id=357425)
7246
 */
7247
public void testBug357425() throws Exception {
7248
	try {
7249
		IJavaProject p = createJavaProject("P");
7250
		addExternalLibrary(p, getExternalResourcePath("lib357425_a.jar"), new String[0], 
7251
			new String[] {
7252
				"META-INF/MANIFEST.MF",
7253
				"Manifest-Version: 1.0\n"
7254
			},
7255
			JavaCore.VERSION_1_4);
7256
		refreshExternalArchives(p);		
7257
7258
		startDeltas();
7259
		org.eclipse.jdt.core.tests.util.Util.createJar(new String[0],
7260
			new String[] {
7261
				"META-INF/MANIFEST.MF",
7262
				"Manifest-Version: 1.0\n" +
7263
				"Class-Path: lib357425_b.jar\n",
7264
			},
7265
			getExternalResourcePath("lib357425_a.jar"),
7266
			JavaCore.VERSION_1_4);
7267
		createExternalFile("lib357425_b.jar", "");
7268
7269
		refreshExternalArchives(p);
7270
		assertDeltas(
7271
			"Unexpected delta",
7272
			"P[*]: {CHILDREN | RESOLVED CLASSPATH CHANGED}\n" + 
7273
			"	"+ getExternalPath() + "lib357425_a.jar[*]: {CONTENT | REORDERED | ARCHIVE CONTENT CHANGED}\n" + 
7274
			"	"+ getExternalPath() + "lib357425_b.jar[+]: {}"
7275
				);
7276
	} finally {
7277
		stopDeltas();
7278
		deleteProject("P");
7279
		deleteExternalResource("lib357425_a.jar");
7280
		deleteExternalResource("lib357425_b.jar");
7281
	}
7282
}
7283
/**
7284
 * @bug287164: Report build path error if source folder has other source folder as output folder
7285
 * 
7286
 * @see "https://bugs.eclipse.org/bugs/show_bug.cgi?id=287164"
7287
 */
7288
public void testBug287164() throws CoreException {
7289
	try {
7290
		IJavaProject proj =  this.createJavaProject("P", new String[] {}, "");
7291
		
7292
		// Test that with the option set to IGNORE, the Java model status returns OK
7293
		proj.setOption(JavaCore.CORE_OUTPUT_LOCATION_OVERLAPPING_ANOTHER_SOURCE, JavaCore.IGNORE);
7294
		IClasspathEntry[] originalCP = proj.getRawClasspath();
7295
7296
		IClasspathEntry[] newCP = new IClasspathEntry[originalCP.length+2];
7297
		System.arraycopy(originalCP, 0, newCP, 0, originalCP.length);
7298
		newCP[originalCP.length] = JavaCore.newSourceEntry(new Path("/P/src"), new IPath[0], new Path("/P/src2"));
7299
		newCP[originalCP.length+1] = JavaCore.newSourceEntry(new Path("/P/src2"), new IPath[0], new Path("/P/src"));
7300
7301
		createFolder("/P/src");
7302
		createFolder("/P/src2");
7303
7304
		IJavaModelStatus status = JavaConventions.validateClasspath(proj, newCP, proj.getOutputLocation());
7305
		assertTrue(status.isOK());
7306
		assertStatus(
7307
			"OK",
7308
			status);
7309
		
7310
		proj.setRawClasspath(newCP, null);
7311
		assertMarkers("Unexpected markers", "", proj);
7312
		
7313
		// Test that with the option set to WARNING, status.isOK() returns true
7314
		proj.setOption(JavaCore.CORE_OUTPUT_LOCATION_OVERLAPPING_ANOTHER_SOURCE, JavaCore.WARNING);
7315
7316
		status = JavaConventions.validateClasspath(proj, newCP, proj.getOutputLocation());
7317
		assertTrue(status.isOK());
7318
		assertStatus(
7319
			"Source folder \'src\' in project \'P\' cannot output to distinct source folder \'src2\'",
7320
			status);
7321
7322
		assertMarkers("Unexpected markers", 
7323
				"Source folder \'src\' in project \'P\' cannot output to distinct source folder \'src2\'", proj);
7324
		
7325
		// Test that with the option set to WARNING and the presence of a more severe error scenario, the error status
7326
		// is returned
7327
		IClasspathEntry[] newCP2 = new IClasspathEntry[newCP.length+1];
7328
		System.arraycopy(newCP, 0, newCP2, 0, newCP.length-1);
7329
		newCP2[newCP.length] = JavaCore.newLibraryEntry(new Path("/P/lib2"), null, null);
7330
		newCP2[newCP.length-1] = JavaCore.newSourceEntry(new Path("/P/src2"), new IPath[0], new Path("/P/lib2"));
7331
7332
		status = JavaConventions.validateClasspath(proj, newCP2, proj.getOutputLocation());
7333
		assertFalse(status.isOK());
7334
		assertStatus(
7335
			"Source folder \'src2\' in project 'P' cannot output to library \'lib2\'",
7336
			status);
7337
		
7338
		proj.setOption(JavaCore.CORE_OUTPUT_LOCATION_OVERLAPPING_ANOTHER_SOURCE, JavaCore.ERROR);
7339
7340
		status = JavaConventions.validateClasspath(proj, newCP, proj.getOutputLocation());
7341
		assertStatus(
7342
			"Source folder \'src\' in project \'P\' cannot output to distinct source folder \'src2\'",
7343
			status);
7344
		
7345
	} finally {
7346
		this.deleteProject("P");
7347
	}
7348
}
7349
7350
/**
7351
 * @bug220928: [buildpath] Should be able to ignore warnings from certain source folders
7352
 * 
7353
 * Verify that adding the {@link IClasspathAttribute#IGNORE_OPTIONAL_PROBLEMS} attribute is
7354
 * correctly reflected by the {@link ClasspathEntry#ignoreOptionalProblems()} method.
7355
 * 
7356
 * @see "https://bugs.eclipse.org/bugs/show_bug.cgi?id=220928"
7357
 */
7358
public void testBug220928a() throws CoreException {
7359
	ClasspathEntry entry;
7360
7361
	entry = (ClasspathEntry) JavaCore.newSourceEntry(new Path("/P/src"));
7362
	assertFalse(entry.ignoreOptionalProblems());
7363
7364
	entry = (ClasspathEntry) JavaCore.newSourceEntry(new Path("/P/src"), null, null, null,
7365
			new IClasspathAttribute[] { ATTR_IGNORE_OPTIONAL_PROBLEMS_TRUE });
7366
	assertTrue(entry.ignoreOptionalProblems());
7367
7368
	entry = (ClasspathEntry) JavaCore.newSourceEntry(new Path("/P/src"), null, null, null,
7369
			new IClasspathAttribute[] { ATTR_IGNORE_OPTIONAL_PROBLEMS_FALSE });
7370
	assertFalse(entry.ignoreOptionalProblems());
7371
}
7372
7373
/**
7374
 * @bug220928: [buildpath] Should be able to ignore warnings from certain source folders
7375
 * 
7376
 * Verify that value of the {@link IClasspathAttribute#IGNORE_OPTIONAL_PROBLEMS} attribute is
7377
 * correctly saved on workspace save.
7378
 * 
7379
 * @see "https://bugs.eclipse.org/bugs/show_bug.cgi?id=220928"
7380
 */
7381
public void testBug220928b() throws CoreException {
7382
	boolean autoBuild = getWorkspace().isAutoBuilding();
7383
	IWorkspaceDescription preferences = getWorkspace().getDescription();
7384
	try {
7385
		// ensure that the workspace auto-build is ON
7386
		preferences.setAutoBuilding(true);
7387
		getWorkspace().setDescription(preferences);
7388
7389
		IJavaProject project = createJavaProject("P", new String[] {}, "bin");
7390
		createFolder("/P/src");
7391
		IClasspathEntry[] originalCP = project.getRawClasspath();
7392
		IClasspathEntry[] newCP = new IClasspathEntry[originalCP.length + 1];
7393
		State state;
7394
7395
		System.arraycopy(originalCP, 0, newCP, 0, originalCP.length);
7396
		newCP[originalCP.length] = JavaCore.newSourceEntry(new Path("/P/src"));
7397
		getJavaProject("P").setRawClasspath(newCP, null);
7398
		simulateExitRestart();
7399
		state = (State) JavaModelManager.getJavaModelManager().getLastBuiltState(getJavaProject("P").getProject(), null);
7400
		assertFalse(state.sourceLocations[0].ignoreOptionalProblems);
7401
7402
		System.arraycopy(originalCP, 0, newCP, 0, originalCP.length);
7403
		newCP[originalCP.length] = JavaCore.newSourceEntry(new Path("/P/src"), null, null, null,
7404
				new IClasspathAttribute[] { ATTR_IGNORE_OPTIONAL_PROBLEMS_TRUE });
7405
		getJavaProject("P").setRawClasspath(newCP, null);
7406
		simulateExitRestart();
7407
		state = (State) JavaModelManager.getJavaModelManager().getLastBuiltState(getJavaProject("P").getProject(), null);
7408
		assertTrue(state.sourceLocations[0].ignoreOptionalProblems);
7409
7410
		System.arraycopy(originalCP, 0, newCP, 0, originalCP.length);
7411
		newCP[originalCP.length] = JavaCore.newSourceEntry(new Path("/P/src"), null, null, null,
7412
				new IClasspathAttribute[] { ATTR_IGNORE_OPTIONAL_PROBLEMS_FALSE });
7413
		getJavaProject("P").setRawClasspath(newCP, null);
7414
		simulateExitRestart();
7415
		state = (State) JavaModelManager.getJavaModelManager().getLastBuiltState(getJavaProject("P").getProject(), null);
7416
		assertFalse(state.sourceLocations[0].ignoreOptionalProblems);
7417
	} finally {
7418
		preferences.setAutoBuilding(autoBuild);
7419
		getWorkspace().setDescription(preferences);
7420
		deleteProject("P");
7421
	}
7422
}
7193
}
7423
}
(-)a/org.eclipse.jdt.core.tests.model/src/org/eclipse/jdt/core/tests/model/CompletionTests2.java (-1 / +262 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 38-43 Link Here
38
import org.eclipse.jdt.core.IJavaProject;
38
import org.eclipse.jdt.core.IJavaProject;
39
import org.eclipse.jdt.core.IType;
39
import org.eclipse.jdt.core.IType;
40
import org.eclipse.jdt.core.JavaCore;
40
import org.eclipse.jdt.core.JavaCore;
41
import org.eclipse.jdt.core.JavaModelException;
41
import org.eclipse.jdt.core.tests.util.Util;
42
import org.eclipse.jdt.core.tests.util.Util;
42
import org.eclipse.jdt.internal.codeassist.RelevanceConstants;
43
import org.eclipse.jdt.internal.codeassist.RelevanceConstants;
43
import org.eclipse.jdt.internal.compiler.impl.CompilerOptions;
44
import org.eclipse.jdt.internal.compiler.impl.CompilerOptions;
Lines 45-50 Link Here
45
import org.eclipse.jdt.internal.core.search.indexing.IndexManager;
46
import org.eclipse.jdt.internal.core.search.indexing.IndexManager;
46
47
47
public class CompletionTests2 extends ModifyingResourceTests implements RelevanceConstants {
48
public class CompletionTests2 extends ModifyingResourceTests implements RelevanceConstants {
49
	
50
	static {
51
//		TESTS_NAMES = new String[]{"testBug340945"};
52
	}
48
53
49
	public static class CompletionContainerInitializer implements ContainerInitializer.ITestInitializer {
54
	public static class CompletionContainerInitializer implements ContainerInitializer.ITestInitializer {
50
55
Lines 5591-5594 Link Here
5591
		deleteProject(project);
5596
		deleteProject(project);
5592
	}
5597
	}
5593
}
5598
}
5599
5600
//https://bugs.eclipse.org/bugs/show_bug.cgi?id=292087
5601
public void testBug340945() throws JavaModelException {
5602
	this.workingCopies = new ICompilationUnit[1];
5603
	this.workingCopies[0] = getWorkingCopy(
5604
			"/Completion/src/test/Try.java",
5605
			"package test;\n" +
5606
			"public class Try extends Thread{\n" +
5607
			"	int inty = 1;\n" +
5608
			"	void foo() {\n" +
5609
			"		int i = 1;\n" +
5610
			"		Object o = new Object() {\n" +
5611
			"			void running() {\n" +
5612
			"				int j = 1;\n" +
5613
			"				int k = " +
5614
			"			}\n" +
5615
			"		}\n" +
5616
			"	}\n" +
5617
			"}\n");
5618
5619
	CompletionTestsRequestor2 requestor = new CompletionTestsRequestor2(true);
5620
	requestor.setRequireExtendedContext(true);
5621
	requestor.allowAllRequiredProposals();
5622
	requestor.setComputeVisibleElements(true);
5623
//	requestor.setAssignableType("I");
5624
	String str = this.workingCopies[0].getSource();
5625
	String completeBehind = "int k =";
5626
	int cursorLocation = str.lastIndexOf(completeBehind) + completeBehind.length();
5627
	this.workingCopies[0].codeComplete(cursorLocation, requestor, this.wcOwner);
5628
	assertResults(
5629
			"<CompleteOnName:>",
5630
			requestor.getCompletionNode());
5631
	assertResults(
5632
			"int k = <CompleteOnName:>;",
5633
			requestor.getCompletionNodeParent());
5634
	assertResults(
5635
			"int j[pos: unused][id:2]\n" +
5636
			"int i[pos: unused][id:0]\n" +
5637
			"java.lang.Object o[pos: unused][id:1]\n",
5638
			requestor.getVisibleLocalVariables());
5639
	assertResults(
5640
			"int inty\n",
5641
			requestor.getVisibleFields());
5642
	assertResults(
5643
			"void running() \n" +
5644
			"public final void wait(long, int) throws java.lang.IllegalMonitorStateException, java.lang.InterruptedException\n" +
5645
			"public final void wait(long) throws java.lang.IllegalMonitorStateException, java.lang.InterruptedException\n" +
5646
			"public final void wait() throws java.lang.IllegalMonitorStateException, java.lang.InterruptedException\n" +
5647
			"public java.lang.String toString() \n" +
5648
			"public final void notifyAll() throws java.lang.IllegalMonitorStateException\n" +
5649
			"public final void notify() throws java.lang.IllegalMonitorStateException\n" +
5650
			"public int hashCode() \n" +
5651
			"public final java.lang.Class getClass() \n" + 
5652
			"protected void finalize() throws java.lang.Throwable\n" +
5653
			"public boolean equals(java.lang.Object) \n" +
5654
			"protected java.lang.Object clone() throws java.lang.CloneNotSupportedException\n" +
5655
			"void foo() \n",
5656
			requestor.getVisibleMethods());
5657
}
5658
5659
// https://bugs.eclipse.org/bugs/show_bug.cgi?id=292087
5660
public void testBug340945a() throws JavaModelException {
5661
	this.workingCopies = new ICompilationUnit[1];
5662
	this.workingCopies[0] = getWorkingCopy(
5663
			"/Completion/src/test/Try.java",
5664
			"package test;\n" +
5665
			"public class Try extends Thread{\n" +
5666
			"	int int1 = 1;\n" +
5667
			"	int int2 = 2;\n" +
5668
			"	int int3 = " +
5669
			"}\n");
5670
5671
	CompletionTestsRequestor2 requestor = new CompletionTestsRequestor2(true);
5672
	requestor.setRequireExtendedContext(true);
5673
	requestor.allowAllRequiredProposals();
5674
	requestor.setComputeVisibleElements(true);
5675
	String str = this.workingCopies[0].getSource();
5676
	String completeBehind = "int int3 =";
5677
	int cursorLocation = str.lastIndexOf(completeBehind) + completeBehind.length();
5678
	this.workingCopies[0].codeComplete(cursorLocation, requestor, this.wcOwner);
5679
	assertResults(
5680
			"<CompleteOnName:>",
5681
			requestor.getCompletionNode());
5682
	assertResults(
5683
			"int int3 = <CompleteOnName:>;",
5684
			requestor.getCompletionNodeParent());
5685
	assertResults(
5686
			"",
5687
			requestor.getVisibleLocalVariables());
5688
	assertResults(
5689
			"int int2\n" +
5690
			"int int1\n",
5691
			requestor.getVisibleFields());
5692
	assertResults(
5693
			"public final void wait(long, int) throws java.lang.IllegalMonitorStateException, java.lang.InterruptedException\n" +
5694
			"public final void wait(long) throws java.lang.IllegalMonitorStateException, java.lang.InterruptedException\n" +
5695
			"public final void wait() throws java.lang.IllegalMonitorStateException, java.lang.InterruptedException\n" +
5696
			"public java.lang.String toString() \n" +
5697
			"public final void notifyAll() throws java.lang.IllegalMonitorStateException\n" +
5698
			"public final void notify() throws java.lang.IllegalMonitorStateException\n" +
5699
			"public int hashCode() \n" +
5700
			"public final java.lang.Class getClass() \n" + 
5701
			"protected void finalize() throws java.lang.Throwable\n" +
5702
			"public boolean equals(java.lang.Object) \n" +
5703
			"protected java.lang.Object clone() throws java.lang.CloneNotSupportedException\n",
5704
			requestor.getVisibleMethods());
5705
}
5706
5707
// https://bugs.eclipse.org/bugs/show_bug.cgi?id=292087
5708
public void testBug340945b() throws JavaModelException {
5709
	this.workingCopies = new ICompilationUnit[1];
5710
	this.workingCopies[0] = getWorkingCopy(
5711
			"/Completion/src/test/Try.java",
5712
			"package test;\n" +
5713
			"public class Try extends Thread{\n" +
5714
			"Object field;\n" +
5715
			"void foo() {\n" +
5716
			"	int int1 = 1;\n" +
5717
			"	int int2 = 2;\n" +
5718
			"	int int3 = " +
5719
			"}\n" +
5720
			"}\n");
5721
5722
	CompletionTestsRequestor2 requestor = new CompletionTestsRequestor2(true);
5723
	requestor.setRequireExtendedContext(true);
5724
	requestor.allowAllRequiredProposals();
5725
	requestor.setComputeVisibleElements(true);
5726
	String str = this.workingCopies[0].getSource();
5727
	String completeBehind = "int int3 =";
5728
	int cursorLocation = str.lastIndexOf(completeBehind) + completeBehind.length();
5729
	this.workingCopies[0].codeComplete(cursorLocation, requestor, this.wcOwner);
5730
	assertResults(
5731
			"<CompleteOnName:>",
5732
			requestor.getCompletionNode());
5733
	assertResults(
5734
			"int int3 = <CompleteOnName:>;",
5735
			requestor.getCompletionNodeParent());
5736
	assertResults(
5737
			"int int1[pos: unused][id:0]\n" +
5738
			"int int2[pos: unused][id:1]\n",
5739
			requestor.getVisibleLocalVariables());
5740
	assertResults(
5741
			"java.lang.Object field\n",
5742
			requestor.getVisibleFields());
5743
	assertResults(
5744
			"void foo() \n" +
5745
			"public final void wait(long, int) throws java.lang.IllegalMonitorStateException, java.lang.InterruptedException\n" +
5746
			"public final void wait(long) throws java.lang.IllegalMonitorStateException, java.lang.InterruptedException\n" +
5747
			"public final void wait() throws java.lang.IllegalMonitorStateException, java.lang.InterruptedException\n" +
5748
			"public java.lang.String toString() \n" +
5749
			"public final void notifyAll() throws java.lang.IllegalMonitorStateException\n" +
5750
			"public final void notify() throws java.lang.IllegalMonitorStateException\n" +
5751
			"public int hashCode() \n" +
5752
			"public final java.lang.Class getClass() \n" + 
5753
			"protected void finalize() throws java.lang.Throwable\n" +
5754
			"public boolean equals(java.lang.Object) \n" +
5755
			"protected java.lang.Object clone() throws java.lang.CloneNotSupportedException\n",			
5756
			requestor.getVisibleMethods());
5757
}
5758
5759
// https://bugs.eclipse.org/bugs/show_bug.cgi?id=292087
5760
public void testBug340945c() throws JavaModelException {
5761
	this.workingCopies = new ICompilationUnit[1];
5762
	this.workingCopies[0] = getWorkingCopy(
5763
			"/Completion/src/test/Try.java",
5764
			"package test;\n" +
5765
			"public class Try extends Thread{\n" +
5766
			"Object field;\n" +
5767
			"void foo() {\n" +
5768
			"	int int1 = 1;\n" +
5769
			"	int int2 = 2;\n" +
5770
			"	Object o1 = new Object();\n" +
5771
			"   o1." +
5772
			"}\n" +
5773
			"}\n");
5774
5775
	CompletionTestsRequestor2 requestor = new CompletionTestsRequestor2(true);
5776
	requestor.setRequireExtendedContext(true);
5777
	requestor.allowAllRequiredProposals();
5778
	requestor.setComputeVisibleElements(true);
5779
	String str = this.workingCopies[0].getSource();
5780
	String completeBehind = "o1.";
5781
	int cursorLocation = str.lastIndexOf(completeBehind) + completeBehind.length();
5782
	this.workingCopies[0].codeComplete(cursorLocation, requestor, this.wcOwner);
5783
	assertResults(
5784
			"<CompleteOnName:o1.>",
5785
			requestor.getCompletionNode());
5786
	assertNull(
5787
			"should be null",
5788
			requestor.getCompletionNodeParent());
5789
	assertResults(
5790
			"int int1[pos: unused][id:0]\n" +
5791
			"int int2[pos: unused][id:1]\n" +
5792
			"java.lang.Object o1[pos: unused][id:2]\n",
5793
			requestor.getVisibleLocalVariables());
5794
	assertResults(
5795
			"java.lang.Object field\n",
5796
			requestor.getVisibleFields());
5797
	assertResults(
5798
			"void foo() \n" +
5799
			"public final void wait(long, int) throws java.lang.IllegalMonitorStateException, java.lang.InterruptedException\n" +
5800
			"public final void wait(long) throws java.lang.IllegalMonitorStateException, java.lang.InterruptedException\n" +
5801
			"public final void wait() throws java.lang.IllegalMonitorStateException, java.lang.InterruptedException\n" +
5802
			"public java.lang.String toString() \n" +
5803
			"public final void notifyAll() throws java.lang.IllegalMonitorStateException\n" +
5804
			"public final void notify() throws java.lang.IllegalMonitorStateException\n" +
5805
			"public int hashCode() \n" +
5806
			"public final java.lang.Class getClass() \n" + 
5807
			"protected void finalize() throws java.lang.Throwable\n" +
5808
			"public boolean equals(java.lang.Object) \n" +
5809
			"protected java.lang.Object clone() throws java.lang.CloneNotSupportedException\n",			
5810
			requestor.getVisibleMethods());
5811
}
5812
5813
// https://bugs.eclipse.org/bugs/show_bug.cgi?id=292087
5814
public void testBug340945d() throws JavaModelException {
5815
	this.workingCopies = new ICompilationUnit[1];
5816
	this.workingCopies[0] = getWorkingCopy(
5817
			"/Completion/src/test/Try.java",
5818
			"package test;\n" +
5819
			"public class Try extends Thread{\n" +
5820
			"Object field;\n" +
5821
			"static void foo() {\n" +	// field should not be visible here
5822
			"	int int1 = 1;\n" +
5823
			"	int int2 = 2;\n" +
5824
			"	Object o1 = new Object();\n" +
5825
			"   o1." +
5826
			"}\n" +
5827
			"}\n");
5828
5829
	CompletionTestsRequestor2 requestor = new CompletionTestsRequestor2(true);
5830
	requestor.setRequireExtendedContext(true);
5831
	requestor.allowAllRequiredProposals();
5832
	requestor.setComputeVisibleElements(true);
5833
	String str = this.workingCopies[0].getSource();
5834
	String completeBehind = "o1.";
5835
	int cursorLocation = str.lastIndexOf(completeBehind) + completeBehind.length();
5836
	this.workingCopies[0].codeComplete(cursorLocation, requestor, this.wcOwner);
5837
	assertResults(
5838
			"<CompleteOnName:o1.>",
5839
			requestor.getCompletionNode());
5840
	assertNull(
5841
			"should be null",
5842
			requestor.getCompletionNodeParent());
5843
	assertResults(
5844
			"int int1[pos: unused][id:0]\n" +
5845
			"int int2[pos: unused][id:1]\n" +
5846
			"java.lang.Object o1[pos: unused][id:2]\n",
5847
			requestor.getVisibleLocalVariables());
5848
	assertResults(
5849
			"",
5850
			requestor.getVisibleFields());
5851
	assertResults(
5852
			"static void foo() \n",			
5853
			requestor.getVisibleMethods());
5854
}
5594
}
5855
}
(-)a/org.eclipse.jdt.core.tests.model/src/org/eclipse/jdt/core/tests/model/CompletionTestsRequestor2.java (-2 / +54 lines)
Lines 1-5 Link Here
1
/*******************************************************************************
1
/*******************************************************************************
2
 * Copyright (c) 2004, 2011 IBM Corporation and others.
2
 * Copyright (c) 2004, 2012 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 20-25 Link Here
20
import org.eclipse.jdt.core.IJavaElement;
20
import org.eclipse.jdt.core.IJavaElement;
21
import org.eclipse.jdt.core.Signature;
21
import org.eclipse.jdt.core.Signature;
22
import org.eclipse.jdt.core.compiler.IProblem;
22
import org.eclipse.jdt.core.compiler.IProblem;
23
import org.eclipse.jdt.internal.codeassist.InternalCompletionContext;
24
import org.eclipse.jdt.internal.compiler.ast.ASTNode;
25
import org.eclipse.jdt.internal.compiler.util.ObjectVector;
23
import org.eclipse.jdt.internal.core.JavaElement;
26
import org.eclipse.jdt.internal.core.JavaElement;
24
27
25
public class CompletionTestsRequestor2 extends CompletionRequestor {
28
public class CompletionTestsRequestor2 extends CompletionRequestor {
Lines 600-608 Link Here
600
	
603
	
601
	public boolean canUseDiamond(int proposalNo) {
604
	public boolean canUseDiamond(int proposalNo) {
602
		if (proposalNo < this.proposals.length && this.proposals[proposalNo] != null) {
605
		if (proposalNo < this.proposals.length && this.proposals[proposalNo] != null) {
603
			System.out.println(this.proposals[proposalNo]);
604
			return this.proposals[proposalNo].canUseDiamond(this.context);
606
			return this.proposals[proposalNo].canUseDiamond(this.context);
605
		}
607
		}
606
		return false;
608
		return false;
607
	}
609
	}
610
	
611
	public String getCompletionNode() {
612
		if (this.context instanceof InternalCompletionContext) {
613
			InternalCompletionContext internalCompletionContext = (InternalCompletionContext) this.context;
614
			ASTNode astNode = internalCompletionContext.getCompletionNode();
615
			if (astNode != null) return astNode.toString();
616
			
617
		}
618
		return null;
619
	}
620
	
621
	public String getCompletionNodeParent() {
622
		if (this.context instanceof InternalCompletionContext) {
623
			InternalCompletionContext internalCompletionContext = (InternalCompletionContext) this.context;
624
			ASTNode astNode = internalCompletionContext.getCompletionNodeParent();
625
			if (astNode != null) return astNode.toString();
626
			
627
		}
628
		return null;
629
	}
630
	
631
	public String getVisibleLocalVariables() {
632
		if (this.context instanceof InternalCompletionContext) {
633
			InternalCompletionContext internalCompletionContext = (InternalCompletionContext) this.context;
634
			ObjectVector locals = internalCompletionContext.getVisibleLocalVariables();
635
			if (locals != null) return locals.toString();
636
			
637
		}
638
		return null;
639
	}
640
	
641
	public String getVisibleFields() {
642
		if (this.context instanceof InternalCompletionContext) {
643
			InternalCompletionContext internalCompletionContext = (InternalCompletionContext) this.context;
644
			ObjectVector fields = internalCompletionContext.getVisibleFields();
645
			if (fields != null) return fields.toString();
646
			
647
		}
648
		return null;
649
	}
650
	
651
	public String getVisibleMethods() {
652
		if (this.context instanceof InternalCompletionContext) {
653
			InternalCompletionContext internalCompletionContext = (InternalCompletionContext) this.context;
654
			ObjectVector methods = internalCompletionContext.getVisibleMethods();
655
			if (methods != null) return methods.toString();
656
			
657
		}
658
		return null;
659
	}
608
}
660
}
(-)a/org.eclipse.jdt.core.tests.model/src/org/eclipse/jdt/core/tests/model/CompletionTests_1_5.java (-1 / +21 lines)
Lines 1-5 Link Here
1
/*******************************************************************************
1
/*******************************************************************************
2
 * Copyright (c) 2000, 2011 IBM Corporation and others.
2
 * Copyright (c) 2000, 2012 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 14286-14289 Link Here
14286
			"X1<T>[TYPE_REF]{, test, Ltest.X1<TT;>;, null, null, replace[77, 77], token[77, 77], " + relevance + "}",
14286
			"X1<T>[TYPE_REF]{, test, Ltest.X1<TT;>;, null, null, replace[77, 77], token[77, 77], " + relevance + "}",
14287
			requestor.getResults());
14287
			requestor.getResults());
14288
}
14288
}
14289
// https://bugs.eclipse.org/bugs/show_bug.cgi?id=361963
14290
public void test361963() throws JavaModelException {
14291
	this.workingCopies = new ICompilationUnit[1];
14292
	this.workingCopies[0] = getWorkingCopy(
14293
			"/Completion/src/X.java",
14294
			"public class X<T> {\n" +
14295
			"    void g() {\n" +
14296
			"        return new X() {\n" +
14297
			"            void g() {\n" +
14298
			"                Object o = new X<\n");
14299
	CompletionTestsRequestor2 requestor = new CompletionTestsRequestor2(true, false, true, true, true, true);
14300
	requestor.allowAllRequiredProposals();
14301
	String str = this.workingCopies[0].getSource();
14302
	String completeBehind = "new X<";
14303
	int cursorLocation = str.lastIndexOf(completeBehind) + completeBehind.length();
14304
	this.workingCopies[0].codeComplete(cursorLocation, requestor, this.wcOwner);
14305
	assertResults(
14306
			"X<T>[TYPE_REF]{, , LX<TT;>;, null, null, replace[116, 116], token[116, 116], 51}",
14307
			requestor.getResults());
14308
}
14289
}
14309
}
(-)a/org.eclipse.jdt.core.tests.model/src/org/eclipse/jdt/core/tests/model/CopyMoveElementsTests.java (-2 / +2 lines)
Lines 2452-2458 Link Here
2452
	try {
2452
	try {
2453
		TestProgressMonitor monitor = TestProgressMonitor.getInstance();
2453
		TestProgressMonitor monitor = TestProgressMonitor.getInstance();
2454
		monitor.setCancelledCounter(1);
2454
		monitor.setCancelledCounter(1);
2455
		movePositive(typeSource.getMethods(), new IJavaElement[] {typeDest}, null, null, false, monitor);
2455
		movePositive(typeSource.getMethods(), new IJavaElement[] {typeDest}, null, null, false, true, monitor);
2456
	} catch (OperationCanceledException e) {
2456
	} catch (OperationCanceledException e) {
2457
		isCanceled = true;
2457
		isCanceled = true;
2458
	}
2458
	}
Lines 2488-2494 Link Here
2488
		try {
2488
		try {
2489
			TestProgressMonitor monitor = TestProgressMonitor.getInstance();
2489
			TestProgressMonitor monitor = TestProgressMonitor.getInstance();
2490
			monitor.setCancelledCounter(1);
2490
			monitor.setCancelledCounter(1);
2491
			movePositive(typeSource.getMethods(), new IJavaElement[] {typeDest}, null, null, false, monitor);
2491
			movePositive(typeSource.getMethods(), new IJavaElement[] {typeDest}, null, null, false, true, monitor);
2492
		} catch (OperationCanceledException e) {
2492
		} catch (OperationCanceledException e) {
2493
			isCanceled = true;
2493
			isCanceled = true;
2494
		}
2494
		}
(-)a/org.eclipse.jdt.core.tests.model/src/org/eclipse/jdt/core/tests/model/CopyMoveResourcesTests.java (-37 / +70 lines)
Lines 80-86 Link Here
80
		}
80
		}
81
		IJavaElementDelta destDelta = this.deltaListener.getDeltaFor(container, true);
81
		IJavaElementDelta destDelta = this.deltaListener.getDeltaFor(container, true);
82
		assertTrue("Destination container not changed", destDelta != null && destDelta.getKind() == IJavaElementDelta.CHANGED);
82
		assertTrue("Destination container not changed", destDelta != null && destDelta.getKind() == IJavaElementDelta.CHANGED);
83
		IJavaElementDelta[] deltas = destDelta.getAddedChildren();
83
		IJavaElementDelta[] deltas = null;
84
		if (force) {
85
			deltas = destDelta.getChangedChildren();
86
		}
87
		else {
88
			deltas = destDelta.getAddedChildren();
89
		}
84
		// FIXME: not strong enough
90
		// FIXME: not strong enough
85
		boolean found = false;
91
		boolean found = false;
86
		for (int i = 0; i < deltas.length; i++) {
92
		for (int i = 0; i < deltas.length; i++) {
Lines 809-833 Link Here
809
 * existing CU.
815
 * existing CU.
810
 */
816
 */
811
public void testMoveCU03() throws CoreException {
817
public void testMoveCU03() throws CoreException {
812
	this.createFolder("/P/src/p1");
818
	try {
813
	this.createFile(
819
		this.createFolder("/P/src/p1");
814
		"/P/src/p1/X.java",
820
		this.createFile(
815
		"package p1;\n" +
821
			"/P/src/p1/X.java",
816
		"public class X {\n" +
822
			"package p1;\n" +
817
		"}"
823
			"public class X {\n" +
818
	);
824
			"}"
819
	ICompilationUnit cuSource = getCompilationUnit("/P/src/p1/X.java");
825
		);
826
		ICompilationUnit cuSource = getCompilationUnit("/P/src/p1/X.java");
820
827
821
	this.createFolder("/P/src/p2");
828
		this.createFolder("/P/src/p2");
822
	this.createFile(
829
		this.createFile(
823
		"/P/src/p2/X.java",
830
			"/P/src/p2/X.java",
824
		"package p2;\n" +
831
			"package p2;\n" +
825
		"public class X {\n" +
832
			"public class X {\n" +
826
		"}"
833
			"}"
827
	);
834
		);
828
	IPackageFragment pkgDest = getPackage("/P/src/p2");
835
		IPackageFragment pkgDest = getPackage("/P/src/p2");
829
836
		startDeltas();
830
	movePositive(cuSource, pkgDest, null, null, true);
837
		movePositive(new IJavaElement[] {cuSource}, new IJavaElement[] {pkgDest}, null, null, true, false, null);
838
			assertDeltas(
839
					"Incorrect delta",
840
					"P[*]: {CHILDREN}\n"
841
							+ "	src[*]: {CHILDREN}\n"
842
							+ "		p1[*]: {CHILDREN}\n"
843
							+ "			X.java[-]: {MOVED_TO(X.java [in p2 [in src [in P]]])}\n"
844
							+ "		p2[*]: {CHILDREN}\n"
845
							+ "			X.java[*]: {CONTENT | PRIMARY RESOURCE}");
846
	}
847
	finally {
848
		stopDeltas();
849
	}
831
}
850
}
832
/**
851
/**
833
 * Ensures that a CU can be moved to a different package,
852
 * Ensures that a CU can be moved to a different package,
Lines 853-877 Link Here
853
 * be renamed, overwriting an existing resource.
872
 * be renamed, overwriting an existing resource.
854
 */
873
 */
855
public void testMoveCU05() throws CoreException {
874
public void testMoveCU05() throws CoreException {
856
	this.createFolder("/P/src/p1");
875
	try {
857
	this.createFile(
876
		this.createFolder("/P/src/p1");
858
		"/P/src/p1/X.java",
877
		this.createFile(
859
		"package p1;\n" +
878
			"/P/src/p1/X.java",
860
		"public class X {\n" +
879
			"package p1;\n" +
861
		"}"
880
			"public class X {\n" +
862
	);
881
			"}"
863
	ICompilationUnit cuSource = getCompilationUnit("/P/src/p1/X.java");
882
		);
883
		ICompilationUnit cuSource = getCompilationUnit("/P/src/p1/X.java");
864
884
865
	this.createFolder("/P/src/p2");
885
		this.createFolder("/P/src/p2");
866
	this.createFile(
886
		this.createFile(
867
		"/P/src/p2/Y.java",
887
			"/P/src/p2/Y.java",
868
		"package p2;\n" +
888
			"package p2;\n" +
869
		"public class Y {\n" +
889
			"public class Y {\n" +
870
		"}"
890
			"}"
871
	);
891
		);
872
	IPackageFragment pkgDest = getPackage("/P/src/p2");
892
		IPackageFragment pkgDest = getPackage("/P/src/p2");
873
893
		startDeltas();
874
	movePositive(cuSource, pkgDest, null, "Y.java", true);
894
		movePositive(new IJavaElement[] {cuSource}, new IJavaElement[] {pkgDest}, null, new String[]{"Y.java"}, true, false, null);
895
		assertDeltas(
896
					"Incorrect delta",
897
					"P[*]: {CHILDREN}\n"
898
							+ "	src[*]: {CHILDREN}\n"
899
							+ "		p1[*]: {CHILDREN}\n"
900
							+ "			X.java[-]: {MOVED_TO(Y.java [in p2 [in src [in P]]])}\n"
901
							+ "		p2[*]: {CHILDREN}\n"
902
							+ "			Y.java[*]: {CHILDREN | FINE GRAINED | PRIMARY RESOURCE}\n"
903
							+ "				Y[+]: {MOVED_FROM(X [in X.java [in p1 [in src [in P]]]])}");
904
	}
905
	finally {
906
		stopDeltas();
907
	}
875
}
908
}
876
/**
909
/**
877
 * Ensures that a CU cannot be moved to a different package, replacing an
910
 * Ensures that a CU cannot be moved to a different package, replacing an
(-)a/org.eclipse.jdt.core.tests.model/src/org/eclipse/jdt/core/tests/model/CopyMoveTests.java (-17 / +22 lines)
Lines 253-264 Link Here
253
public void movePositive(IJavaElement[] elements, IJavaElement[] destinations, IJavaElement[] siblings, String[] names, boolean force) throws JavaModelException {
253
public void movePositive(IJavaElement[] elements, IJavaElement[] destinations, IJavaElement[] siblings, String[] names, boolean force) throws JavaModelException {
254
	movePositive(elements, destinations, siblings, names, force, null);
254
	movePositive(elements, destinations, siblings, names, force, null);
255
}
255
}
256
public void movePositive(IJavaElement[] elements, IJavaElement[] destinations, IJavaElement[] siblings, String[] names, boolean force, IProgressMonitor monitor) throws JavaModelException {
257
	movePositive(elements, destinations, siblings, names, force, true, null);
258
}
256
/**
259
/**
257
 * Moves the elements to the containers with optional renaming
260
 * Moves the elements to the containers with optional renaming
258
 * and forcing. The operation should succeed, so any exceptions
261
 * and forcing. The operation should succeed, so any exceptions
259
 * encountered are thrown.
262
 * encountered are thrown.
260
 */
263
 */
261
public void movePositive(IJavaElement[] elements, IJavaElement[] destinations, IJavaElement[] siblings, String[] names, boolean force, IProgressMonitor monitor) throws JavaModelException {
264
public void movePositive(IJavaElement[] elements, IJavaElement[] destinations, IJavaElement[] siblings, String[] names, boolean force, boolean checkDelta, IProgressMonitor monitor) throws JavaModelException {
262
	// if forcing, ensure that a name collision exists
265
	// if forcing, ensure that a name collision exists
263
	int i;
266
	int i;
264
	if (force) {
267
	if (force) {
Lines 275-281 Link Here
275
	}
278
	}
276
279
277
	try {
280
	try {
278
		startDeltas();
281
		if(checkDelta)	startDeltas();
279
282
280
		// move
283
		// move
281
		getJavaModel().move(elements, destinations, siblings, names, force, monitor);
284
		getJavaModel().move(elements, destinations, siblings, names, force, monitor);
Lines 341-364 Link Here
341
					}
344
					}
342
				}
345
				}
343
			}
346
			}
344
			IJavaElementDelta destDelta = null;
347
			if(checkDelta) {
345
			if (isMainType(element, destinations[i]) && names != null && names[i] != null) { //moved/renamed main type to same cu
348
				IJavaElementDelta destDelta = null;
346
				destDelta = this.deltaListener.getDeltaFor(moved.getParent());
349
				if (isMainType(element, destinations[i]) && names != null && names[i] != null) { //moved/renamed main type to same cu
347
				assertTrue("Renamed compilation unit as result of main type not added", destDelta != null && destDelta.getKind() == IJavaElementDelta.ADDED);
350
					destDelta = this.deltaListener.getDeltaFor(moved.getParent());
348
				assertTrue("flag should be F_MOVED_FROM", (destDelta.getFlags() & IJavaElementDelta.F_MOVED_FROM) > 0);
351
					assertTrue("Renamed compilation unit as result of main type not added", destDelta != null && destDelta.getKind() == IJavaElementDelta.ADDED);
349
				assertTrue("moved from handle should be original", destDelta.getMovedFromElement().equals(element.getParent()));
352
					assertTrue("flag should be F_MOVED_FROM", (destDelta.getFlags() & IJavaElementDelta.F_MOVED_FROM) > 0);
350
			} else {
353
					assertTrue("moved from handle should be original", destDelta.getMovedFromElement().equals(element.getParent()));
351
				destDelta = this.deltaListener.getDeltaFor(destinations[i], true);
354
				} else {
352
				assertTrue("Destination container not changed", destDelta != null && destDelta.getKind() == IJavaElementDelta.CHANGED);
355
					destDelta = this.deltaListener.getDeltaFor(destinations[i], true);
353
				IJavaElementDelta[] deltas = destDelta.getAddedChildren();
356
					assertTrue("Destination container not changed", destDelta != null && destDelta.getKind() == IJavaElementDelta.CHANGED);
354
				assertTrue("Added children not correct for element copy", deltas[i].getElement().equals(moved));
357
					IJavaElementDelta[] deltas = destDelta.getAddedChildren();
355
				assertTrue("should be K_ADDED", deltas[i].getKind() == IJavaElementDelta.ADDED);
358
					assertTrue("Added children not correct for element copy", deltas[i].getElement().equals(moved));
356
				IJavaElementDelta sourceDelta= this.deltaListener.getDeltaFor(element, false);
359
					assertTrue("should be K_ADDED", deltas[i].getKind() == IJavaElementDelta.ADDED);
357
				assertTrue("should be K_REMOVED", sourceDelta.getKind() == IJavaElementDelta.REMOVED);
360
					IJavaElementDelta sourceDelta= this.deltaListener.getDeltaFor(element, false);
361
					assertTrue("should be K_REMOVED", sourceDelta.getKind() == IJavaElementDelta.REMOVED);
362
				}
358
			}
363
			}
359
		}
364
		}
360
	} finally {
365
	} finally {
361
		stopDeltas();
366
		if(checkDelta)	stopDeltas();
362
	}
367
	}
363
}
368
}
364
}
369
}
(-)a/org.eclipse.jdt.core.tests.model/src/org/eclipse/jdt/core/tests/model/EncodingTests.java (-2 / +252 lines)
Lines 28-33 Link Here
28
import org.eclipse.core.runtime.content.IContentDescription;
28
import org.eclipse.core.runtime.content.IContentDescription;
29
import org.eclipse.core.runtime.preferences.IEclipsePreferences;
29
import org.eclipse.core.runtime.preferences.IEclipsePreferences;
30
import org.eclipse.core.runtime.preferences.InstanceScope;
30
import org.eclipse.core.runtime.preferences.InstanceScope;
31
import org.eclipse.jdt.core.IClasspathAttribute;
31
import org.eclipse.jdt.core.IClasspathEntry;
32
import org.eclipse.jdt.core.IClasspathEntry;
32
import org.eclipse.jdt.core.ICompilationUnit;
33
import org.eclipse.jdt.core.ICompilationUnit;
33
import org.eclipse.jdt.core.IJavaProject;
34
import org.eclipse.jdt.core.IJavaProject;
Lines 62-68 Link Here
62
	// Use this static initializer to specify subset for tests
63
	// Use this static initializer to specify subset for tests
63
	// All specified tests which do not belong to the class are skipped...
64
	// All specified tests which do not belong to the class are skipped...
64
	static {
65
	static {
65
//		TESTS_NAMES = new String[] { "testBug110576" };
66
//		TESTS_NAMES = new String[] { "testBug361356" };
66
//		TESTS_NUMBERS = new int[] { 2, 12 };
67
//		TESTS_NUMBERS = new int[] { 2, 12 };
67
//		TESTS_RANGE = new int[] { 16, -1 };
68
//		TESTS_RANGE = new int[] { 16, -1 };
68
	}
69
	}
Lines 1217-1223 Link Here
1217
			getWorkspaceRoot().setDefaultCharset(wkspEncoding, null);
1218
			getWorkspaceRoot().setDefaultCharset(wkspEncoding, null);
1218
		}
1219
		}
1219
	}
1220
	}
1220
	
1221
	public void testBug361356() throws Exception {
1222
		String oldEncoding = this.encodingProject.getDefaultCharset();
1223
		try{
1224
			String encoding = "Shift-JIS";
1225
			if (wkspEncoding.equals(encoding))
1226
				getWorkspaceRoot().setDefaultCharset("UTF-8", null);
1227
			this.encodingProject.setDefaultCharset("UTF-8", null);
1228
			IJavaProject project = this.createJavaProject("Encoding2", new String[] {""}, "");
1229
			IFile zipFile = (IFile) this.encodingProject.findMember("testShiftJIS.zip"); //$NON-NLS-1$
1230
			IFile sourceFile = (IFile) this.encodingProject.findMember("src/testShiftJIS/A.java");
1231
			
1232
			IClasspathEntry[] entries = this.encodingJavaProject.getRawClasspath();
1233
			IClasspathEntry newEntry = null;
1234
			for (int index = 0; index < entries.length; index++) {
1235
				IClasspathEntry entry = entries[index];
1236
				if (entry.getPath().toOSString().endsWith("testShiftJIS.jar")) {
1237
					newEntry = entries[index]; 
1238
				}
1239
			}
1240
1241
			IClasspathAttribute attribute = JavaCore.newClasspathAttribute(IClasspathAttribute.SOURCE_ATTACHMENT_ENCODING, encoding);
1242
			project.setRawClasspath(new IClasspathEntry[]{JavaCore.newLibraryEntry(newEntry.getPath(), new Path("/Encoding/src"), null, null, new IClasspathAttribute[]{attribute}, false)}, null);
1243
			sourceFile.setCharset(null, null);
1244
			
1245
			IPackageFragmentRoot root = getPackageFragmentRoot("Encoding2", "testShiftJIS.jar");
1246
			ISourceReference sourceRef = root.getPackageFragment("testShiftJIS").getClassFile("A.class");
1247
			assertNotNull(sourceRef);
1248
			String source = sourceRef.getSource();
1249
			assertNotNull(source);
1250
			String encodedContents = new String (Util.getResourceContentsAsCharArray(sourceFile, encoding));
1251
			char[] charArray = encodedContents.toCharArray();
1252
			encodedContents = new String(CharOperation.remove(charArray, '\r'));
1253
			charArray = source.toCharArray();
1254
			source = new String(CharOperation.remove(charArray, '\r'));
1255
			assertTrue("Sources should be decoded the same way", encodedContents.equals(source));
1256
1257
			attribute = JavaCore.newClasspathAttribute(IClasspathAttribute.SOURCE_ATTACHMENT_ENCODING, "UTF-8");
1258
			project.setRawClasspath(new IClasspathEntry[]{JavaCore.newLibraryEntry(newEntry.getPath(), new Path("/Encoding/src"), null, null, new IClasspathAttribute[]{attribute}, false)}, null);
1259
			sourceFile.setCharset(encoding, null);
1260
			
1261
			root = getPackageFragmentRoot("Encoding2", "testShiftJIS.jar");
1262
			sourceRef = root.getPackageFragment("testShiftJIS").getClassFile("A.class");
1263
			assertNotNull(sourceRef);
1264
			source = sourceRef.getSource();
1265
			assertNotNull(source);
1266
			encodedContents = new String (Util.getResourceContentsAsCharArray(sourceFile, encoding));
1267
			charArray = encodedContents.toCharArray();
1268
			encodedContents = new String(CharOperation.remove(charArray, '\r'));
1269
			charArray = source.toCharArray();
1270
			source = new String(CharOperation.remove(charArray, '\r'));
1271
			assertTrue("Sources should be decoded the same way", encodedContents.equals(source));
1272
1273
			attribute = JavaCore.newClasspathAttribute(IClasspathAttribute.SOURCE_ATTACHMENT_ENCODING, encoding);
1274
			project.setRawClasspath(new IClasspathEntry[]{JavaCore.newLibraryEntry(newEntry.getPath(), new Path("/Encoding/testShiftJIS.zip"), null, null, new IClasspathAttribute[]{attribute}, false)}, null);
1275
			zipFile.setCharset(null, null);
1276
			
1277
			root = getPackageFragmentRoot("Encoding2", "testShiftJIS.jar");
1278
			sourceRef = root.getPackageFragment("testShiftJIS").getClassFile("A.class");
1279
			assertNotNull(sourceRef);
1280
			source = sourceRef.getSource();
1281
			assertNotNull(source);
1282
			encodedContents = new String (Util.getResourceContentsAsCharArray(sourceFile, encoding));
1283
			charArray = encodedContents.toCharArray();
1284
			encodedContents = new String(CharOperation.remove(charArray, '\r'));
1285
			charArray = source.toCharArray();
1286
			source = new String(CharOperation.remove(charArray, '\r'));
1287
			assertTrue("Sources should be decoded the same way", encodedContents.equals(source));
1288
1289
			attribute = JavaCore.newClasspathAttribute(IClasspathAttribute.SOURCE_ATTACHMENT_ENCODING, "UTF-8");
1290
			project.setRawClasspath(new IClasspathEntry[]{JavaCore.newLibraryEntry(newEntry.getPath(), new Path("/Encoding/testShiftJIS.zip"), null, null, new IClasspathAttribute[]{attribute}, false)}, null);
1291
			zipFile.setCharset(encoding, null);
1292
			
1293
			root = getPackageFragmentRoot("Encoding2", "testShiftJIS.jar");
1294
			sourceRef = root.getPackageFragment("testShiftJIS").getClassFile("A.class");
1295
			assertNotNull(sourceRef);
1296
			source = sourceRef.getSource();
1297
			assertNotNull(source);
1298
			encodedContents = new String (Util.getResourceContentsAsCharArray(sourceFile, encoding));
1299
			charArray = encodedContents.toCharArray();
1300
			encodedContents = new String(CharOperation.remove(charArray, '\r'));
1301
			charArray = source.toCharArray();
1302
			source = new String(CharOperation.remove(charArray, '\r'));
1303
			assertTrue("Sources should be decoded the same way", encodedContents.equals(source));
1304
1305
		}
1306
		finally {
1307
			this.encodingProject.setDefaultCharset(oldEncoding, null);
1308
			deleteProject("Encoding2");
1309
			getWorkspaceRoot().setDefaultCharset(wkspEncoding, null);
1310
		}		
1311
	}
1312
	public void testBug361356a() throws Exception {
1313
		String oldEncoding = this.encodingProject.getDefaultCharset();
1314
		try{
1315
			String encoding = "Shift-JIS";
1316
			if (wkspEncoding.equals(encoding))
1317
				getWorkspaceRoot().setDefaultCharset("UTF-8", null);
1318
			this.encodingProject.setDefaultCharset("UTF-8", null);
1319
			IJavaProject project = this.createJavaProject("Encoding2", new String[] {""}, "");
1320
			IFile zipFile = (IFile) this.encodingProject.findMember("testShiftJIS.zip"); //$NON-NLS-1$
1321
			IFile sourceFile = (IFile) this.encodingProject.findMember("src/testShiftJIS/A.java");
1322
			
1323
			IClasspathEntry[] entries = this.encodingJavaProject.getRawClasspath();
1324
			IClasspathEntry newEntry = null;
1325
			for (int index = 0; index < entries.length; index++) {
1326
				IClasspathEntry entry = entries[index];
1327
				if (entry.getPath().toOSString().endsWith("testShiftJIS.jar")) {
1328
					newEntry = entries[index]; 
1329
				}
1330
			}
1331
1332
			IClasspathAttribute attribute = JavaCore.newClasspathAttribute(IClasspathAttribute.SOURCE_ATTACHMENT_ENCODING, encoding);
1333
			attribute = JavaCore.newClasspathAttribute(IClasspathAttribute.SOURCE_ATTACHMENT_ENCODING, encoding);
1334
			project.setRawClasspath(new IClasspathEntry[]{JavaCore.newLibraryEntry(newEntry.getPath(), new Path("/Encoding/testShiftJIS.zip"), null, null, new IClasspathAttribute[]{attribute}, false)}, null);
1335
			zipFile.setCharset(null, null);
1336
			
1337
			IPackageFragmentRoot root = getPackageFragmentRoot("Encoding2", "testShiftJIS.jar");
1338
			ISourceReference sourceRef = root.getPackageFragment("testShiftJIS").getClassFile("A.class");
1339
			assertNotNull(sourceRef);
1340
			String source = sourceRef.getSource();
1341
			assertNotNull(source);
1342
			String encodedContents = new String (Util.getResourceContentsAsCharArray(sourceFile, encoding));
1343
			char[] charArray = encodedContents.toCharArray();
1344
			encodedContents = new String(CharOperation.remove(charArray, '\r'));
1345
			charArray = source.toCharArray();
1346
			source = new String(CharOperation.remove(charArray, '\r'));
1347
			assertTrue("Sources should be decoded the same way", encodedContents.equals(source));
1348
1349
			attribute = JavaCore.newClasspathAttribute(IClasspathAttribute.SOURCE_ATTACHMENT_ENCODING, "UTF-8");
1350
			project.setRawClasspath(new IClasspathEntry[]{JavaCore.newLibraryEntry(newEntry.getPath(), new Path("/Encoding/testShiftJIS.zip"), null, null, new IClasspathAttribute[]{attribute}, false)}, null);
1351
			zipFile.setCharset(encoding, null);
1352
			
1353
			root = getPackageFragmentRoot("Encoding2", "testShiftJIS.jar");
1354
			sourceRef = root.getPackageFragment("testShiftJIS").getClassFile("A.class");
1355
			assertNotNull(sourceRef);
1356
			source = sourceRef.getSource();
1357
			assertNotNull(source);
1358
			encodedContents = new String (Util.getResourceContentsAsCharArray(sourceFile, encoding));
1359
			charArray = encodedContents.toCharArray();
1360
			encodedContents = new String(CharOperation.remove(charArray, '\r'));
1361
			charArray = source.toCharArray();
1362
			source = new String(CharOperation.remove(charArray, '\r'));
1363
			assertTrue("Sources should be decoded the same way", encodedContents.equals(source));
1364
		}
1365
		finally {
1366
			this.encodingProject.setDefaultCharset(oldEncoding, null);
1367
			deleteProject("Encoding2");
1368
			getWorkspaceRoot().setDefaultCharset(wkspEncoding, null);
1369
		}		
1370
	}
1371
	public void testBug361356b() throws Exception {
1372
		String oldEncoding = this.encodingProject.getDefaultCharset();
1373
		File externalSourceZip = null;
1374
		File externalSource = null;
1375
		try{
1376
			String encoding = "Shift-JIS";
1377
			if (wkspEncoding.equals(encoding))
1378
				getWorkspaceRoot().setDefaultCharset("UTF-8", null);
1379
			this.encodingProject.setDefaultCharset("UTF-8", null);
1380
			IJavaProject project = this.createJavaProject("Encoding2", new String[] {""}, "");
1381
			IFile sourceFile = (IFile) this.encodingProject.findMember("src/testShiftJIS/A.java");
1382
			
1383
			File internalSourceZip = new File(getWorkspacePath(), "/Encoding/testShiftJIS.zip");
1384
			externalSourceZip = new File(getExternalPath(), "testShiftJIS.zip");
1385
			File internalSource = new File(getWorkspacePath(), "/Encoding/src");
1386
			externalSource = new File(getExternalPath(), "testShiftJIS");
1387
1388
			copyDirectory(internalSource, externalSource);
1389
			copy(internalSourceZip, externalSourceZip);
1390
			
1391
			IClasspathEntry[] entries = this.encodingJavaProject.getRawClasspath();
1392
			IClasspathEntry newEntry = null;
1393
			for (int index = 0; index < entries.length; index++) {
1394
				IClasspathEntry entry = entries[index];
1395
				if (entry.getPath().toOSString().endsWith("testShiftJIS.jar")) {
1396
					newEntry = entries[index]; 
1397
				}
1398
			}
1399
1400
			IClasspathAttribute attribute = JavaCore.newClasspathAttribute(IClasspathAttribute.SOURCE_ATTACHMENT_ENCODING, encoding);
1401
			attribute = JavaCore.newClasspathAttribute(IClasspathAttribute.SOURCE_ATTACHMENT_ENCODING, encoding);
1402
			project.setRawClasspath(new IClasspathEntry[]{JavaCore.newLibraryEntry(newEntry.getPath(), new Path(getExternalResourcePath("testShiftJIS.zip")), null, null, new IClasspathAttribute[]{attribute}, false)}, null);
1403
			
1404
			IPackageFragmentRoot root = getPackageFragmentRoot("Encoding2", "testShiftJIS.jar");
1405
			ISourceReference sourceRef = root.getPackageFragment("testShiftJIS").getClassFile("A.class");
1406
			assertNotNull(sourceRef);
1407
			String source = sourceRef.getSource();
1408
			assertNotNull(source);
1409
			String encodedContents = new String (Util.getResourceContentsAsCharArray(sourceFile, encoding));
1410
			char[] charArray = encodedContents.toCharArray();
1411
			encodedContents = new String(CharOperation.remove(charArray, '\r'));
1412
			charArray = source.toCharArray();
1413
			source = new String(CharOperation.remove(charArray, '\r'));
1414
			assertTrue("Sources should be decoded the same way", encodedContents.equals(source));
1415
1416
			attribute = JavaCore.newClasspathAttribute(IClasspathAttribute.SOURCE_ATTACHMENT_ENCODING, "UTF-8");
1417
			project.setRawClasspath(new IClasspathEntry[]{JavaCore.newLibraryEntry(newEntry.getPath(), new Path(getExternalResourcePath("testShiftJIS.zip")), null, null, new IClasspathAttribute[]{attribute}, false)}, null);
1418
			
1419
			root = getPackageFragmentRoot("Encoding2", "testShiftJIS.jar");
1420
			sourceRef = root.getPackageFragment("testShiftJIS").getClassFile("A.class");
1421
			assertNotNull(sourceRef);
1422
			source = sourceRef.getSource();
1423
			assertNotNull(source);
1424
			encodedContents = new String (Util.getResourceContentsAsCharArray(sourceFile, encoding));
1425
			charArray = encodedContents.toCharArray();
1426
			encodedContents = new String(CharOperation.remove(charArray, '\r'));
1427
			charArray = source.toCharArray();
1428
			source = new String(CharOperation.remove(charArray, '\r'));
1429
			assertFalse("Sources should not be decoded the same way", encodedContents.equals(source));
1430
			
1431
			attribute = JavaCore.newClasspathAttribute(IClasspathAttribute.SOURCE_ATTACHMENT_ENCODING, encoding);
1432
			project.setRawClasspath(new IClasspathEntry[]{JavaCore.newLibraryEntry(newEntry.getPath(), new Path(getExternalResourcePath("testShiftJIS")), null, null, new IClasspathAttribute[]{attribute}, false)}, null);
1433
			sourceFile.setCharset(null, null);
1434
			
1435
			root = getPackageFragmentRoot("Encoding2", "testShiftJIS.jar");
1436
			sourceRef = root.getPackageFragment("testShiftJIS").getClassFile("A.class");
1437
			assertNotNull(sourceRef);
1438
			source = sourceRef.getSource();
1439
			assertNotNull(source);
1440
			encodedContents = new String (Util.getResourceContentsAsCharArray(sourceFile, encoding));
1441
			charArray = encodedContents.toCharArray();
1442
			encodedContents = new String(CharOperation.remove(charArray, '\r'));
1443
			charArray = source.toCharArray();
1444
			source = new String(CharOperation.remove(charArray, '\r'));
1445
			assertTrue("Sources should be decoded the same way", encodedContents.equals(source));
1446
1447
			attribute = JavaCore.newClasspathAttribute(IClasspathAttribute.SOURCE_ATTACHMENT_ENCODING, "UTF-8");
1448
			project.setRawClasspath(new IClasspathEntry[]{JavaCore.newLibraryEntry(newEntry.getPath(), new Path(getExternalResourcePath("testShiftJIS")), null, null, new IClasspathAttribute[]{attribute}, false)}, null);
1449
			sourceFile.setCharset(encoding, null);
1450
			
1451
			root = getPackageFragmentRoot("Encoding2", "testShiftJIS.jar");
1452
			sourceRef = root.getPackageFragment("testShiftJIS").getClassFile("A.class");
1453
			assertNotNull(sourceRef);
1454
			source = sourceRef.getSource();
1455
			assertNotNull(source);
1456
			encodedContents = new String (Util.getResourceContentsAsCharArray(sourceFile, encoding));
1457
			charArray = encodedContents.toCharArray();
1458
			encodedContents = new String(CharOperation.remove(charArray, '\r'));
1459
			charArray = source.toCharArray();
1460
			source = new String(CharOperation.remove(charArray, '\r'));
1461
			assertFalse("Sources should not be decoded the same way", encodedContents.equals(source));
1462
		}
1463
		finally {
1464
			if (externalSourceZip != null) externalSourceZip.delete();
1465
			if (externalSource != null) deleteExternalResource("testShiftJIS");
1466
			this.encodingProject.setDefaultCharset(oldEncoding, null);
1467
			deleteProject("Encoding2");
1468
			getWorkspaceRoot().setDefaultCharset(wkspEncoding, null);
1469
		}		
1470
	}
1221
	private void verifyUtf8BOM(IFile file) throws CoreException {
1471
	private void verifyUtf8BOM(IFile file) throws CoreException {
1222
		assertNull("File should not have any explicit charset", file.getCharset(false));
1472
		assertNull("File should not have any explicit charset", file.getCharset(false));
1223
		IContentDescription contentDescription = file.getContentDescription();
1473
		IContentDescription contentDescription = file.getContentDescription();
(-)a/org.eclipse.jdt.core.tests.model/src/org/eclipse/jdt/core/tests/model/IgnoreOptionalProblemsFromSourceFoldersTests.java (+289 lines)
Added Link Here
1
/*******************************************************************************
2
 * Copyright (c) 2012 IBM Corporation and others.
3
 * All rights reserved. This program and the accompanying materials
4
 * are made available under the terms of the Eclipse Public License v1.0
5
 * which accompanies this distribution, and is available at
6
 * http://www.eclipse.org/legal/epl-v10.html
7
 *
8
 * Contributors:
9
 *     IBM Corporation - initial API and implementation
10
 *******************************************************************************/
11
package org.eclipse.jdt.core.tests.model;
12
13
import junit.framework.Test;
14
15
import org.eclipse.core.resources.IFile;
16
import org.eclipse.core.runtime.CoreException;
17
import org.eclipse.core.runtime.Path;
18
import org.eclipse.jdt.core.IClasspathAttribute;
19
import org.eclipse.jdt.core.IClasspathEntry;
20
import org.eclipse.jdt.core.ICompilationUnit;
21
import org.eclipse.jdt.core.IJavaProject;
22
import org.eclipse.jdt.core.JavaCore;
23
import org.eclipse.jdt.core.WorkingCopyOwner;
24
25
public class IgnoreOptionalProblemsFromSourceFoldersTests extends ModifyingResourceTests {
26
	private static final IClasspathAttribute ATTR_IGNORE_OPTIONAL_PROBLEMS_TRUE = JavaCore.newClasspathAttribute(IClasspathAttribute.IGNORE_OPTIONAL_PROBLEMS, "true");
27
28
	public static Test suite() {
29
		return buildModelTestSuite(IgnoreOptionalProblemsFromSourceFoldersTests.class);
30
	}
31
32
	public IgnoreOptionalProblemsFromSourceFoldersTests(String name) {
33
		super(name);
34
	}
35
36
	// ignore optional errors
37
	public void test001() throws CoreException {
38
		ICompilationUnit unit = null;
39
		try {
40
			IJavaProject project = createJavaProject("P", new String[] {}, new String[] { "JCL_LIB" }, "bin");
41
			project.setOption(JavaCore.COMPILER_PB_UNUSED_LOCAL, JavaCore.ERROR);
42
43
			IClasspathEntry[] originalCP = project.getRawClasspath();
44
			IClasspathEntry[] newCP = new IClasspathEntry[originalCP.length + 1];
45
			System.arraycopy(originalCP, 0, newCP, 0, originalCP.length);
46
			newCP[originalCP.length] = JavaCore.newSourceEntry(new Path("/P/src"), null, null, null,
47
					new IClasspathAttribute[] { ATTR_IGNORE_OPTIONAL_PROBLEMS_TRUE });
48
			project.setRawClasspath(newCP, null);
49
50
			createFolder("/P/src/p");
51
			IFile file = createFile("/P/src/p/X.java",
52
					"package p;\n" +
53
					"public class X {\n" +
54
					"	public void foo() {\n" +
55
					"		int i;\n" +
56
					"	}\n" +
57
					"}");
58
			unit = (ICompilationUnit) JavaCore.create(file);
59
60
			ProblemRequestor problemRequestor = new ProblemRequestor();
61
			WorkingCopyOwner owner = newWorkingCopyOwner(problemRequestor);
62
			unit.getWorkingCopy(owner, null);
63
			assertProblems("Unexpected problems",
64
					"----------\n" +
65
					"----------\n",
66
					problemRequestor);
67
		} finally {
68
			if (unit != null) {
69
				unit.discardWorkingCopy();
70
			}
71
			deleteProject("P");
72
		}
73
	}
74
75
	// two different source folders ignore only from one
76
	public void test002() throws CoreException {
77
		ICompilationUnit x = null;
78
		ICompilationUnit y = null;
79
		try {
80
			IJavaProject project = createJavaProject("P", new String[] {}, new String[] { "JCL_LIB" }, "bin");
81
			project.setOption(JavaCore.COMPILER_PB_UNUSED_LOCAL, JavaCore.ERROR);
82
83
			IClasspathEntry[] originalCP = project.getRawClasspath();
84
			IClasspathEntry[] newCP = new IClasspathEntry[originalCP.length + 2];
85
			System.arraycopy(originalCP, 0, newCP, 0, originalCP.length);
86
			newCP[originalCP.length] = JavaCore.newSourceEntry(new Path("/P/src"), null, null, null,
87
					new IClasspathAttribute[] { ATTR_IGNORE_OPTIONAL_PROBLEMS_TRUE });
88
			newCP[originalCP.length + 1] = JavaCore.newSourceEntry(new Path("/P/src2"));
89
			project.setRawClasspath(newCP, null);
90
91
			createFolder("/P/src/p");
92
			IFile fileX = createFile("/P/src/p/X.java",
93
					"package p;\n" +
94
					"public class X {\n" +
95
					"	public void foo() {\n" +
96
					"		int i;\n" +
97
					"	}\n" +
98
					"}");
99
			x = (ICompilationUnit) JavaCore.create(fileX);
100
			createFolder("/P/src2/q");
101
			IFile fileY = createFile("/P/src2/q/Y.java",
102
					"package q;\n" +
103
					"public class Y {\n" +
104
					"	public void foo() {\n" +
105
					"		int i;\n" +
106
					"	}\n" +
107
					"}");
108
			y = (ICompilationUnit) JavaCore.create(fileY);
109
110
			ProblemRequestor problemRequestorX = new ProblemRequestor();
111
			WorkingCopyOwner ownerX = newWorkingCopyOwner(problemRequestorX);
112
			x.getWorkingCopy(ownerX, null);
113
			assertProblems("Unexpected problems",
114
					"----------\n" +
115
					"----------\n",
116
					problemRequestorX);
117
118
			ProblemRequestor problemRequestorY = new ProblemRequestor();
119
			WorkingCopyOwner ownerY = newWorkingCopyOwner(problemRequestorY);
120
			y.getWorkingCopy(ownerY, null);
121
			assertProblems("Unexpected problems value",
122
					"----------\n" +
123
					"1. ERROR in /P/src2/q/Y.java\n" +
124
					"The value of the local variable i is not used\n" +
125
					"----------\n",
126
					problemRequestorY);
127
		} finally {
128
			if (x != null) {
129
				x.discardWorkingCopy();
130
			}
131
			if (y != null) {
132
				y.discardWorkingCopy();
133
			}
134
			deleteProject("P");
135
		}
136
	}
137
138
	// two different source folders ignore from both
139
	public void test003() throws CoreException {
140
		ICompilationUnit x = null;
141
		ICompilationUnit y = null;
142
		try {
143
			IJavaProject project = createJavaProject("P", new String[] {}, new String[] { "JCL_LIB" }, "bin");
144
			project.setOption(JavaCore.COMPILER_PB_UNUSED_LOCAL, JavaCore.ERROR);
145
146
			IClasspathEntry[] originalCP = project.getRawClasspath();
147
			IClasspathEntry[] newCP = new IClasspathEntry[originalCP.length + 2];
148
			System.arraycopy(originalCP, 0, newCP, 0, originalCP.length);
149
			newCP[originalCP.length] = JavaCore.newSourceEntry(new Path("/P/src"), null, null, null,
150
					new IClasspathAttribute[] { ATTR_IGNORE_OPTIONAL_PROBLEMS_TRUE });
151
			newCP[originalCP.length + 1] = JavaCore.newSourceEntry(new Path("/P/src2"), null, null, null,
152
					new IClasspathAttribute[] { ATTR_IGNORE_OPTIONAL_PROBLEMS_TRUE });
153
			project.setRawClasspath(newCP, null);
154
155
			createFolder("/P/src/p");
156
			IFile fileX = createFile("/P/src/p/X.java",
157
					"package p;\n" +
158
					"public class X {\n" +
159
					"	public void foo() {\n" +
160
					"		int i;\n" +
161
					"	}\n" +
162
					"}");
163
			x = (ICompilationUnit) JavaCore.create(fileX);
164
			createFolder("/P/src2/q");
165
			IFile fileY = createFile("/P/src2/q/Y.java",
166
					"package q;\n" +
167
					"public class Y {\n" +
168
					"	public void foo() {\n" +
169
					"		int i;\n" +
170
					"	}\n" +
171
					"}");
172
			y = (ICompilationUnit) JavaCore.create(fileY);
173
174
			ProblemRequestor problemRequestorX = new ProblemRequestor();
175
			WorkingCopyOwner ownerX = newWorkingCopyOwner(problemRequestorX);
176
			x.getWorkingCopy(ownerX, null);
177
			assertProblems("Unexpected problems",
178
					"----------\n" +
179
					"----------\n",
180
					problemRequestorX);
181
182
			ProblemRequestor problemRequestorY = new ProblemRequestor();
183
			WorkingCopyOwner ownerY = newWorkingCopyOwner(problemRequestorY);
184
			y.getWorkingCopy(ownerY, null);
185
			assertProblems("Unexpected problems",
186
					"----------\n" +
187
					"----------\n",
188
					problemRequestorY);
189
		} finally {
190
			if (x != null) {
191
				x.discardWorkingCopy();
192
			}
193
			if (y != null) {
194
				y.discardWorkingCopy();
195
			}
196
			deleteProject("P");
197
		}
198
	}
199
200
	// non-optional errors cannot be ignored
201
	public void test004() throws CoreException {
202
		ICompilationUnit unit = null;
203
		try {
204
			IJavaProject project = createJavaProject("P", new String[] {}, new String[] { "JCL_LIB" }, "bin");
205
			project.setOption(JavaCore.COMPILER_PB_UNUSED_LOCAL, JavaCore.ERROR);
206
207
			IClasspathEntry[] originalCP = project.getRawClasspath();
208
			IClasspathEntry[] newCP = new IClasspathEntry[originalCP.length + 1];
209
			System.arraycopy(originalCP, 0, newCP, 0, originalCP.length);
210
			newCP[originalCP.length] = JavaCore.newSourceEntry(new Path("/P/src"), null, null, null,
211
					new IClasspathAttribute[] { ATTR_IGNORE_OPTIONAL_PROBLEMS_TRUE });
212
			project.setRawClasspath(newCP, null);
213
214
			createFolder("/P/src/p");
215
			IFile file = createFile("/P/src/p/X.java",
216
					"package p;\n" +
217
					"public class X {\n" +
218
					"	public void foo() {\n" +
219
					"		int i;\n" +
220
					"	}\n" +
221
					"	public void bar() {\n" +
222
					"		a++;\n" +
223
					"	}\n" +
224
					"}");
225
			unit = (ICompilationUnit) JavaCore.create(file);
226
227
			ProblemRequestor problemRequestor = new ProblemRequestor();
228
			WorkingCopyOwner owner = newWorkingCopyOwner(problemRequestor);
229
			unit.getWorkingCopy(owner, null);
230
			assertProblems("Unexpeted problems",
231
					"----------\n" +
232
					"1. ERROR in /P/src/p/X.java\n" +
233
					"a cannot be resolved to a variable\n" +
234
					"----------\n",
235
					problemRequestor);
236
		} finally {
237
			if (unit != null) {
238
				unit.discardWorkingCopy();
239
			}
240
			deleteProject("P");
241
		}
242
	}
243
244
	// task tags cannot be ignored
245
	public void test005() throws CoreException {
246
		ICompilationUnit unit = null;
247
		try {
248
			IJavaProject project = createJavaProject("P", new String[] {}, new String[] { "JCL_LIB" }, "bin");
249
			project.setOption(JavaCore.COMPILER_PB_UNUSED_LOCAL, JavaCore.ERROR);
250
			project.setOption(JavaCore.COMPILER_TASK_TAGS, "TODO");
251
			project.setOption(JavaCore.COMPILER_TASK_PRIORITIES, "NORMAL");
252
253
			IClasspathEntry[] originalCP = project.getRawClasspath();
254
			IClasspathEntry[] newCP = new IClasspathEntry[originalCP.length + 1];
255
			System.arraycopy(originalCP, 0, newCP, 0, originalCP.length);
256
			newCP[originalCP.length] = JavaCore.newSourceEntry(new Path("/P/src"), null, null, null,
257
					new IClasspathAttribute[] { ATTR_IGNORE_OPTIONAL_PROBLEMS_TRUE });
258
			project.setRawClasspath(newCP, null);
259
260
			createFolder("/P/src/p");
261
			IFile file = createFile("/P/src/p/X.java",
262
					"package p;\n" +
263
					"public class X {\n" +
264
					"	public void foo() {\n" +
265
					"		int i;\n" +
266
					"	}\n" +
267
					"	public void bar() {\n" +
268
					"		// TODO nothing\n" +
269
					"	}\n" +
270
					"}");
271
			unit = (ICompilationUnit) JavaCore.create(file);
272
273
			ProblemRequestor problemRequestor = new ProblemRequestor();
274
			WorkingCopyOwner owner = newWorkingCopyOwner(problemRequestor);
275
			unit.getWorkingCopy(owner, null);
276
			assertProblems("Unexpeted problems",
277
					"----------\n" +
278
					"1. WARNING in /P/src/p/X.java\n" +
279
					"TODO nothing\n" +
280
					"----------\n",
281
					problemRequestor);
282
		} finally {
283
			if (unit != null) {
284
				unit.discardWorkingCopy();
285
			}
286
			deleteProject("P");
287
		}
288
	}
289
}
(-)a/org.eclipse.jdt.core.tests.model/src/org/eclipse/jdt/core/tests/model/JavaIndexTests.java (+866 lines)
Added Link Here
1
/*******************************************************************************
2
 * Copyright (c) 2012 IBM Corporation and others.
3
 * All rights reserved. This program and the accompanying materials
4
 * are made available under the terms of the Eclipse Public License v1.0
5
 * which accompanies this distribution, and is available at
6
 * http://www.eclipse.org/legal/epl-v10.html
7
 *
8
 * Contributors:
9
 *     IBM Corporation - initial API and implementation
10
 *******************************************************************************/
11
package org.eclipse.jdt.core.tests.model;
12
13
import java.io.File;
14
import java.io.IOException;
15
import java.net.URL;
16
17
import junit.framework.Test;
18
19
import org.eclipse.core.resources.IProject;
20
import org.eclipse.core.runtime.CoreException;
21
import org.eclipse.core.runtime.IPath;
22
import org.eclipse.core.runtime.Path;
23
import org.eclipse.core.runtime.preferences.IEclipsePreferences;
24
import org.eclipse.core.runtime.preferences.InstanceScope;
25
import org.eclipse.jdt.core.ClasspathContainerInitializer;
26
import org.eclipse.jdt.core.IClasspathAttribute;
27
import org.eclipse.jdt.core.IClasspathEntry;
28
import org.eclipse.jdt.core.IJavaElement;
29
import org.eclipse.jdt.core.IJavaProject;
30
import org.eclipse.jdt.core.JavaCore;
31
import org.eclipse.jdt.core.index.*;
32
import org.eclipse.jdt.core.search.SearchEngine;
33
import org.eclipse.jdt.core.tests.util.Util;
34
import org.eclipse.jdt.internal.core.JavaModelManager;
35
import org.eclipse.jdt.internal.core.UserLibraryClasspathContainer;
36
import org.osgi.service.prefs.BackingStoreException;
37
38
public class JavaIndexTests extends AbstractJavaSearchTests  {
39
40
	static {
41
		// TESTS_NAMES = new String[] {"testPlatformIndexFile"};
42
	}
43
	public JavaIndexTests(String name) {
44
		super(name);
45
	}
46
47
	public static Test suite() {
48
		return buildModelTestSuite(JavaIndexTests.class);
49
	}
50
	// Test that the index file is really generated.
51
	public void testGenerateIndex() throws IOException {
52
		String indexFilePath = getExternalResourcePath("Test.index");
53
		String jarFilePath = getExternalResourcePath("Test.jar");
54
		try {
55
			createJar(new String[] {
56
					"pkg/Test.java",
57
					"package pkg;\n" +
58
					"public class Test {\n" +
59
					"  protected Test(int i) {}\n" +
60
					"}"}, jarFilePath);
61
			
62
			JavaIndexer.generateIndexForJar(jarFilePath, indexFilePath);
63
			assertTrue(new File(indexFilePath).exists());
64
		} finally {
65
			new File(indexFilePath).delete();
66
			new File(jarFilePath).delete();
67
		}
68
	}
69
	
70
	// Test that the index file and the jar can be deleted after the indexing is done
71
	// This is to ensure that the files are closed
72
	public void testDeleteIndexedFile() {
73
		String indexFilePath = getExternalResourcePath("Test.index");
74
		String jarFilePath = getExternalResourcePath("Test.jar");
75
		try {
76
			createJar(new String[] {
77
					"pkg/Test.java",
78
					"package pkg;\n" +
79
					"public class Test {\n" +
80
					"  protected Test(int i) {}\n" +
81
					"}"}, jarFilePath);
82
			JavaIndexer.generateIndexForJar(jarFilePath, indexFilePath);
83
			assertTrue("Could not delete the index file", new File(indexFilePath).delete());
84
			assertTrue("Could not delete the jar file", new File(jarFilePath).delete());
85
		} catch (IOException e) {
86
			assertFalse("Test failed", true);
87
		}
88
	}
89
	
90
	// Test that search works fine with the index file
91
	public void testUseIndex() throws CoreException, IOException {
92
		String indexFilePath = getExternalResourcePath("Test.index");
93
		String jarFilePath = getExternalResourcePath("Test.jar");
94
		try {
95
			createJar(new String[] {
96
					"pkg/Test.java",
97
					"package pkg;\n" +
98
					"public class Test {\n" +
99
					"  protected Test(int i) {}\n" +
100
					"}"}, jarFilePath);
101
			JavaIndexer.generateIndexForJar(jarFilePath, indexFilePath);
102
			long modified = new File(indexFilePath).lastModified();
103
			
104
			IJavaProject p = createJavaProject("P");
105
			Path libPath = new Path(jarFilePath);
106
			IClasspathAttribute attribute = JavaCore.newClasspathAttribute(IClasspathAttribute.INDEX_LOCATION_ATTRIBUTE_NAME, "file:///"+indexFilePath);
107
			IClasspathEntry entry = JavaCore.newLibraryEntry(libPath, null, null, null, new IClasspathAttribute[]{attribute}, false);
108
			setClasspath(p, new IClasspathEntry[] {entry});
109
			
110
			waitUntilIndexesReady();
111
			
112
			// Test that specified index file is really used
113
			java.io.File indexFile = JavaModelManager.getIndexManager().getIndex(libPath, false, false).getIndexFile();
114
			assertEquals("Specified index file is not being used", indexFilePath,indexFile.toString());
115
			
116
			// Test that search works properly 
117
			search("Test", TYPE, DECLARATIONS, EXACT_RULE, SearchEngine.createJavaSearchScope(new IJavaElement[]{p}));
118
			assertSearchResults(getExternalPath() + "Test.jar pkg.Test");
119
			
120
			// Ensure that the index file is not modified
121
			assertEquals(modified, new File(indexFilePath).lastModified());
122
		} finally {
123
			deleteProject("P");
124
			new File(indexFilePath).delete();
125
			new File(jarFilePath).delete();
126
		}
127
	}
128
	
129
	// Test that the same index file is used even after restarting
130
	public void testUseIndexAfterRestart() throws IOException, CoreException {
131
		String indexFilePath = getExternalResourcePath("Test.index");
132
		String jarFilePath = getExternalResourcePath("Test.jar");
133
		try {
134
			createJar(new String[] {
135
					"pkg/Test.java",
136
					"package pkg;\n" +
137
					"public class Test {\n" +
138
					"  protected Test(int i) {}\n" +
139
					"}"}, jarFilePath);
140
			JavaIndexer.generateIndexForJar(jarFilePath, indexFilePath);
141
			long modified = new File(indexFilePath).lastModified();
142
			IJavaProject p = createJavaProject("P");
143
			Path libPath = new Path(jarFilePath);
144
			IClasspathAttribute attribute = JavaCore.newClasspathAttribute(IClasspathAttribute.INDEX_LOCATION_ATTRIBUTE_NAME, "file:///"+indexFilePath);
145
			IClasspathEntry entry = JavaCore.newLibraryEntry(libPath, null, null, null, new IClasspathAttribute[]{attribute}, false);
146
			setClasspath(p, new IClasspathEntry[] {entry});
147
			waitUntilIndexesReady();
148
			
149
			search("Test", TYPE, DECLARATIONS, EXACT_RULE, SearchEngine.createJavaSearchScope(new IJavaElement[]{p}));
150
			assertSearchResults(getExternalPath() + "Test.jar pkg.Test");
151
			
152
			simulateExitRestart();
153
			getJavaModel().refreshExternalArchives(null, null);
154
			waitUntilIndexesReady();
155
			
156
			this.resultCollector = new JavaSearchResultCollector();
157
			search("Test", TYPE, DECLARATIONS, EXACT_RULE, SearchEngine.createJavaSearchScope(new IJavaElement[]{p}));
158
			assertSearchResults(getExternalPath() + "Test.jar pkg.Test");
159
			
160
			java.io.File indexFile = JavaModelManager.getIndexManager().getIndex(libPath, false, false).getIndexFile();
161
			assertEquals(indexFilePath,indexFile.toString());
162
			// Ensure that the file is not modified
163
			assertEquals(modified, new File(indexFilePath).lastModified());
164
		} finally {
165
			deleteProject("P");
166
			new File(indexFilePath).delete();
167
			new File(jarFilePath).delete();
168
		}
169
	}
170
	
171
	// Test that the same index file is used even after restarting
172
	public void testUseIndexInternalJarAfterRestart() throws IOException, CoreException {
173
		String indexFilePath = getExternalResourcePath("Test.index");
174
		String jarFilePath = "/P/Test.jar";
175
		String fullJarPath = getWorkspacePath() + jarFilePath;
176
		try {
177
			IJavaProject p = createJavaProject("P");
178
			createJar(new String[] {
179
					"pkg/Test.java",
180
					"package pkg;\n" +
181
					"public class Test {\n" +
182
					"  protected Test(int i) {}\n" +
183
					"}"}, fullJarPath);
184
			p.getProject().refreshLocal(1, null);
185
			JavaIndexer.generateIndexForJar(fullJarPath, indexFilePath);
186
			long modified = new File(indexFilePath).lastModified();
187
			IPath libPath = new Path(jarFilePath);
188
			IClasspathAttribute attribute = JavaCore.newClasspathAttribute(IClasspathAttribute.INDEX_LOCATION_ATTRIBUTE_NAME, "file:///"+indexFilePath);
189
			IClasspathEntry entry = JavaCore.newLibraryEntry(libPath, null, null, null, new IClasspathAttribute[]{attribute}, false);
190
			setClasspath(p, new IClasspathEntry[] {entry});
191
			waitUntilIndexesReady();
192
			
193
			search("Test", TYPE, DECLARATIONS, EXACT_RULE, SearchEngine.createJavaSearchScope(new IJavaElement[]{p}));
194
			assertSearchResults("Test.jar pkg.Test [No source]");
195
			java.io.File indexFile = JavaModelManager.getIndexManager().getIndex(libPath, false, false).getIndexFile();
196
			assertEquals(indexFilePath,indexFile.toString());
197
			
198
			simulateExitRestart();
199
			waitUntilIndexesReady();
200
			
201
			this.resultCollector = new JavaSearchResultCollector();
202
			search("Test", TYPE, DECLARATIONS, EXACT_RULE, SearchEngine.createJavaSearchScope(new IJavaElement[]{p}));
203
			assertSearchResults("Test.jar pkg.Test [No source]");
204
			
205
			indexFile = JavaModelManager.getIndexManager().getIndex(libPath, false, false).getIndexFile();
206
			assertEquals(indexFilePath,indexFile.toString());
207
			// Ensure that the file is not modified
208
			assertEquals(modified, new File(indexFilePath).lastModified());
209
		} finally {
210
			deleteProject("P");
211
			new File(indexFilePath).delete();
212
		}
213
	}
214
	
215
	// Test that a jar file that gets modified after the index is created doesn't return new changes. 
216
	// This behavior might have to be modified but.. 
217
	public void testModifyJarAfterIndex() throws CoreException, IOException {
218
		String indexFilePath = getExternalResourcePath("Test.index");
219
		String jarFilePath = getExternalResourcePath("Test.jar");
220
		try {
221
			createJar(new String[] {
222
					"pkg/Test.java",
223
					"package pkg;\n" +
224
					"public class Test {\n" +
225
					"  protected Test(int i) {}\n" +
226
					"}"}, jarFilePath);
227
			JavaIndexer.generateIndexForJar(jarFilePath, indexFilePath);
228
			createJar(new String[] {
229
					"pkg/Test.java",
230
					"package pkg;\n" +
231
					"public class Test {\n" +
232
					"  protected Test(int i) {}\n" +
233
					"}", 
234
					"pkg/NewTest.java",
235
					"package pkg;\n" +
236
					"public class NewTest {\n" +
237
					"  protected NewTest(int i) {}\n" +
238
					"}"}, jarFilePath);
239
			IJavaProject p = createJavaProject("P");
240
			Path libPath = new Path(jarFilePath);
241
			IClasspathAttribute attribute = JavaCore.newClasspathAttribute(IClasspathAttribute.INDEX_LOCATION_ATTRIBUTE_NAME, "file:///"+indexFilePath);
242
			IClasspathEntry entry = JavaCore.newLibraryEntry(libPath, null, null, null, new IClasspathAttribute[]{attribute}, false);
243
			setClasspath(p, new IClasspathEntry[] {entry});
244
			waitUntilIndexesReady();
245
			search("NewTest", TYPE, DECLARATIONS, EXACT_RULE, SearchEngine.createJavaSearchScope(new IJavaElement[]{p}));
246
			assertSearchResults("");
247
		} finally {
248
			deleteProject("P");
249
			new File(indexFilePath).delete();
250
			new File(jarFilePath).delete();
251
		}
252
	}
253
254
	// test a non-existent index
255
	public void testNonExistentIndex() throws CoreException, IOException {
256
		String indexFilePath = getExternalResourcePath("Test.index");
257
		String jarFilePath = getExternalResourcePath("Test.jar");
258
		try {
259
			createJar(new String[] {
260
					"pkg/Test.java",
261
					"package pkg;\n" +
262
					"public class Test {\n" +
263
					"  protected Test(int i) {}\n" +
264
					"}"}, jarFilePath);
265
			IJavaProject p = createJavaProject("P");
266
			Path libPath = new Path(jarFilePath);
267
			new File(indexFilePath).delete();
268
			IClasspathAttribute attribute = JavaCore.newClasspathAttribute(IClasspathAttribute.INDEX_LOCATION_ATTRIBUTE_NAME, "file:///"+indexFilePath);
269
			IClasspathEntry entry = JavaCore.newLibraryEntry(libPath, null, null, null, new IClasspathAttribute[]{attribute}, false);
270
			setClasspath(p, new IClasspathEntry[] {entry});
271
			waitUntilIndexesReady();
272
			search("Test", TYPE, DECLARATIONS, EXACT_RULE, SearchEngine.createJavaSearchScope(new IJavaElement[]{p}));
273
			assertSearchResults(getExternalPath() + "Test.jar pkg.Test");
274
			
275
		} finally {
276
			deleteProject("P");
277
			new File(indexFilePath).delete();
278
			new File(jarFilePath).delete();
279
		}
280
	}
281
	
282
	// test a non-existent index
283
	public void testNonExistentIndexRestart() throws CoreException, IOException {
284
		String indexFilePath = getExternalResourcePath("Test.index");
285
		String jarFilePath = getExternalResourcePath("Test.jar");
286
		try {
287
			createJar(new String[] {
288
					"pkg/Test.java",
289
					"package pkg;\n" +
290
					"public class Test {\n" +
291
					"  protected Test(int i) {}\n" +
292
					"}"}, jarFilePath);
293
			
294
			new File(indexFilePath).delete();
295
			
296
			IJavaProject p = createJavaProject("P");
297
			Path libPath = new Path(jarFilePath);
298
			IClasspathAttribute attribute = JavaCore.newClasspathAttribute(IClasspathAttribute.INDEX_LOCATION_ATTRIBUTE_NAME, "file:///"+indexFilePath);
299
			IClasspathEntry entry = JavaCore.newLibraryEntry(libPath, null, null, null, new IClasspathAttribute[]{attribute}, false);
300
			setClasspath(p, new IClasspathEntry[] {entry});
301
			waitUntilIndexesReady();
302
			
303
			search("Test", TYPE, DECLARATIONS, EXACT_RULE, SearchEngine.createJavaSearchScope(new IJavaElement[]{p}));
304
			assertSearchResults(getExternalPath() + "Test.jar pkg.Test");
305
			
306
			java.io.File indexFile = JavaModelManager.getIndexManager().getIndex(libPath, false, false).getIndexFile();
307
			long modified = indexFile.lastModified();
308
			assertEquals(modified, indexFile.lastModified());
309
			
310
			simulateExitRestart();
311
			getJavaModel().refreshExternalArchives(null,null);
312
			waitUntilIndexesReady();
313
			
314
			this.resultCollector = new JavaSearchResultCollector();
315
			search("Test", TYPE, DECLARATIONS, EXACT_RULE, SearchEngine.createJavaSearchScope(new IJavaElement[]{p}));
316
			assertSearchResults(getExternalPath() + "Test.jar pkg.Test");
317
			
318
			indexFile = JavaModelManager.getIndexManager().getIndex(libPath, false, false).getIndexFile();
319
			assertEquals("Index File should not have got modified",modified, indexFile.lastModified());
320
		} finally {
321
			deleteProject("P");
322
			new File(indexFilePath).delete();
323
			new File(jarFilePath).delete();
324
		}
325
	}
326
	
327
	// test that if the index is not existent after restart, it should build up a new index
328
	public void testNonExistentIndexAfterRestart() throws CoreException, IOException {
329
		String indexFilePath = getExternalResourcePath("Test.index");
330
		String jarFilePath = getExternalResourcePath("Test.jar");
331
		try {
332
			createJar(new String[] {
333
					"pkg/Test.java",
334
					"package pkg;\n" + 
335
					"public class Test {\n" +
336
					"protected Test(int i) {}\n" + "}" 
337
					},jarFilePath);
338
			JavaIndexer.generateIndexForJar(jarFilePath, indexFilePath);
339
			
340
			IJavaProject p = createJavaProject("P");
341
			Path libPath = new Path(jarFilePath);
342
			IClasspathAttribute attribute = JavaCore.newClasspathAttribute(IClasspathAttribute.INDEX_LOCATION_ATTRIBUTE_NAME, "file:///"+indexFilePath);
343
			IClasspathEntry entry = JavaCore.newLibraryEntry(libPath, null, null, null, new IClasspathAttribute[]{attribute}, false);
344
			setClasspath(p, new IClasspathEntry[] {entry});
345
			waitUntilIndexesReady();
346
			
347
			search("Test", TYPE, DECLARATIONS, EXACT_RULE, SearchEngine.createJavaSearchScope(new IJavaElement[]{p}));
348
			assertSearchResults(getExternalPath() + "Test.jar pkg.Test");
349
			
350
			simulateExitRestart();
351
			File indexFile = new File(indexFilePath);
352
			indexFile.delete();
353
			assertTrue(!indexFile.exists());
354
			getJavaModel().refreshExternalArchives(null,null);
355
			waitUntilIndexesReady();
356
			
357
			this.resultCollector = new JavaSearchResultCollector();
358
			search("Test", TYPE, DECLARATIONS, EXACT_RULE, SearchEngine.createJavaSearchScope(new IJavaElement[]{p}));
359
			assertSearchResults(getExternalPath() + "Test.jar pkg.Test");
360
			
361
		} finally {
362
			deleteProject("P");
363
			new File(indexFilePath).delete();
364
			new File(jarFilePath).delete();
365
		}
366
	}
367
	
368
	// test a non-existent index which becomes existent after restart
369
	public void testExistentIndexAfterRestart() throws CoreException, IOException {
370
		String indexFilePath = getExternalResourcePath("Test.index");
371
		String jarFilePath = getExternalResourcePath("Test.jar");
372
		try {
373
			createJar(new String[] {
374
					"pkg/Test.java",
375
					"package pkg;\n" +
376
					"public class Test {\n" +
377
					"  protected Test(int i) {}\n" +
378
					"}"}, jarFilePath);
379
			
380
			File indexFile = new File(indexFilePath);
381
			indexFile.delete();
382
			assertTrue(!indexFile.exists());
383
			
384
			IJavaProject p = createJavaProject("P");
385
			Path libPath = new Path(jarFilePath);
386
			IClasspathAttribute attribute = JavaCore.newClasspathAttribute(IClasspathAttribute.INDEX_LOCATION_ATTRIBUTE_NAME, "file:///"+indexFilePath);
387
			IClasspathEntry entry = JavaCore.newLibraryEntry(libPath, null, null, null, new IClasspathAttribute[]{attribute}, false);
388
			setClasspath(p, new IClasspathEntry[] {entry});
389
			waitUntilIndexesReady();
390
			
391
			search("Test", TYPE, DECLARATIONS, EXACT_RULE, SearchEngine.createJavaSearchScope(new IJavaElement[]{p}));
392
			assertSearchResults(getExternalPath() + "Test.jar pkg.Test");
393
			
394
			JavaIndexer.generateIndexForJar(jarFilePath, indexFilePath);
395
			simulateExitRestart();
396
			getJavaModel().refreshExternalArchives(null,null);
397
			waitUntilIndexesReady();
398
			
399
			this.resultCollector = new JavaSearchResultCollector();
400
			search("Test", TYPE, DECLARATIONS, EXACT_RULE, SearchEngine.createJavaSearchScope(new IJavaElement[]{p}));
401
			assertSearchResults(getExternalPath() + "Test.jar pkg.Test");
402
			
403
			indexFile = JavaModelManager.getIndexManager().getIndex(libPath, false, false).getIndexFile();
404
			assertEquals(indexFilePath,indexFile.toString());
405
		} finally {
406
			deleteProject("P");
407
			new File(indexFilePath).delete();
408
			new File(jarFilePath).delete();
409
		}
410
	}
411
	
412
	// Test that the index file is not deleted when the project is deleted
413
	public void testDeleteProject() throws CoreException, IOException {
414
		String indexFilePath = getExternalResourcePath("Test.index");
415
		String jarFilePath = getExternalResourcePath("Test.jar");
416
		try {
417
			createJar(new String[] {
418
					"pkg/Test.java",
419
					"package pkg;\n" +
420
					"public class Test {\n" +
421
					"  protected Test(int i) {}\n" +
422
					"}"}, jarFilePath);
423
			JavaIndexer.generateIndexForJar(jarFilePath, indexFilePath);
424
			IJavaProject p = createJavaProject("P");
425
			createExternalFolder("externalLib");
426
			Path libPath = new Path(jarFilePath);
427
			IClasspathAttribute attribute = JavaCore.newClasspathAttribute(IClasspathAttribute.INDEX_LOCATION_ATTRIBUTE_NAME, "file:///"+indexFilePath);
428
			IClasspathEntry entry = JavaCore.newLibraryEntry(libPath, null, null, null, new IClasspathAttribute[]{attribute}, false);
429
			setClasspath(p, new IClasspathEntry[] {entry});
430
			waitUntilIndexesReady();
431
			deleteProject("P");
432
			File f = new File(indexFilePath);
433
			assertTrue(f.exists());
434
		} finally {
435
			new File(indexFilePath).delete();
436
			new File(jarFilePath).delete();
437
		}
438
	}
439
	
440
441
	
442
	// Test index file in platform
443
	public void testPlatformIndexFile() throws CoreException, IOException {
444
		String indexFilePath = null;
445
		String jarFilePath = getExternalResourcePath("Test.jar");
446
		String indexUrl = "platform:/resource/P/Test.index";
447
		try {
448
			createJar(new String[] {
449
					"pkg/Test.java",
450
					"package pkg;\n" +
451
					"public class Test {\n" +
452
					"  protected Test(int i) {}\n" +
453
					"}"}, jarFilePath);
454
			
455
			IJavaProject p = createJavaProject("P");
456
			indexFilePath = p.getProject().getLocation().append("Test.index").toFile().getAbsolutePath();
457
			JavaIndexer.generateIndexForJar(jarFilePath, indexFilePath);
458
			long modified = new File(indexFilePath).lastModified();
459
			
460
			Path libPath = new Path(jarFilePath);
461
			IClasspathAttribute attribute = JavaCore.newClasspathAttribute(IClasspathAttribute.INDEX_LOCATION_ATTRIBUTE_NAME, indexUrl);
462
			IClasspathEntry entry = JavaCore.newLibraryEntry(libPath, null, null, null, new IClasspathAttribute[]{attribute}, false);
463
			setClasspath(p, new IClasspathEntry[] {entry});
464
			waitUntilIndexesReady();
465
			
466
			search("Test", TYPE, DECLARATIONS, EXACT_RULE, SearchEngine.createJavaSearchScope(new IJavaElement[]{p}));
467
			assertSearchResults(getExternalPath() + "Test.jar pkg.Test");
468
			
469
			String indexFileName = JavaModelManager.getIndexManager().getIndex(libPath, false, false).getIndexFile().getName();
470
			assertEquals(indexFileName, "Test.index");
471
			
472
			simulateExitRestart();
473
			getJavaModel().refreshExternalArchives(null,null);
474
			waitUntilIndexesReady();
475
			
476
			this.resultCollector = new JavaSearchResultCollector();
477
			search("Test", TYPE, DECLARATIONS, EXACT_RULE, SearchEngine.createJavaSearchScope(new IJavaElement[]{p}));
478
			assertSearchResults(getExternalPath() + "Test.jar pkg.Test");
479
			
480
			indexFileName = JavaModelManager.getIndexManager().getIndex(libPath, false, false).getIndexFile().getName();
481
			assertEquals(indexFileName, "Test.index");
482
483
			assertEquals(modified, new File(indexFilePath).lastModified());
484
		} finally {
485
			deleteProject("P");
486
			if (indexFilePath != null) new File(indexFilePath).delete();
487
			new File(jarFilePath).delete();
488
		}
489
	}
490
	
491
	
492
	public void testEditClasspath() throws CoreException, IOException {
493
		String indexFilePath = getExternalResourcePath("Test.index");
494
		String jarFilePath = getExternalResourcePath("Test.jar");
495
		try {
496
			createJar(new String[] {
497
					"pkg/Test.java",
498
					"package pkg;\n" +
499
					"public class Test {\n" +
500
					"  protected Test(int i) {}\n" +
501
					"}"}, jarFilePath);
502
			JavaIndexer.generateIndexForJar(jarFilePath, indexFilePath);
503
			File f = new File(indexFilePath);
504
			long modified = f.lastModified();
505
			IJavaProject p = this.createJavaProject("P", new String[] {}, "bin");
506
507
			String content = new String(
508
					"<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n"
509
					+ "<classpath>\n"
510
					+ "<classpathentry kind=\"src\" path=\"src a\"/>\n"
511
					+ "<classpathentry kind=\"src\" path=\"src x\"/>\n"
512
					+ "<classpathentry kind=\"lib\" path=\""
513
					+ getExternalJCLPath()
514
					+ "\"/>\n"
515
					+ "<classpathentry kind=\"lib\" path=\""
516
					+ jarFilePath
517
					+ "\">"
518
					+ "<attributes>\n" 
519
					+ "	<attribute name=\"index_location\" value=\"file:///"
520
					+ indexFilePath
521
					+"\"/>\n" 
522
					+ "</attributes>\n"
523
					+ "</classpathentry>\n"
524
					+ "<classpathentry kind=\"output\" path=\"bin\"/>\n"
525
					+ "</classpath>\n");
526
527
			editFile("/P/.classpath", content);
528
			p.open(null);
529
			waitUntilIndexesReady();
530
			search("Test", TYPE, DECLARATIONS, EXACT_RULE, SearchEngine.createJavaSearchScope(new IJavaElement[]{p}));
531
			assertSearchResults(getExternalPath() + "Test.jar pkg.Test");
532
			java.io.File indexFile = JavaModelManager.getIndexManager().getIndex(new Path(jarFilePath), false, false).getIndexFile();
533
			assertEquals(indexFilePath,indexFile.toString());
534
			f = new File(indexFilePath);
535
			assertEquals(modified, f.lastModified());
536
		} finally {
537
			deleteProject("P");
538
			new File(indexFilePath).delete();
539
			new File(jarFilePath).delete();
540
		}
541
	}
542
	
543
	// Test changing the classpath	
544
	public void testChangeClasspath() throws CoreException, IOException {
545
		String indexFilePath = getExternalResourcePath("Test.index");
546
		String jarFilePath = getExternalResourcePath("Test.jar");
547
		try {
548
			createJar(new String[] {
549
					"pkg/Test.java",
550
					"package pkg;\n" +
551
					"public class Test {\n" +
552
					"  protected Test(int i) {}\n" +
553
					"}"}, jarFilePath);
554
			JavaIndexer.generateIndexForJar(jarFilePath, indexFilePath);
555
			createJar(new String[] {
556
					"pkg/Test.java",
557
					"package pkg;\n" +
558
					"public class Test {\n" +
559
					"  protected Test(int i) {}\n" +
560
					"}", 
561
					"pkg/NewTest.java",
562
					"package pkg;\n" +
563
					"public class NewTest {\n" +
564
					"  protected NewTest(int i) {}\n" +
565
					"}"}, jarFilePath);
566
			IJavaProject p = createJavaProject("P");
567
			Path libPath = new Path(jarFilePath);
568
			
569
			IClasspathEntry entry = JavaCore.newLibraryEntry(libPath, null, null, null, null, false);
570
			setClasspath(p, new IClasspathEntry[] {entry});
571
			waitUntilIndexesReady();
572
			search("NewTest", TYPE, DECLARATIONS, EXACT_RULE, SearchEngine.createJavaSearchScope(new IJavaElement[]{p}));
573
			assertSearchResults(getExternalPath() + "Test.jar pkg.NewTest");
574
			
575
			IClasspathAttribute attribute = JavaCore.newClasspathAttribute(IClasspathAttribute.INDEX_LOCATION_ATTRIBUTE_NAME, "file:///"+indexFilePath);
576
			entry = JavaCore.newLibraryEntry(libPath, null, null, null, new IClasspathAttribute[]{attribute}, false);
577
			setClasspath(p, new IClasspathEntry[] {entry});
578
			waitUntilIndexesReady();
579
			this.resultCollector = new JavaSearchResultCollector();
580
			search("NewTest", TYPE, DECLARATIONS, EXACT_RULE, SearchEngine.createJavaSearchScope(new IJavaElement[]{p}));
581
			assertSearchResults("");
582
			
583
			entry = JavaCore.newLibraryEntry(libPath, null, null, null, null, false);
584
			setClasspath(p, new IClasspathEntry[] {entry});
585
			waitUntilIndexesReady();
586
			this.resultCollector = new JavaSearchResultCollector();
587
			search("NewTest", TYPE, DECLARATIONS, EXACT_RULE, SearchEngine.createJavaSearchScope(new IJavaElement[]{p}));
588
			assertSearchResults(getExternalPath() + "Test.jar pkg.NewTest");
589
			
590
			
591
		} finally {
592
			deleteProject("P");
593
			new File(indexFilePath).delete();
594
			new File(jarFilePath).delete();
595
		}
596
	}
597
	
598
	// Test changing the classpath	
599
	public void testChangeClasspathForInternalJar() throws CoreException, IOException {
600
		String indexFilePath = getExternalResourcePath("Test.index");
601
		String jarFilePath = "/P/Test.jar";
602
		String fullJarPath = getWorkspacePath() + jarFilePath;
603
		try {
604
			IJavaProject p = createJavaProject("P");
605
			createJar(new String[] {
606
					"pkg/Test.java",
607
					"package pkg;\n" +
608
					"public class Test {\n" +
609
					"  protected Test(int i) {}\n" +
610
					"}"}, fullJarPath);
611
			JavaIndexer.generateIndexForJar(fullJarPath, indexFilePath);
612
			createJar(new String[] {
613
					"pkg/Test.java",
614
					"package pkg;\n" +
615
					"public class Test {\n" +
616
					"  protected Test(int i) {}\n" +
617
					"}", 
618
					"pkg/NewTest.java",
619
					"package pkg;\n" +
620
					"public class NewTest {\n" +
621
					"  protected NewTest(int i) {}\n" +
622
					"}"}, fullJarPath);
623
			p.getProject().refreshLocal(1, null);
624
			Path libPath = new Path(jarFilePath);
625
			
626
			IClasspathEntry entry = JavaCore.newLibraryEntry(libPath, null, null, null, null, false);
627
			setClasspath(p, new IClasspathEntry[] {entry});
628
			waitUntilIndexesReady();
629
			search("NewTest", TYPE, DECLARATIONS, EXACT_RULE, SearchEngine.createJavaSearchScope(new IJavaElement[]{p}));
630
			assertSearchResults("Test.jar pkg.NewTest [No source]");
631
			
632
			IClasspathAttribute attribute = JavaCore.newClasspathAttribute(IClasspathAttribute.INDEX_LOCATION_ATTRIBUTE_NAME, "file:///"+indexFilePath);
633
			entry = JavaCore.newLibraryEntry(libPath, null, null, null, new IClasspathAttribute[]{attribute}, false);
634
			setClasspath(p, new IClasspathEntry[] {entry});
635
			waitUntilIndexesReady();
636
			this.resultCollector = new JavaSearchResultCollector();
637
			search("NewTest", TYPE, DECLARATIONS, EXACT_RULE, SearchEngine.createJavaSearchScope(new IJavaElement[]{p}));
638
			assertSearchResults("");
639
			
640
			entry = JavaCore.newLibraryEntry(libPath, null, null, null, null, false);
641
			setClasspath(p, new IClasspathEntry[] {entry});
642
			waitUntilIndexesReady();
643
			this.resultCollector = new JavaSearchResultCollector();
644
			search("NewTest", TYPE, DECLARATIONS, EXACT_RULE, SearchEngine.createJavaSearchScope(new IJavaElement[]{p}));
645
			assertSearchResults("Test.jar pkg.NewTest [No source]");	
646
		} finally {
647
			deleteProject("P");
648
			new File(indexFilePath).delete();
649
		}
650
	}
651
		
652
	public void testMultipleProjects() throws CoreException, IOException {
653
		String indexFilePath = getExternalResourcePath("Test.index");
654
		String jarFilePath = getExternalResourcePath("Test.jar");
655
		try {
656
			createJar(new String[] {
657
					"pkg/Test.java",
658
					"package pkg;\n" +
659
					"public class Test {\n" +
660
					"  protected Test(int i) {}\n" +
661
					"}"}, jarFilePath);
662
			JavaIndexer.generateIndexForJar(jarFilePath, indexFilePath);
663
			
664
			IJavaProject p1 = createJavaProject("P1");
665
			Path libPath = new Path(jarFilePath);
666
			IClasspathEntry entry = JavaCore.newLibraryEntry(libPath, null, null, null, null, false);
667
			setClasspath(p1, new IClasspathEntry[] {entry});
668
			waitUntilIndexesReady();
669
			
670
			IJavaProject p2 = createJavaProject("P2");
671
			IClasspathAttribute attribute = JavaCore.newClasspathAttribute(IClasspathAttribute.INDEX_LOCATION_ATTRIBUTE_NAME, "file:///"+indexFilePath);
672
			entry = JavaCore.newLibraryEntry(libPath, null, null, null, new IClasspathAttribute[]{attribute}, false);
673
			setClasspath(p2, new IClasspathEntry[] {entry});
674
			waitUntilIndexesReady();
675
			
676
			search("Test", TYPE, DECLARATIONS, EXACT_RULE, SearchEngine.createJavaSearchScope(new IJavaElement[]{p1}));
677
			assertSearchResults(getExternalPath() + "Test.jar pkg.Test");
678
			
679
			File indexFile = JavaModelManager.getIndexManager().getIndex(libPath, false, false).getIndexFile();
680
			assertEquals(indexFilePath,indexFile.toString());
681
			
682
		} finally {
683
			deleteProject("P1");
684
			deleteProject("P2");
685
			new File(indexFilePath).delete();
686
			new File(jarFilePath).delete();
687
		}
688
	}
689
	
690
	public void setContainerPath(IJavaProject p, IPath jarPath, String indexLocation) throws CoreException, BackingStoreException {
691
		// Create new user library "SomeUserLibrary"
692
		ClasspathContainerInitializer initializer= JavaCore.getClasspathContainerInitializer(JavaCore.USER_LIBRARY_CONTAINER_ID);
693
		String libraryName = "SomeUserLibrary";
694
		IPath containerPath = new Path(JavaCore.USER_LIBRARY_CONTAINER_ID);
695
		UserLibraryClasspathContainer containerSuggestion = new UserLibraryClasspathContainer(libraryName);
696
		initializer.requestClasspathContainerUpdate(containerPath.append(libraryName), null, containerSuggestion);
697
698
		// Modify user library
699
		IEclipsePreferences preferences = InstanceScope.INSTANCE.getNode(JavaCore.PLUGIN_ID);
700
		String propertyName = JavaModelManager.CP_USERLIBRARY_PREFERENCES_PREFIX+"SomeUserLibrary";
701
		StringBuffer propertyValue = new StringBuffer("<?xml version=\"1.0\" encoding=\"UTF-8\"?>\r\n<userlibrary systemlibrary=\"false\" version=\"1\">\r\n<archive ");
702
		//String jarFullPath = getWorkspaceRoot().getLocation().append(jarFile.getFullPath()).toString();
703
		propertyValue.append(" path=\"" + jarPath + "\">\r\n");
704
		propertyValue.append(" <attributes>\r\n");
705
		propertyValue.append("		<attribute name=\"index_location\" value=\"");
706
		propertyValue.append(indexLocation);
707
		propertyValue.append("\"/>\r\n</attributes>\r\n");
708
		propertyValue.append("</archive>\r\n");
709
		propertyValue.append("</userlibrary>\r\n");
710
		preferences.put(propertyName, propertyValue.toString());
711
		preferences.flush();
712
		
713
		IClasspathEntry[] entries = p.getRawClasspath();
714
		int length = entries.length;
715
		System.arraycopy(entries, 0, entries = new IClasspathEntry[length+1], 0, length);
716
		entries[length] = JavaCore.newContainerEntry(containerSuggestion.getPath());
717
		p.setRawClasspath(entries, null);
718
	}
719
	
720
	public void testUserLibraryIndex() throws IOException, CoreException, BackingStoreException {
721
		String indexFilePath = getExternalResourcePath("Test.index");
722
		String jarFilePath = getExternalResourcePath("Test.jar");
723
		try {
724
			createJar(new String[] {
725
					"pkg/Test.java",
726
					"package pkg;\n" +
727
					"public class Test {\n" +
728
					"  protected Test(int i) {}\n" +
729
					"}"}, jarFilePath);
730
			JavaIndexer.generateIndexForJar(jarFilePath, indexFilePath);
731
			long modified = new File(indexFilePath).lastModified();
732
			
733
			IJavaProject p = createJavaProject("P");
734
			
735
			Path libPath = new Path(jarFilePath);
736
			setContainerPath(p, libPath, "file:///"+indexFilePath);
737
			
738
			waitUntilIndexesReady();
739
			
740
			// Test that specified index file is really used
741
			java.io.File indexFile = JavaModelManager.getIndexManager().getIndex(libPath, false, false).getIndexFile();
742
			assertEquals("Specified index file is not being used", indexFilePath,indexFile.toString());
743
			
744
			// Test that search works properly 
745
			search("Test", TYPE, DECLARATIONS, EXACT_RULE, SearchEngine.createJavaSearchScope(new IJavaElement[]{p}));
746
			assertSearchResults(getExternalPath() + "Test.jar pkg.Test");
747
			// Ensure that the index file is not modified
748
			assertEquals(modified, new File(indexFilePath).lastModified());
749
			
750
			simulateExitRestart();
751
			getJavaModel().refreshExternalArchives(null,null);
752
			waitUntilIndexesReady();
753
			
754
			// Test that specified index file is really used
755
			indexFile = JavaModelManager.getIndexManager().getIndex(libPath, false, false).getIndexFile();
756
			assertEquals("Specified index file is not being used", indexFilePath,indexFile.toString());
757
			
758
			// Test that search works properly
759
			this.resultCollector = new JavaSearchResultCollector();
760
			search("Test", TYPE, DECLARATIONS, EXACT_RULE, SearchEngine.createJavaSearchScope(new IJavaElement[]{p}));
761
			assertSearchResults(getExternalPath() + "Test.jar pkg.Test");
762
			// Ensure that the index file is not modified
763
			assertEquals(modified, new File(indexFilePath).lastModified());
764
		} finally {
765
			deleteProject("P");
766
			new File(indexFilePath).delete();
767
			new File(jarFilePath).delete();
768
		}		
769
	}
770
	
771
	// Test that it works if the index file is in the jar file
772
	public void testIndexInJar() throws IOException, CoreException {
773
		String indexFilePath = getExternalResourcePath("Test.index");
774
		String jarFilePath = getExternalResourcePath("Test.jar");
775
		String indexZipPath =  getExternalResourcePath("TestIndex.zip");
776
		try {
777
			createJar(new String[] {
778
					"pkg/Test.java",
779
					"package pkg;\n" +
780
					"public class Test {\n" +
781
					"  protected Test(int i) {}\n" +
782
					"}"}, jarFilePath);
783
			
784
			JavaIndexer.generateIndexForJar(jarFilePath, indexFilePath);
785
			Util.zipFiles(new File[]{new File(indexFilePath)}, indexZipPath);
786
			
787
			IJavaProject p = createJavaProject("P");
788
			Path libPath = new Path(jarFilePath);
789
			String url = "jar:file:"+indexZipPath+"!/Test.index";
790
			IClasspathAttribute attribute = JavaCore.newClasspathAttribute(IClasspathAttribute.INDEX_LOCATION_ATTRIBUTE_NAME, url);
791
			IClasspathEntry entry = JavaCore.newLibraryEntry(libPath, null, null, null, new IClasspathAttribute[]{attribute}, false);
792
			setClasspath(p, new IClasspathEntry[] {entry});
793
			waitUntilIndexesReady();
794
			
795
			assertEquals(url,JavaModelManager.getIndexManager().getIndex(libPath, false, false).getIndexLocation().getUrl().toString());
796
			
797
			search("Test", TYPE, DECLARATIONS, EXACT_RULE, SearchEngine.createJavaSearchScope(new IJavaElement[]{p}));
798
			assertSearchResults(getExternalPath() + "Test.jar pkg.Test");
799
			
800
			simulateExitRestart();
801
			getJavaModel().refreshExternalArchives(null,null);
802
			waitUntilIndexesReady();
803
			
804
			this.resultCollector = new JavaSearchResultCollector();
805
			assertEquals(url,JavaModelManager.getIndexManager().getIndex(libPath, false, false).getIndexLocation().getUrl().toString());
806
			search("Test", TYPE, DECLARATIONS, EXACT_RULE, SearchEngine.createJavaSearchScope(new IJavaElement[]{p}));
807
			assertSearchResults(getExternalPath() + "Test.jar pkg.Test");
808
		} finally {
809
			deleteProject("P");
810
			new File(indexZipPath).delete();
811
			new File(jarFilePath).delete();
812
		}
813
	}
814
815
	// Test index file in platform
816
	public void testPlatformJarIndexFile() throws CoreException, IOException {
817
		String indexFilePath = null;
818
		String jarFilePath = getExternalResourcePath("Test.jar");
819
		String indexUrl = "platform:/resource/ForIndex/Test.index.zip!/Test.index";
820
		try {
821
			createJar(new String[] {
822
					"pkg/Test.java",
823
					"package pkg;\n" +
824
					"public class Test {\n" +
825
					"  protected Test(int i) {}\n" +
826
					"}"}, jarFilePath);
827
			
828
			IProject indexProj = createProject("ForIndex");
829
			indexFilePath = indexProj.getProject().getLocation().append("Test.index").toFile().getAbsolutePath();
830
			JavaIndexer.generateIndexForJar(jarFilePath, indexFilePath);
831
			Util.zipFiles(new File[]{new File(indexFilePath)}, indexFilePath+".zip");
832
			
833
			IJavaProject p = createJavaProject("P");
834
			Path libPath = new Path(jarFilePath);
835
			IClasspathAttribute attribute = JavaCore.newClasspathAttribute(IClasspathAttribute.INDEX_LOCATION_ATTRIBUTE_NAME, indexUrl);
836
			IClasspathEntry entry = JavaCore.newLibraryEntry(libPath, null, null, null, new IClasspathAttribute[]{attribute}, false);
837
			setClasspath(p, new IClasspathEntry[] {entry});
838
			waitUntilIndexesReady();
839
			
840
			search("Test", TYPE, DECLARATIONS, EXACT_RULE, SearchEngine.createJavaSearchScope(new IJavaElement[]{p}));
841
			assertSearchResults(getExternalPath() + "Test.jar pkg.Test");
842
			
843
			URL url = JavaModelManager.getIndexManager().getIndex(libPath, false, false).getIndexLocation().getUrl();
844
			assertEquals(indexUrl, url.toString());
845
			
846
			simulateExitRestart();
847
			getJavaModel().refreshExternalArchives(null,null);
848
			waitUntilIndexesReady();
849
			
850
			this.resultCollector = new JavaSearchResultCollector();
851
			search("Test", TYPE, DECLARATIONS, EXACT_RULE, SearchEngine.createJavaSearchScope(new IJavaElement[]{p}));
852
			assertSearchResults(getExternalPath() + "Test.jar pkg.Test");
853
			
854
			url = JavaModelManager.getIndexManager().getIndex(libPath, false, false).getIndexLocation().getUrl();
855
			assertEquals(indexUrl, url.toString());
856
		} finally {
857
			deleteProject("P");
858
			if (indexFilePath != null) {
859
				new File(indexFilePath).delete();
860
				new File(indexFilePath+".zip").delete();
861
			}
862
			new File(jarFilePath).delete();
863
			deleteProject("ForIndex");
864
		}
865
	}
866
}
(-)a/org.eclipse.jdt.core.tests.model/src/org/eclipse/jdt/core/tests/model/JavaProjectTests.java (-1 / +99 lines)
Lines 37-43 Link Here
37
	super(name);
37
	super(name);
38
}
38
}
39
static {
39
static {
40
//	TESTS_NAMES = new String[] { "testAddExternalLibFolder6" };
40
//	TESTS_NAMES = new String[] { "testBug360164" };
41
}
41
}
42
public static Test suite() {
42
public static Test suite() {
43
	TestSuite suite = (TestSuite) buildModelTestSuite(JavaProjectTests.class);
43
	TestSuite suite = (TestSuite) buildModelTestSuite(JavaProjectTests.class);
Lines 2389-2392 Link Here
2389
		deleteProject("JavaProjectTestsInvalidProject");
2389
		deleteProject("JavaProjectTestsInvalidProject");
2390
	}
2390
	}
2391
}
2391
}
2392
// Bug 360164 - Compile error in XSDImpl
2393
// test that we can tolerate if a 1.4 project refers to an enum inside a library.
2394
public void testBug360164() throws IOException, CoreException {
2395
	String libPath = getWorkspacePath()+"JavaProjectTests/bin/bug360164.jar";
2396
	try {
2397
		this.createJavaProject("P", new String[] {"src"}, new String[] {"JCL_LIB", libPath}, "bin", JavaCore.VERSION_1_4);
2398
		IFile file = createFile("/P/src/X.java", 
2399
				"import p360164.Provider;\n" +
2400
				"import p360164.MyEnum;\n" +
2401
				"public class X {\n" +
2402
				"    int foo(Provider p) {\n" +
2403
				"        MyEnum e = p.getE();\n" +
2404
				"        switch (e.getValue()) {\n" +
2405
				"        case MyEnum.ONE_COMPAT: return 1;\n" +
2406
				"        case MyEnum.TWO_COMPAT: return 2;\n" +
2407
				"        }\n" +
2408
				"        return 0;\n" +
2409
				"    }\n" +
2410
				"}"
2411
		);	
2412
		ICompilationUnit unit = (ICompilationUnit)JavaCore.create(file);
2413
		ProblemRequestor problemRequestor = new ProblemRequestor();
2414
		WorkingCopyOwner owner = newWorkingCopyOwner(problemRequestor);
2415
		unit.getWorkingCopy(owner, null);
2416
		assertProblems("Unexpected problems", 
2417
				"----------\n" + 
2418
				"----------\n", 
2419
				problemRequestor);
2420
	} finally {
2421
		this.deleteProject("P");
2422
	}
2423
}
2424
// Bug 360164 - Compile error in XSDImpl
2425
// test that we still report the missing superclass when resolving non-local methods
2426
public void testBug360164a() throws IOException, CoreException {
2427
	String libPath = getWorkspacePath()+"JavaProjectTests/bin/bug360164.jar";
2428
	try {
2429
		this.createJavaProject("P", new String[] {"src"}, new String[] {"JCL_LIB", libPath}, "bin", JavaCore.VERSION_1_4);
2430
		IFile file = createFile("/P/src/X.java", 
2431
				"import p360164.Provider;\n" +
2432
				"import p360164.MyEnum;\n" +
2433
				"public class X {\n" +
2434
				"    String foo(Provider p) {\n" +
2435
				"        MyEnum e = p.getE();\n" +
2436
				"        return e.toString();\n" +
2437
				"    }\n" +
2438
				"}"
2439
		);	
2440
		ICompilationUnit unit = (ICompilationUnit)JavaCore.create(file);
2441
		ProblemRequestor problemRequestor = new ProblemRequestor();
2442
		WorkingCopyOwner owner = newWorkingCopyOwner(problemRequestor);
2443
		unit.getWorkingCopy(owner, null);
2444
		assertProblems("Unexpected problems", 
2445
				"----------\n" + 
2446
				"1. ERROR in /P/src/X.java\n" + 
2447
				"The type java.lang.Enum cannot be resolved. It is indirectly referenced from required .class files\n" + 
2448
				"----------\n", 
2449
				problemRequestor);
2450
	} finally {
2451
		this.deleteProject("P");
2452
	}
2453
}
2454
// Bug 360317 - [compiler] report switch over enum in 1.4- mode
2455
public void testBug360317() throws IOException, CoreException {
2456
	// use the setup from testBug360164():
2457
	String libPath = getWorkspacePath()+"JavaProjectTests/bin/bug360164.jar";
2458
	try {
2459
		this.createJavaProject("P", new String[] {"src"}, new String[] {"JCL_LIB", libPath}, "bin", JavaCore.VERSION_1_4);
2460
		String sourceX = "import p360164.Provider;\n" +
2461
						 "import p360164.MyEnum;\n" +
2462
						 "public class X {\n" +
2463
						 "    int foo(Provider p) {\n" +
2464
						 "        MyEnum e = p.getE();\n" +
2465
						 "        switch (e) {\n" +
2466
						 "        case ONE: return 1;\n" +
2467
						 "        case TWO: return 2;\n" +
2468
						 "        }\n" +
2469
						 "        return 0;\n" +
2470
						 "    }\n" +
2471
						 "}";
2472
		IFile file = createFile("/P/src/X.java", sourceX);	
2473
		ICompilationUnit unit = (ICompilationUnit)JavaCore.create(file);
2474
		ProblemRequestor problemRequestor = new ProblemRequestor();
2475
		problemRequestor.initialize(sourceX.toCharArray());
2476
		WorkingCopyOwner owner = newWorkingCopyOwner(problemRequestor);
2477
		unit.getWorkingCopy(owner, null);
2478
		assertProblems("Unexpected problems", 
2479
				"----------\n" +
2480
				"1. ERROR in /P/src/X.java (at line 6)\n" +
2481
				"	switch (e) {\n" +
2482
				"	        ^\n" +
2483
				"Cannot switch on an enum value for source level below 1.5. Only convertible int values are permitted\n" +
2484
				"----------\n",
2485
				problemRequestor);
2486
	} finally {
2487
		this.deleteProject("P");
2488
	}
2489
}
2392
}
2490
}
(-)a/org.eclipse.jdt.core.tests.model/src/org/eclipse/jdt/core/tests/model/JavaSearchBugsTests.java (-55 / +86 lines)
Lines 1-5 Link Here
1
/*******************************************************************************
1
/*******************************************************************************
2
 * Copyright (c) 2000, 2011 IBM Corporation and others.
2
 * Copyright (c) 2000, 2012 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 69-75 Link Here
69
import org.eclipse.jdt.core.search.TypeReferenceMatch;
69
import org.eclipse.jdt.core.search.TypeReferenceMatch;
70
import org.eclipse.jdt.core.tests.util.Util;
70
import org.eclipse.jdt.core.tests.util.Util;
71
import org.eclipse.jdt.internal.compiler.classfmt.ClassFileConstants;
71
import org.eclipse.jdt.internal.compiler.classfmt.ClassFileConstants;
72
import org.eclipse.jdt.internal.compiler.impl.CompilerOptions;
73
import org.eclipse.jdt.internal.core.ClassFile;
72
import org.eclipse.jdt.internal.core.ClassFile;
74
import org.eclipse.jdt.internal.core.JavaModelManager;
73
import org.eclipse.jdt.internal.core.JavaModelManager;
75
import org.eclipse.jdt.internal.core.SourceMethod;
74
import org.eclipse.jdt.internal.core.SourceMethod;
Lines 94-100 Link Here
94
// Debug
93
// Debug
95
static {
94
static {
96
//	 org.eclipse.jdt.internal.core.search.BasicSearchEngine.VERBOSE = true;
95
//	 org.eclipse.jdt.internal.core.search.BasicSearchEngine.VERBOSE = true;
97
//	TESTS_NAMES = new String[] {"testBug306223"};
96
//	TESTS_NAMES = new String[] {"testBug324189d"};
98
}
97
}
99
98
100
public JavaSearchBugsTests(String name) {
99
public JavaSearchBugsTests(String name) {
Lines 710-715 Link Here
710
	suite.addTest(new JavaSearchBugsTests("testBug350885"));
709
	suite.addTest(new JavaSearchBugsTests("testBug350885"));
711
	suite.addTest(new JavaSearchBugsTests("testBug349683"));
710
	suite.addTest(new JavaSearchBugsTests("testBug349683"));
712
	suite.addTest(new JavaSearchBugsTests("testBug345807"));
711
	suite.addTest(new JavaSearchBugsTests("testBug345807"));
712
	suite.addTest(new JavaSearchBugsTests("testBug355605"));
713
	suite.addTest(new JavaSearchBugsTests("testBug241834"));
713
	return suite;
714
	return suite;
714
}
715
}
715
class TestCollector extends JavaSearchResultCollector {
716
class TestCollector extends JavaSearchResultCollector {
Lines 11579-11587 Link Here
11579
 */
11580
 */
11580
public void testBug286379c() throws CoreException {
11581
public void testBug286379c() throws CoreException {
11581
	class TestResourceChangeListener implements IResourceChangeListener {
11582
	class TestResourceChangeListener implements IResourceChangeListener {
11582
		boolean valid = false;
11583
		boolean toRemPresent = false;
11583
		public void resourceChanged(IResourceChangeEvent event) {
11584
		public void resourceChanged(IResourceChangeEvent event) {
11584
			this.valid = validate(event.getDelta());
11585
			this.toRemPresent = validate(event.getDelta());
11585
		}
11586
		}
11586
		/*
11587
		/*
11587
		 * Ensure that the listener receives a delta concerning the resource
11588
		 * Ensure that the listener receives a delta concerning the resource
Lines 11604-11620 Link Here
11604
	        return false;
11605
	        return false;
11605
        }
11606
        }
11606
	}
11607
	}
11607
	// print statement to debug random failures of this test
11608
	JavaModelManager.DEBUG_302850 = true;
11609
	System.out.println("================================================================================");
11610
	System.out.println("Starting test JavaSearchBugTests.testBug286379c()...");
11611
	System.out.println("	- Default Options at test start:");
11612
	System.out.println(Util.indentString(new CompilerOptions(JavaCore.getDefaultOptions()).toString(), 1));
11613
	System.out.println("	- Options at test start:");
11614
	System.out.println("		+ Task tags:           " + JavaCore.getOption(JavaCore.COMPILER_TASK_TAGS));
11615
	System.out.println("		+ Task priorities:     " + JavaCore.getOption(JavaCore.COMPILER_TASK_PRIORITIES));
11616
	System.out.println("		+ Forbidden reference: " + JavaCore.getOption(JavaCore.COMPILER_PB_FORBIDDEN_REFERENCE));
11617
	System.out.println(Util.indentString(new CompilerOptions(JavaCore.getOptions()).toString(), 2));
11618
	
11608
	
11619
	IContentType javaContentType = Platform.getContentTypeManager().getContentType(JavaCore.JAVA_SOURCE_CONTENT_TYPE);
11609
	IContentType javaContentType = Platform.getContentTypeManager().getContentType(JavaCore.JAVA_SOURCE_CONTENT_TYPE);
11620
	TestResourceChangeListener changeListener = new TestResourceChangeListener();
11610
	TestResourceChangeListener changeListener = new TestResourceChangeListener();
Lines 11644-11650 Link Here
11644
		// fail as we don't get any specific event from the platform to refresh the indexes.
11634
		// fail as we don't get any specific event from the platform to refresh the indexes.
11645
		// see https://bugs.eclipse.org/bugs/show_bug.cgi?id=118619
11635
		// see https://bugs.eclipse.org/bugs/show_bug.cgi?id=118619
11646
		int counter = 0;
11636
		int counter = 0;
11647
		while (!changeListener.valid) {
11637
		while (!changeListener.toRemPresent) {
11648
			try {
11638
			try {
11649
				Thread.sleep(100);
11639
				Thread.sleep(100);
11650
			}
11640
			}
Lines 11657-11677 Link Here
11657
		// Wait to be sure that indexes are ready after the new resource was added
11647
		// Wait to be sure that indexes are ready after the new resource was added
11658
		waitUntilIndexesReady();
11648
		waitUntilIndexesReady();
11659
11649
11660
		// print statement to debug random failures of this test
11661
		System.out.println("	- Options before first exit:");
11662
		System.out.println("		+ Task tags:           " + JavaCore.getOption(JavaCore.COMPILER_TASK_TAGS));
11663
		System.out.println("		+ Task priorities:     " + JavaCore.getOption(JavaCore.COMPILER_TASK_PRIORITIES));
11664
		System.out.println("		+ Forbidden reference: " + JavaCore.getOption(JavaCore.COMPILER_PB_FORBIDDEN_REFERENCE));
11665
		System.out.println(Util.indentString(new CompilerOptions(JavaCore.getOptions()).toString(), 2));
11666
		// Restart to let the indexes to be refreshed
11650
		// Restart to let the indexes to be refreshed
11667
		simulateExit();
11651
		simulateExit();
11668
		simulateRestart();
11652
		simulateRestart();
11669
		// print statement to debug random failures of this test
11670
		System.out.println("	- Options after first restart:");
11671
		System.out.println("		+ Task tags:           " + JavaCore.getOption(JavaCore.COMPILER_TASK_TAGS));
11672
		System.out.println("		+ Task priorities:     " + JavaCore.getOption(JavaCore.COMPILER_TASK_PRIORITIES));
11673
		System.out.println("		+ Forbidden reference: " + JavaCore.getOption(JavaCore.COMPILER_PB_FORBIDDEN_REFERENCE));
11674
		System.out.println(Util.indentString(new CompilerOptions(JavaCore.getOptions()).toString(), 2));
11675
		waitUntilIndexesReady();
11653
		waitUntilIndexesReady();
11676
11654
11677
		// Search for the new type with new extension
11655
		// Search for the new type with new extension
Lines 11689-11710 Link Here
11689
				false /*only assume*/);
11667
				false /*only assume*/);
11690
		
11668
		
11691
		// Delete the file specification
11669
		// Delete the file specification
11670
		changeListener.toRemPresent = true;
11692
		javaContentType.removeFileSpec("torem", IContentType.FILE_EXTENSION_SPEC);
11671
		javaContentType.removeFileSpec("torem", IContentType.FILE_EXTENSION_SPEC);
11672
		counter = 0;
11673
		while (changeListener.toRemPresent) {
11674
			try {
11675
				Thread.sleep(100);
11676
			}
11677
			catch (InterruptedException ie) {
11678
				// skip
11679
			}
11680
			assertTrue("We should have got a resource event within a 10s delay!", counter++ < 100);
11681
		}
11682
		waitUntilIndexesReady();
11693
		
11683
		
11694
		// print statement to debug random failures of this test
11695
		System.out.println("	- Options before second exit:");
11696
		System.out.println("		+ Task tags:           " + JavaCore.getOption(JavaCore.COMPILER_TASK_TAGS));
11697
		System.out.println("		+ Task priorities:     " + JavaCore.getOption(JavaCore.COMPILER_TASK_PRIORITIES));
11698
		System.out.println("		+ Forbidden reference: " + JavaCore.getOption(JavaCore.COMPILER_PB_FORBIDDEN_REFERENCE));
11699
		System.out.println(Util.indentString(new CompilerOptions(JavaCore.getOptions()).toString(), 2));
11700
		// Restarting should update the index file to remove the references of any .torem files
11684
		// Restarting should update the index file to remove the references of any .torem files
11701
		simulateExit();
11685
		simulateExit();
11702
		simulateRestart();	
11686
		simulateRestart();
11703
		// print statement to debug random failures of this test
11704
		System.out.println("	- Options after second restart:");
11705
		System.out.println("		+ Task tags:           " + JavaCore.getOption(JavaCore.COMPILER_TASK_TAGS));
11706
		System.out.println("		+ Task priorities:     " + JavaCore.getOption(JavaCore.COMPILER_TASK_PRIORITIES));
11707
		System.out.println("		+ Forbidden reference: " + JavaCore.getOption(JavaCore.COMPILER_PB_FORBIDDEN_REFERENCE));
11708
		waitUntilIndexesReady();
11687
		waitUntilIndexesReady();
11709
11688
11710
		// Search for the new type with new extension
11689
		// Search for the new type with new extension
Lines 11717-11740 Link Here
11717
				IJavaSearchConstants.WAIT_UNTIL_READY_TO_SEARCH,
11696
				IJavaSearchConstants.WAIT_UNTIL_READY_TO_SEARCH,
11718
				null);
11697
				null);
11719
		assertSearchResults("No search results expected", "", collector);
11698
		assertSearchResults("No search results expected", "", collector);
11720
		System.out.println("	- Options after search:");
11721
		System.out.println("		+ Task tags:           " + JavaCore.getOption(JavaCore.COMPILER_TASK_TAGS));
11722
		System.out.println("		+ Task priorities:     " + JavaCore.getOption(JavaCore.COMPILER_TASK_PRIORITIES));
11723
		System.out.println("		+ Forbidden reference: " + JavaCore.getOption(JavaCore.COMPILER_PB_FORBIDDEN_REFERENCE));
11724
		System.out.println(Util.indentString(new CompilerOptions(JavaCore.getOptions()).toString(), 2));
11725
	} finally {
11699
	} finally {
11726
		getWorkspace().removeResourceChangeListener(changeListener);
11700
		getWorkspace().removeResourceChangeListener(changeListener);
11727
		if (javaContentType != null)
11701
		if (javaContentType != null)
11728
			javaContentType.removeFileSpec("torem", IContentType.FILE_EXTENSION_SPEC);
11702
			javaContentType.removeFileSpec("torem", IContentType.FILE_EXTENSION_SPEC);
11729
		deleteProject("P");
11703
		deleteProject("P");
11730
		System.out.println("	- Options at test end:");
11731
		System.out.println("		+ Task tags:           " + JavaCore.getOption(JavaCore.COMPILER_TASK_TAGS));
11732
		System.out.println("		+ Task priorities:     " + JavaCore.getOption(JavaCore.COMPILER_TASK_PRIORITIES));
11733
		System.out.println("		+ Forbidden reference: " + JavaCore.getOption(JavaCore.COMPILER_PB_FORBIDDEN_REFERENCE));
11734
		System.out.println(Util.indentString(new CompilerOptions(JavaCore.getOptions()).toString(), 2));
11735
		System.out.println("	- Default Options at test end:");
11736
		System.out.println(Util.indentString(new CompilerOptions(JavaCore.getDefaultOptions()).toString(), 2));
11737
		JavaModelManager.DEBUG_302850 = false;
11738
	}
11704
	}
11739
}
11705
}
11740
11706
Lines 13434-13440 Link Here
13434
			},
13400
			},
13435
			new HashMap(),
13401
			new HashMap(),
13436
			libPath);
13402
			libPath);
13437
		IJavaProject javaProject = createJavaProject("P", new String[0], new String[] {libPath}, "");
13403
		IJavaProject javaProject = createJavaProject("P", new String[0], new String[] {libPath, "JCL_LIB"}, "");
13438
		waitUntilIndexesReady();
13404
		waitUntilIndexesReady();
13439
		int mask = IJavaSearchScope.APPLICATION_LIBRARIES | IJavaSearchScope.SOURCES ;
13405
		int mask = IJavaSearchScope.APPLICATION_LIBRARIES | IJavaSearchScope.SOURCES ;
13440
		IJavaSearchScope scope = SearchEngine.createJavaSearchScope(new IJavaElement[] { javaProject }, mask);
13406
		IJavaSearchScope scope = SearchEngine.createJavaSearchScope(new IJavaElement[] { javaProject }, mask);
Lines 13713-13716 Link Here
13713
		deleteProject("Project2");
13679
		deleteProject("Project2");
13714
	}
13680
	}
13715
}
13681
}
13682
// https://bugs.eclipse.org/bugs/show_bug.cgi?id=355605
13683
public void testBug355605() throws CoreException {
13684
	try {
13685
	createJavaProject("P");
13686
13687
		String fileContent = 				
13688
			"public class X { \n" 
13689
			+ "class R {\n"
13690
			+ "   class S {\n" 
13691
			+ "   	void setInfo(String x) {\n"
13692
			+ "   	}\n" 
13693
			+ "   }\n"
13694
			+ "   class T {\n"
13695
			+ "   }\n"
13696
			+ "	T t = new T()  {\n" 
13697
			+ "		S s = new S() {\n"
13698
			+ "           void myMethod() {\n"
13699
			+ "               setInfo(\"a\");\n" 
13700
			+ "           }\n"
13701
			+ "      };// S ends\n"
13702
			+ "   };\n" 
13703
			+ "}\n" 
13704
			+ "}\n" ;
13705
		createFile("/P/X.java", fileContent);
13706
		
13707
		waitUntilIndexesReady();
13708
		this.resultCollector = new TestCollector();
13709
		this.resultCollector.showAccuracy(true);
13710
		ICompilationUnit unit = getCompilationUnit("/P/X.java");
13711
		IMethod method = selectMethod(unit, "myMethod", 1);
13712
		IJavaSearchScope hierarchyScope = SearchEngine.createHierarchyScope((IType)method.getParent());
13713
		search(method, IMPLEMENTORS, EXACT_RULE, hierarchyScope, this.resultCollector);
13714
		assertSearchResults("Unexpected search results!", "X.java void X$R.t:<anonymous>#1.s:<anonymous>#1.myMethod() [myMethod] EXACT_MATCH", this.resultCollector);
13715
		
13716
	} finally {
13717
		deleteProject("P");
13718
	}
13719
}
13720
/**
13721
 * @bug 241834: [search] ClassCastException during move class refactoring
13722
 * @test that search for declarations of referenced types doesn't cause CCE
13723
 * @see "https://bugs.eclipse.org/bugs/show_bug.cgi?id=241834"
13724
 */
13725
public void testBug241834() throws CoreException {
13726
	try {
13727
		IJavaProject project = createJavaProject("P");
13728
		project.setOption(JavaCore.COMPILER_DOC_COMMENT_SUPPORT, JavaCore.ENABLED);
13729
		createFolder("/P/pkg");
13730
		createFile("/P/pkg/Foo.java",
13731
				"package pkg;\n"+
13732
				"/**\n" +
13733
				"  * {@link missing.Foo}\n" +
13734
				"  */\n" +
13735
				"public class Foo {\n" +
13736
				"}\n");
13737
		waitUntilIndexesReady();
13738
		IType type = getCompilationUnit("/P/pkg/Foo.java").getType("Foo");
13739
		searchDeclarationsOfReferencedTypes(type, this.resultCollector);
13740
		assertSearchResults("");
13741
	} finally {
13742
		deleteProject("P");
13743
		
13744
	}
13745
}
13746
// Add new tests in JavaSearchBugsTests2
13716
}
13747
}
(-)a/org.eclipse.jdt.core.tests.model/src/org/eclipse/jdt/core/tests/model/JavaSearchBugsTests2.java (+484 lines)
Added Link Here
1
/*******************************************************************************
2
 * Copyright (c) 2012 IBM Corporation and others.
3
 * All rights reserved. This program and the accompanying materials
4
 * are made available under the terms of the Eclipse Public License v1.0
5
 * which accompanies this distribution, and is available at
6
 * http://www.eclipse.org/legal/epl-v10.html
7
 * 
8
 * Contributors:
9
 *     IBM Corporation - initial API and implementation
10
 *******************************************************************************/
11
12
package org.eclipse.jdt.core.tests.model;
13
14
import java.io.IOException;
15
import java.util.ArrayList;
16
import java.util.List;
17
18
import junit.framework.Test;
19
20
import org.eclipse.core.runtime.CoreException;
21
import org.eclipse.jdt.core.IJavaElement;
22
import org.eclipse.jdt.core.IJavaProject;
23
import org.eclipse.jdt.core.IMethod;
24
import org.eclipse.jdt.core.IType;
25
import org.eclipse.jdt.core.search.IJavaSearchConstants;
26
import org.eclipse.jdt.core.search.IJavaSearchScope;
27
import org.eclipse.jdt.core.search.SearchEngine;
28
import org.eclipse.jdt.core.search.SearchMatch;
29
import org.eclipse.jdt.core.search.SearchPattern;
30
31
// The size of JavaSearchBugsTests.java is very big, Hence continuing here.
32
public class JavaSearchBugsTests2 extends AbstractJavaSearchTests {
33
34
	public JavaSearchBugsTests2(String name) {
35
		super(name);
36
		this.endChar = "";
37
	}
38
	
39
	static {
40
		//TESTS_NAMES = new String[] {"testBug123836"};
41
	}
42
43
	public static Test suite() {
44
		return buildModelTestSuite(JavaSearchBugsTests2.class);
45
	}
46
47
	class TestCollector extends JavaSearchResultCollector {
48
		public List matches = new ArrayList();
49
50
		public void acceptSearchMatch(SearchMatch searchMatch) throws CoreException {
51
			super.acceptSearchMatch(searchMatch);
52
			this.matches.add(searchMatch);
53
		}
54
	}
55
56
	protected void setUp() throws Exception {
57
		super.setUp();
58
		this.resultCollector = new TestCollector();
59
		this.resultCollector.showAccuracy(true);
60
	}
61
62
	/**
63
	 * Test that missing types in the class shouldn't impact the search of a type in an inner class
64
	 */
65
	public void testBug362633() throws CoreException, IOException {
66
		try {
67
			IJavaProject p = createJavaProject("P", new String[] {}, new String[] { "/P/lib325418.jar", "JCL15_LIB" }, "", "1.5");
68
			org.eclipse.jdt.core.tests.util.Util.createJar(new String[] {
69
					"p325418M/Missing.java",
70
					"package p325418M;\n" + 
71
					"public class Missing{}\n" }, 
72
					p.getProject().getLocation().append("lib325418M.jar").toOSString(), "1.5");
73
			
74
			org.eclipse.jdt.core.tests.util.Util.createJar(
75
							new String[] {
76
							"p325418/Test.java",
77
							"package p325418;\n" +
78
							"public class Test{\n" +
79
							"	public void foo(p325418M.Missing a) {}\n" +
80
							"	public <T> T foo(int a) {\n" +
81
							 "		return new Inner<T>() {T  run() {  return null;  }}.run();\n" +
82
							 "	}\n" + "}\n",
83
							"p325418/Inner.java",
84
							"package p325418;\n" +
85
							"abstract class Inner <T> {\n" +
86
							"	 abstract T run();\n" + "}\n" },
87
							null,
88
							p.getProject().getLocation().append("lib325418.jar").toOSString(),
89
							new String[] { p.getProject().getLocation().append("lib325418M.jar").toOSString() },
90
							"1.5");
91
			refresh(p);
92
			int mask = IJavaSearchScope.APPLICATION_LIBRARIES | IJavaSearchScope.SOURCES;
93
			IJavaSearchScope scope = SearchEngine.createJavaSearchScope(new IJavaElement[] { p }, mask);
94
			search("Inner.run()", IJavaSearchConstants.METHOD, IJavaSearchConstants.DECLARATIONS, scope, this.resultCollector);
95
			assertSearchResults(
96
					"Unexpected search results!",
97
					"lib325418.jar T p325418.Inner.run() [No source] EXACT_MATCH\n" +
98
					"lib325418.jar T p325418.<anonymous>.run() [No source] EXACT_MATCH",
99
					this.resultCollector);
100
		} finally {
101
			deleteProject("P");
102
		}
103
	}
104
	
105
	/**
106
	 * @bug 123836: [1.5][search] for references to overriding method with bound type variable is not polymorphic
107
	 * @test Search for references to an overridden method with bound variables should yield.
108
	 * @see "https://bugs.eclipse.org/bugs/show_bug.cgi?id=123836"
109
	 */
110
	public void testBug123836a() throws CoreException {
111
		IJavaProject project = null;
112
		try
113
		{
114
			project = createJavaProject("P", new String[] {""}, new String[] {"JCL15_LIB"}, "","1.5");	
115
			createFile("/P/Sub.java", 
116
					"abstract class Sup<C> {\n" +
117
					"    protected void m(C classifier) {}\n"+
118
					"    public void use(C owner) { m (owner); }\n" +
119
					"}\n" +
120
					"public class Sub extends Sup<String>{\n" +
121
					"    @Override\n"+
122
					"    protected void m(String classifier) {}\n"+
123
					"}\n");
124
			IType type = getCompilationUnit("/P/Sub.java").getType("Sub");
125
			IMethod method = type.getMethod("m", new String[]{"QString;"});
126
			search(method, REFERENCES, EXACT_RULE, SearchEngine.createWorkspaceScope(), this.resultCollector);
127
			assertSearchResults("Sub.java void Sup.use(C) [m (owner)] EXACT_MATCH");
128
		} finally {
129
			deleteProject(project);
130
		}
131
	}
132
	// Search for a non-overriden method with same name as which could have been overriden should
133
	// not have results
134
	public void testBug123836b() throws CoreException {
135
		IJavaProject project = null;
136
		try
137
		{
138
			project = createJavaProject("P", new String[] {""}, new String[] {"JCL15_LIB"}, "","1.5");	
139
			createFile("/P/Sub.java", 
140
					"abstract class Sup<C> {\n" +
141
					"    protected void m(C classifier) {}\n"+
142
					"    public void use(C owner) { m (owner); }\n" +
143
					"}\n" +
144
					"public class Sub extends Sup<String>{\n" +
145
					"    @Override\n"+
146
					"    protected void m(String classifier) {}\n"+
147
					"    protected void m(Sub classifier) {}\n"+
148
					"}\n" );
149
			// search
150
			IType type = getCompilationUnit("/P/Sub.java").getType("Sub");
151
			IMethod method = type.getMethod("m", new String[]{"QSub;"});
152
			search(method, REFERENCES, EXACT_RULE, SearchEngine.createWorkspaceScope(), this.resultCollector);
153
			assertSearchResults("");
154
			
155
		} finally {
156
			deleteProject(project);
157
		}
158
	}
159
	// another variant of the testcase
160
	public void testBug123836c() throws CoreException {
161
		IJavaProject project = null;
162
		try
163
		{
164
			// create the common project and create an interface
165
			project = createJavaProject("P", new String[] {""}, new String[] {"JCL15_LIB"}, "","1.5");	
166
			createFile("/P/Test.java", 
167
				"class Test {\n"+
168
				"    void calc(Property prop, Property<? extends Serializable> p2) {\n"+
169
				"        prop.compute(null);\n"+
170
				"        p2.compute(null);\n"+
171
				"    }\n"+
172
				"}\n"+
173
				"abstract class Property<E> {\n"+
174
				"    public abstract void compute(E e);\n"+
175
				"}\n"+
176
				"class StringProperty extends Property<String> {\n"+
177
				"    @Override public void compute(String e) {\n"+
178
				"        System.out.println(e);\n"+
179
				"    }");
180
			IType type = getCompilationUnit("/P/Test.java").getType("StringProperty");
181
			IMethod method = type.getMethod("compute", new String[]{"QString;"});
182
			search(method, REFERENCES, EXACT_RULE, SearchEngine.createWorkspaceScope(), this.resultCollector);
183
			assertSearchResults("Test.java void Test.calc(Property, Property<? extends Serializable>) [compute(null)] EXACT_MATCH\n" + 
184
								"Test.java void Test.calc(Property, Property<? extends Serializable>) [compute(null)] EXACT_MATCH");
185
		} finally {
186
			deleteProject(project);
187
		}
188
	}
189
	// Test inner class
190
	public void testBug123836d() throws CoreException {
191
		IJavaProject project = null;
192
		try
193
		{
194
			// create the common project and create an interface
195
			project = createJavaProject("P", new String[] {""}, new String[] {"JCL15_LIB"}, "","1.5");	
196
			createFile("/P/Test.java", 
197
				"class Test {\n"+
198
				"    void calc(Property prop, Property<? extends Serializable> p2) {\n"+
199
				"        prop.compute(null);\n"+
200
				"        p2.compute(null);\n"+
201
				"    }\n"+
202
				"	class StringProperty extends Property<String> {\n"+
203
				"    @Override public void compute(String e) {\n"+
204
				"        System.out.println(e);\n"+
205
				"    }\n"+
206
				"}\n"+
207
				"abstract class Property<E> {\n"+
208
				"    public abstract void compute(E e);\n"+
209
				"}");
210
				
211
			IType type = getCompilationUnit("/P/Test.java").getType("Test").getType("StringProperty");
212
			IMethod method = type.getMethod("compute", new String[]{"QString;"});
213
			search(method, REFERENCES, EXACT_RULE, SearchEngine.createWorkspaceScope(), this.resultCollector);
214
			assertSearchResults("Test.java void Test.calc(Property, Property<? extends Serializable>) [compute(null)] EXACT_MATCH\n" + 
215
								"Test.java void Test.calc(Property, Property<? extends Serializable>) [compute(null)] EXACT_MATCH");
216
		} finally {
217
			deleteProject(project);
218
		}
219
	}
220
	// Test local class
221
	public void testBug123836e() throws CoreException {
222
		IJavaProject project = null;
223
		try
224
		{
225
			// create the common project and create an interface
226
			project = createJavaProject("P", new String[] {""}, new String[] {"JCL15_LIB"}, "","1.5");	
227
			createFile("/P/Test.java", 
228
				"class Test {\n"+
229
				"    void calc(Property prop, Property<? extends Serializable> p2) {\n"+
230
				"        prop.compute(null);\n"+
231
				"        p2.compute(null);\n"+
232
				"		class StringProperty extends Property<String> {\n"+
233
				"   		@Override public void compute(String e) {\n"+
234
				"        		System.out.println(e);\n"+
235
				"    		}\n"+
236
				"		}\n"+
237
				"    }\n"+
238
				"}\n"+
239
				"abstract class Property<E> {\n"+
240
				"    public abstract void compute(E e);\n"+
241
				"}");
242
			IMethod method = selectMethod(getCompilationUnit("/P/Test.java"), "compute", 3);
243
			search(method, REFERENCES, EXACT_RULE, SearchEngine.createWorkspaceScope(), this.resultCollector);
244
			assertSearchResults("Test.java void Test.calc(Property, Property<? extends Serializable>) [compute(null)] EXACT_MATCH\n" + 
245
								"Test.java void Test.calc(Property, Property<? extends Serializable>) [compute(null)] EXACT_MATCH");
246
		} finally {
247
			deleteProject(project);
248
		}
249
	}
250
	// test inner class
251
	public void testBug123836f() throws CoreException {
252
		IJavaProject project = null;
253
		try
254
		{
255
			// create the common project and create an interface
256
			project = createJavaProject("P", new String[] {""}, new String[] {"JCL15_LIB"}, "","1.5");	
257
			createFile("/P/Test.java", 
258
				"class Test {\n"+
259
				"    void calc(Property prop, Property<? extends Serializable> p2) {\n"+
260
				"        prop.compute(null);\n"+
261
				"        p2.compute(null);\n"+
262
				"		 new Property<String>() {\n"+
263
				"   		@Override public void compute(String e) {\n"+
264
				"        		System.out.println(e);\n"+
265
				"    		}\n"+
266
				"		};\n"+
267
				"    }\n"+
268
				"}\n"+
269
				"abstract class Property<E> {\n"+
270
				"    public abstract void compute(E e);\n"+
271
				"}");
272
			IMethod method = selectMethod(getCompilationUnit("/P/Test.java"), "compute", 3);
273
			search(method, REFERENCES, EXACT_RULE, SearchEngine.createWorkspaceScope(), this.resultCollector);
274
			assertSearchResults("Test.java void Test.calc(Property, Property<? extends Serializable>) [compute(null)] EXACT_MATCH\n" + 
275
								"Test.java void Test.calc(Property, Property<? extends Serializable>) [compute(null)] EXACT_MATCH");
276
		} finally {
277
			deleteProject(project);
278
		}
279
	}
280
	// test in initializer block
281
	public void testBug123836g() throws CoreException {
282
		IJavaProject project = null;
283
		try
284
		{
285
			// create the common project and create an interface
286
			project = createJavaProject("P", new String[] {""}, new String[] {"JCL15_LIB"}, "","1.5");	
287
			createFile("/P/Test.java", 
288
				"class Test {\n"+
289
				"	{\n" +
290
				"		new Property<String>() {\n" +
291
				"			@Override public void compute(String e) {}\n" +
292
				"		};\n"+
293
				"	 }\n"+
294
				"	void calc(Property prop, Property<? extends Serializable> p2) {\n"+
295
				"		prop.compute(null);\n"+
296
				"		p2.compute(null);\n"+
297
				"	}\n"+
298
				"}\n"+
299
				"abstract class Property<E> {\n"+
300
				"	public abstract void compute(E e);\n"+
301
				"}");
302
			IMethod method = selectMethod(getCompilationUnit("/P/Test.java"), "compute", 1);
303
			search(method, REFERENCES, EXACT_RULE, SearchEngine.createWorkspaceScope(), this.resultCollector);
304
			assertSearchResults("Test.java void Test.calc(Property, Property<? extends Serializable>) [compute(null)] EXACT_MATCH\n" + 
305
								"Test.java void Test.calc(Property, Property<? extends Serializable>) [compute(null)] EXACT_MATCH");
306
		} finally {
307
			deleteProject(project);
308
		}
309
	}
310
	// test in static initializer
311
	public void testBug123836h() throws CoreException {
312
		IJavaProject project = null;
313
		try
314
		{
315
			// create the common project and create an interface
316
			project = createJavaProject("P", new String[] {""}, new String[] {"JCL15_LIB"}, "","1.5");	
317
			createFile("/P/Test.java", 
318
				"class Test {\n"+
319
				"	static {\n" +
320
				"		new Property<String>() {\n" +
321
				"			@Override public void compute(String e) {}\n" +
322
				"		};\n"+
323
				"	 }\n"+
324
				"	void calc(Property prop, Property<? extends Serializable> p2) {\n"+
325
				"		prop.compute(null);\n"+
326
				"		p2.compute(null);\n"+
327
				"	}\n"+
328
				"}\n"+
329
				"abstract class Property<E> {\n"+
330
				"	public abstract void compute(E e);\n"+
331
				"}");
332
			IMethod method = selectMethod(getCompilationUnit("/P/Test.java"), "compute", 1);
333
			search(method, REFERENCES, EXACT_RULE, SearchEngine.createWorkspaceScope(), this.resultCollector);
334
			assertSearchResults("Test.java void Test.calc(Property, Property<? extends Serializable>) [compute(null)] EXACT_MATCH\n" + 
335
								"Test.java void Test.calc(Property, Property<? extends Serializable>) [compute(null)] EXACT_MATCH");
336
		} finally {
337
			deleteProject(project);
338
		}
339
	}
340
	// test in static initializer
341
	public void testBug123836i() throws CoreException {
342
		IJavaProject project = null;
343
		try
344
		{
345
			// create the common project and create an interface
346
			project = createJavaProject("P", new String[] {""}, new String[] {"JCL15_LIB"}, "","1.5");	
347
			createFile("/P/Test.java", 
348
				"class Test {\n"+
349
				"	Property <?>p = new Property<String>() {\n" +
350
				"			@Override public void compute(String e) {}\n" +
351
				"		};\n"+
352
				"	void calc(Property prop, Property<? extends Serializable> p2) {\n"+
353
				"		prop.compute(null);\n"+
354
				"		p2.compute(null);\n"+
355
				"	}\n"+
356
				"}\n"+
357
				"abstract class Property<E> {\n"+
358
				"	public abstract void compute(E e);\n"+
359
				"}");
360
			IMethod method = selectMethod(getCompilationUnit("/P/Test.java"), "compute", 1);
361
			search(method, REFERENCES, EXACT_RULE, SearchEngine.createWorkspaceScope(), this.resultCollector);
362
			assertSearchResults("Test.java void Test.calc(Property, Property<? extends Serializable>) [compute(null)] EXACT_MATCH\n" + 
363
								"Test.java void Test.calc(Property, Property<? extends Serializable>) [compute(null)] EXACT_MATCH");
364
		} finally {
365
			deleteProject(project);
366
		}
367
	}
368
	public void testBug123836j() throws CoreException {
369
		IJavaProject project = null;
370
		try
371
		{
372
			// create the common project and create an interface
373
			project = createJavaProject("P", new String[] {""}, new String[] {"JCL15_LIB"}, "","1.5");	
374
			createFile("/P/Test.java", 
375
				"class Test {\n"+
376
				"    void calc(Property prop, Property<? extends Serializable> p2) {\n"+
377
				"        prop.compute(null);\n"+
378
				"        p2.compute(null);\n"+
379
				"    }\n"+
380
				"}\n"+
381
				"abstract class Property<E> {\n"+
382
				"    public abstract void compute(E e);\n"+
383
				"}\n"+
384
				"class StringProperty extends Property<String> {\n"+
385
				"	@Override public void compute(String e) {\n"+
386
				"		 new Property<String>() {\n"+
387
				"			@Override public void compute(String e) {\n"+
388
				"				new Property<String>() {\n"+
389
				"					@Override public void compute(String e) {}\n"+
390
				"				};\n"+
391
				"			}\n"+
392
				"		};\n"+
393
				"	}\n"+
394
				"}");
395
			IMethod method = selectMethod(getCompilationUnit("/P/Test.java"), "compute", 6);
396
			search(method, REFERENCES, EXACT_RULE, SearchEngine.createWorkspaceScope(), this.resultCollector);
397
			assertSearchResults("Test.java void Test.calc(Property, Property<? extends Serializable>) [compute(null)] EXACT_MATCH\n" + 
398
								"Test.java void Test.calc(Property, Property<? extends Serializable>) [compute(null)] EXACT_MATCH");
399
		} finally {
400
			deleteProject(project);
401
		}
402
	}
403
	// test search of name
404
	public void _testBug123836g1() throws CoreException {
405
		IJavaProject project = null;
406
		try
407
		{
408
			// create the common project and create an interface
409
			project = createJavaProject("P", new String[] {""}, new String[] {"JCL15_LIB"}, "","1.5");	
410
			createFile("/P/Sub.java", 
411
					"abstract class Sup<C> {\n" +
412
					"    protected void m(C classifier) {}\n"+
413
					"    public void use(C owner) { m (owner); }\n" +
414
					"}\n" +
415
					"public class Sub extends Sup<String>{\n" +
416
					"    @Override\n"+
417
					"    protected void m(String classifier) {}\n"+
418
					"    protected void m(Sub classifier) {}\n"+
419
					"}\n" );
420
			waitUntilIndexesReady();
421
			// search
422
			SearchPattern pattern = SearchPattern.createPattern("Sub.m(String)", METHOD, REFERENCES, EXACT_RULE);
423
			search(pattern, SearchEngine.createWorkspaceScope(), this.resultCollector);
424
			assertSearchResults("Sub.java void Sup.use(C) [m (owner)] EXACT_MATCH");
425
			
426
		} finally {
427
			deleteProject(project);
428
		}
429
	}
430
	// test search of name (negative)
431
	public void _testBug123836h1() throws CoreException {
432
		IJavaProject project = null;
433
		try
434
		{
435
			// create the common project and create an interface
436
			project = createJavaProject("P", new String[] {""}, new String[] {"JCL15_LIB"}, "","1.5");	
437
			createFile("/P/Sub.java", 
438
					"abstract class Sup<C> {\n" +
439
					"    protected void m(C classifier) {}\n"+
440
					"    public void use(C owner) { m (owner); }\n" +
441
					"}\n" +
442
					"public class Sub extends Sup<String>{\n" +
443
					"    @Override\n"+
444
					"    protected void m(String classifier) {}\n"+
445
					"    protected void m(Sub classifier) {}\n"+
446
					"}\n" );
447
			// search
448
			SearchPattern pattern = SearchPattern.createPattern("Sub.m(Sub)", METHOD, REFERENCES, EXACT_RULE);
449
			search(pattern, SearchEngine.createWorkspaceScope(), this.resultCollector);
450
			assertSearchResults("");
451
			
452
		} finally {
453
			deleteProject(project);
454
		}
455
	}
456
457
	/**
458
	 * @bug 342393: Anonymous class' occurrence count is incorrect when two methods in a class have the same name.
459
	 * @test Search for Enumerators with anonymous types
460
	 *
461
	 * @throws CoreException
462
	 * @see "https://bugs.eclipse.org/bugs/show_bug.cgi?id=342393"
463
	 */
464
	public void testBug342393() throws CoreException {
465
		try {
466
			IJavaProject project = createJavaProject("P", new String[] {""}, new String[] {"JCL15_LIB"}, "bin", "1.5");
467
			String content = "package b342393;\n" + "class Generic {\n"
468
					+ "enum A {\n" + "ONE {\n" + "A getSquare() {\n"
469
					+ "return ONE;\n" + "}\n" + "},\n" + "TWO {\n"
470
					+ "A getSquare() {\n" + "return TWO;\n" + "}\n" + "};\n"
471
					+ "abstract A getSquare();\n" + "}\n" + "}";
472
			createFolder("/P/b342393");
473
			createFile("/P/b342393/Generic.java", content);
474
			IJavaSearchScope scope = SearchEngine. createJavaSearchScope(
475
					new IJavaElement[] { project }, IJavaSearchScope.SOURCES);
476
			search("getSquare", METHOD, DECLARATIONS, EXACT_RULE, scope, this.resultCollector);
477
			assertSearchResults("b342393/Generic.java A b342393.Generic$A.ONE:<anonymous>#1.getSquare() [getSquare] EXACT_MATCH\n" + 
478
					"b342393/Generic.java A b342393.Generic$A.TWO:<anonymous>#1.getSquare() [getSquare] EXACT_MATCH\n" + 
479
					"b342393/Generic.java A b342393.Generic$A.getSquare() [getSquare] EXACT_MATCH");
480
		} finally {
481
			deleteProject("P");
482
		}
483
	}
484
}
(-)a/org.eclipse.jdt.core.tests.model/src/org/eclipse/jdt/core/tests/model/JavaSearchScopeTests.java (-2 / +2 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 1025-1031 Link Here
1025
1025
1026
		// Index the output location as it is a library for the project
1026
		// Index the output location as it is a library for the project
1027
		IndexManager indexManager = JavaModelManager.getIndexManager();
1027
		IndexManager indexManager = JavaModelManager.getIndexManager();
1028
		indexManager.indexLibrary(new Path("/P1/bin"), project.getProject());
1028
		indexManager.indexLibrary(new Path("/P1/bin"), project.getProject(), null);
1029
		waitUntilIndexesReady();
1029
		waitUntilIndexesReady();
1030
1030
1031
		// Search for all types
1031
		// Search for all types
(-)a/org.eclipse.jdt.core.tests.model/src/org/eclipse/jdt/core/tests/model/JavaSearchTests.java (-5 / +5 lines)
Lines 1-5 Link Here
1
/*******************************************************************************
1
/*******************************************************************************
2
 * Copyright (c) 2000, 2010 IBM Corporation and others.
2
 * Copyright (c) 2000, 2012 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 2168-2175 Link Here
2168
		search("MissingFieldType.*", FIELD, DECLARATIONS,  getJavaSearchScope());
2168
		search("MissingFieldType.*", FIELD, DECLARATIONS,  getJavaSearchScope());
2169
		assertSearchResults(
2169
		assertSearchResults(
2170
			"AbortCompilation.jar AbortCompilation.MissingFieldType.field [No source] EXACT_MATCH\n" +
2170
			"AbortCompilation.jar AbortCompilation.MissingFieldType.field [No source] EXACT_MATCH\n" +
2171
			"AbortCompilation.jar AbortCompilation.MissingFieldType.otherField [No source] EXACT_MATCH\n" +
2171
			"AbortCompilation.jar AbortCompilation.MissingFieldType.missing [No source] EXACT_MATCH\n" +
2172
			"AbortCompilation.jar AbortCompilation.MissingFieldType.missing [No source] POTENTIAL_MATCH"
2172
			"AbortCompilation.jar AbortCompilation.MissingFieldType.otherField [No source] EXACT_MATCH"
2173
		);
2173
		);
2174
	} finally {
2174
	} finally {
2175
		// reset classpath
2175
		// reset classpath
Lines 2229-2236 Link Here
2229
		search("MissingArgumentType.foo*", METHOD, DECLARATIONS, getJavaSearchScope());
2229
		search("MissingArgumentType.foo*", METHOD, DECLARATIONS, getJavaSearchScope());
2230
		assertSearchResults(
2230
		assertSearchResults(
2231
			"AbortCompilation.jar void AbortCompilation.MissingArgumentType.foo() [No source] EXACT_MATCH\n" +
2231
			"AbortCompilation.jar void AbortCompilation.MissingArgumentType.foo() [No source] EXACT_MATCH\n" +
2232
			"AbortCompilation.jar void AbortCompilation.MissingArgumentType.foo2() [No source] EXACT_MATCH\n" +
2232
			"AbortCompilation.jar void AbortCompilation.MissingArgumentType.foo(java.util.EventListener) [No source] EXACT_MATCH\n" +
2233
			"AbortCompilation.jar void AbortCompilation.MissingArgumentType.foo(java.util.EventListener) [No source] POTENTIAL_MATCH"
2233
			"AbortCompilation.jar void AbortCompilation.MissingArgumentType.foo2() [No source] EXACT_MATCH"		
2234
		);
2234
		);
2235
	} finally {
2235
	} finally {
2236
		// reset classpath
2236
		// reset classpath
(-)a/org.eclipse.jdt.core.tests.model/src/org/eclipse/jdt/core/tests/model/NullAnnotationModelTests.java (+489 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.core.tests.model;
12
13
import java.io.File;
14
import java.io.IOException;
15
import java.io.ByteArrayInputStream;
16
import java.net.URL;
17
import java.util.Hashtable;
18
import java.util.List;
19
20
import junit.framework.Test;
21
22
import org.eclipse.core.resources.IFile;
23
import org.eclipse.core.resources.IMarker;
24
import org.eclipse.core.resources.IResource;
25
import org.eclipse.core.resources.IncrementalProjectBuilder;
26
import org.eclipse.core.runtime.CoreException;
27
import org.eclipse.core.runtime.FileLocator;
28
import org.eclipse.core.runtime.Platform;
29
import org.eclipse.jdt.core.ICompilationUnit;
30
import org.eclipse.jdt.core.IJavaModelMarker;
31
import org.eclipse.jdt.core.IJavaProject;
32
import org.eclipse.jdt.core.JavaCore;
33
import org.eclipse.jdt.core.compiler.IProblem;
34
import org.eclipse.jdt.core.dom.AST;
35
import org.eclipse.jdt.core.dom.ASTParser;
36
import org.eclipse.jdt.core.dom.CompilationUnit;
37
import org.eclipse.jdt.core.dom.MarkerAnnotation;
38
import org.eclipse.jdt.core.dom.MethodDeclaration;
39
import org.eclipse.jdt.core.dom.Modifier;
40
import org.eclipse.jdt.core.dom.SingleVariableDeclaration;
41
import org.eclipse.jdt.core.dom.TypeDeclaration;
42
43
public class NullAnnotationModelTests extends ReconcilerTests {
44
45
	String ANNOTATION_LIB;
46
47
	public static Test suite() {
48
		return buildModelTestSuite(NullAnnotationModelTests.class);
49
	}
50
51
	public NullAnnotationModelTests(String name) {
52
		super(name);
53
	}
54
55
	static {
56
//		TESTS_NAMES = new String[] { "testMissingAnnotation5" };
57
	}
58
59
	public void setUp() throws Exception {
60
		super.setUp();
61
		File bundleFile = FileLocator.getBundleFile(Platform.getBundle("org.eclipse.jdt.annotation"));
62
		this.ANNOTATION_LIB = bundleFile.isDirectory() ? bundleFile.getPath()+"/bin" : bundleFile.getPath();
63
	}
64
65
	protected String testJarPath(String jarName) throws IOException {
66
		URL libEntry = Platform.getBundle("org.eclipse.jdt.core.tests.model").getEntry("/workspace/NullAnnotations/lib/"+jarName);
67
		return FileLocator.toFileURL(libEntry).getPath();
68
	}
69
70
	// DISABLED due to dysfunctional global default after Bug 366063 - Compiler should not add synthetic @NonNull annotations
71
	public void _testConvertedSourceType1() throws CoreException, InterruptedException {
72
    	try {
73
			// Resources creation
74
			IJavaProject p = createJavaProject("P", new String[] {""}, new String[] {"JCL15_LIB", this.ANNOTATION_LIB}, "bin", "1.5");
75
			p.setOption(JavaCore.COMPILER_ANNOTATION_NULL_ANALYSIS, JavaCore.ENABLED);
76
			p.setOption(JavaCore.COMPILER_NONNULL_IS_DEFAULT, JavaCore.ENABLED);
77
78
			this.createFolder("/P/p1");
79
			String c1SourceString =
80
				"package p1;\n" +
81
				"import org.eclipse.jdt.annotation.*;\n" +
82
				"public class C1 {\n" +
83
				"	 public String foo(@Nullable Object arg) {\n" + // this is consumed via SourceTypeConverter
84
				"		return arg == null ? \"\" : arg.toString();\n" +
85
				"	 }\n" +
86
				"}\n";
87
			this.createFile(
88
				"/P/p1/C1.java",
89
	    			c1SourceString);
90
91
			this.createFolder("/P/p2");
92
			String c2SourceString =
93
				"package p2;\n" +
94
				"public class C2 {\n" +
95
				"	 String bar(p1.C1 c, C2 c2) {;\n" +
96
				"        return c.foo(null);\n" + // don't complain despite default nonnull, foo has explicit @Nullable
97
				"    }\n" +
98
				"	 String foo(Object arg) {\n" +
99
				"		return arg == null ? null : arg.toString();\n" +
100
				"	 }\n" +
101
				"}\n";
102
			this.createFile(
103
				"/P/p2/C2.java",
104
	    			c2SourceString);
105
106
			char[] c2SourceChars = c2SourceString.toCharArray();
107
			this.problemRequestor.initialize(c2SourceChars);
108
109
			getCompilationUnit("/P/p2/C2.java").getWorkingCopy(this.wcOwner, null);
110
111
			assertProblems("Unexpected problems", "----------\n" +
112
					"1. WARNING in /P/p2/C2.java (at line 7)\n" +
113
					"	return arg == null ? null : arg.toString();\n" +
114
					"	       ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^\n" +
115
					"Potential type mismatch: required \'@NonNull String\' but nullness of the provided value is unknown\n" +
116
					"----------\n");
117
    	} finally {
118
    		deleteProject("P");
119
    	}
120
    }
121
122
	// DISABLED due to dysfunctional global default after Bug 366063 - Compiler should not add synthetic @NonNull annotations
123
	public void _testBinaryType1() throws CoreException, InterruptedException, IOException {
124
    	try {
125
			// Resources creation
126
			IJavaProject p = createJavaProject("P", new String[] {""},
127
											   new String[] {"JCL15_LIB", this.ANNOTATION_LIB, testJarPath("example.jar")},
128
											   "bin", "1.5");
129
			p.setOption(JavaCore.COMPILER_ANNOTATION_NULL_ANALYSIS, JavaCore.ENABLED);
130
			p.setOption(JavaCore.COMPILER_NONNULL_IS_DEFAULT, JavaCore.ENABLED);
131
132
			// example.jar contains p1/C1.java just like testConvertedSourceType1()
133
134
			this.createFolder("/P/p2");
135
			String c2SourceString =
136
				"package p2;\n" +
137
				"public class C2 {\n" +
138
				"	 String bar(p1.C1 c) {;\n" +
139
				"        return c.foo(null);\n" + // don't complain despite default nonnull, foo has explicit @Nullable
140
				"    }\n" +
141
				"	 String foo(Object arg) {\n" +
142
				"		return arg == null ? null : arg.toString();\n" +
143
				"	 }\n" +
144
				"}\n";
145
			this.createFile(
146
				"/P/p2/C2.java",
147
	    			c2SourceString);
148
149
			char[] c2SourceChars = c2SourceString.toCharArray();
150
			this.problemRequestor.initialize(c2SourceChars);
151
152
			getCompilationUnit("/P/p2/C2.java").getWorkingCopy(this.wcOwner, null);
153
154
			assertProblems("Unexpected problems", "----------\n" +
155
					"1. WARNING in /P/p2/C2.java (at line 7)\n" +
156
					"	return arg == null ? null : arg.toString();\n" +
157
					"	       ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^\n" +
158
					"Potential type mismatch: required \'@NonNull String\' but nullness of the provided value is unknown\n" +
159
					"----------\n");
160
    	} finally {
161
    		deleteProject("P");
162
    	}
163
    }
164
165
	// DISABLED: no longer a problem since bug 365531 - [compiler][null] investigate alternative strategy for internally encoding nullness defaults
166
	public void _testMissingAnnotation1() throws CoreException {
167
    	try {
168
			// Resources creation
169
			IJavaProject p = createJavaProject("P", new String[] {""}, new String[] {"JCL15_LIB", this.ANNOTATION_LIB}, "bin", "1.5");
170
			p.setOption(JavaCore.COMPILER_ANNOTATION_NULL_ANALYSIS, JavaCore.ENABLED);
171
			p.setOption(JavaCore.COMPILER_NONNULL_ANNOTATION_NAME, "in.valid");
172
173
			this.createFolder("/P/p1");
174
			String c1SourceString =
175
				"package p1;\n" +
176
				"@org.eclipse.jdt.annotation.NonNullByDefault\n" +
177
				"public class C1 {\n" +
178
				"	 public String foo(Object arg) {\n" +
179
				"		return arg == null ? \"\" : arg.toString();\n" +
180
				"	 }\n" +
181
				"}\n";
182
			this.createFile(
183
				"/P/p1/C1.java",
184
	    			c1SourceString);
185
186
			this.problemRequestor.initialize(c1SourceString.toCharArray());
187
188
			getCompilationUnit("/P/p1/C1.java").getWorkingCopy(this.wcOwner, null);
189
190
			assertProblems("Unexpected problems",
191
					"----------\n" +
192
					"1. ERROR in /P/p1/C1.java (at line 1)\n" +
193
					"	package p1;\n" +
194
					"	^\n" +
195
					"Buildpath problem: the type in.valid, which is configured as a null annotation type, cannot be resolved\n" +
196
					"----------\n");
197
    	} finally {
198
    		deleteProject("P");
199
    	}
200
	}
201
202
	// DISABLED: no longer a problem since bug 365531 - [compiler][null] investigate alternative strategy for internally encoding nullness defaults
203
	public void _testMissingAnnotation2() throws CoreException {
204
		Hashtable javaOptions = JavaCore.getOptions();
205
    	try {
206
			// Resources creation
207
			IJavaProject p = createJavaProject("P", new String[] {""}, new String[] {"JCL15_LIB", this.ANNOTATION_LIB}, "bin", "1.5");
208
			IFile settings = (IFile) p.getProject().findMember(".settings/org.eclipse.jdt.core.prefs");
209
			settings.appendContents(new ByteArrayInputStream("\norg.eclipse.jdt.core.compiler.annotation.nonnull=not.valid\n".getBytes()), 0, null);
210
			p.setOption(JavaCore.COMPILER_ANNOTATION_NULL_ANALYSIS, JavaCore.ENABLED);
211
212
			this.createFolder("/P/p1");
213
			String c1SourceString =
214
				"package p1;\n" +
215
				"@org.eclipse.jdt.annotation.NonNullByDefault\n" +
216
				"public class C1 {\n" +
217
				"	 public String foo(Object arg) {\n" +
218
				"		return arg == null ? \"\" : arg.toString();\n" +
219
				"	 }\n" +
220
				"}\n";
221
			this.createFile(
222
				"/P/p1/C1.java",
223
	    			c1SourceString);
224
225
			this.problemRequestor.initialize(c1SourceString.toCharArray());
226
227
			getCompilationUnit("/P/p1/C1.java").getWorkingCopy(this.wcOwner, null);
228
229
			assertProblems("Unexpected problems",
230
					"----------\n" +
231
					"1. ERROR in /P/p1/C1.java (at line 1)\n" +
232
					"	package p1;\n" +
233
					"	^\n" +
234
					"Buildpath problem: the type not.valid, which is configured as a null annotation type, cannot be resolved\n" +
235
					"----------\n");
236
    	} finally {
237
    		deleteProject("P");
238
    		JavaCore.setOptions(javaOptions);
239
    		// work against side-effect of JavaRuntime listening to change of prefs-file.
240
    		// see https://bugs.eclipse.org/bugs/show_bug.cgi?id=302850#c25
241
    	}
242
	}
243
244
	// Bug 363858 - [dom] early throwing of AbortCompilation causes NPE in CompilationUnitResolver
245
	// currently not actually challenging the NPE, because we no longer report
246
	// "Cannot use the unqualified name \'invalid\' as an annotation name for null specification"
247
	// DISABLED: no longer a problem since bug 365531 - [compiler][null] investigate alternative strategy for internally encoding nullness defaults
248
	public void _testMissingAnnotation3() throws CoreException {
249
    	try {
250
			// Resources creation
251
			IJavaProject p = createJavaProject("P", new String[] {""}, new String[] {"JCL15_LIB", this.ANNOTATION_LIB}, "bin", "1.5");
252
			p.setOption(JavaCore.COMPILER_ANNOTATION_NULL_ANALYSIS, JavaCore.ENABLED);
253
			p.setOption(JavaCore.COMPILER_NONNULL_ANNOTATION_NAME, "invalid");
254
255
			this.createFolder("/P/p1");
256
			String c1SourceString =
257
				"package p1;\n" +
258
				"@org.eclipse.jdt.annotation.NonNullByDefault\n" +
259
				"public class C1 {\n" +
260
				"	 public String foo(Object arg) {\n" +
261
				"		return arg == null ? \"\" : arg.toString();\n" +
262
				"	 }\n" +
263
				"}\n";
264
			this.createFile(
265
				"/P/p1/C1.java",
266
	    			c1SourceString);
267
268
			this.problemRequestor.initialize(c1SourceString.toCharArray());
269
270
			final ICompilationUnit unit = getCompilationUnit("/P/p1/C1.java").getWorkingCopy(this.wcOwner, null);
271
			assertProblems("Unexpected problems",
272
					"----------\n" +
273
					"1. ERROR in /P/p1/C1.java (at line 1)\n" +
274
					"	package p1;\n" +
275
					"	^\n" +
276
					"Buildpath problem: the type invalid, which is configured as a null annotation type, cannot be resolved\n" +
277
					"----------\n");
278
279
			ASTParser parser = ASTParser.newParser(AST.JLS4);
280
			parser.setProject(p);
281
			parser.setResolveBindings(true);
282
			parser.setSource(unit);
283
			CompilationUnit ast = (CompilationUnit) parser.createAST(null);
284
			assertNotNull("ast should not be null", ast);
285
			this.problemRequestor.reset();
286
			this.problemRequestor.beginReporting();
287
			IProblem[] problems = ast.getProblems();
288
			for (int i=0; i<problems.length; i++)
289
				this.problemRequestor.acceptProblem(problems[i]);
290
			assertProblems("Unexpected problems (2)",
291
					"----------\n" +
292
					"1. ERROR in /P/p1/C1.java (at line 1)\n" +
293
					"	package p1;\n" +
294
					"	^\n" +
295
					"Buildpath problem: the type invalid, which is configured as a null annotation type, cannot be resolved\n" +
296
					"----------\n");
297
    	} finally {
298
    		deleteProject("P");
299
    	}
300
	}
301
302
	// initialization of null annotations is triggered from package-info.java: illegal simple name
303
	public void testMissingAnnotation4() throws CoreException, InterruptedException {
304
    	try {
305
			// Resources creation
306
			IJavaProject p = createJavaProject("P", new String[] {""}, new String[] {"JCL15_LIB", this.ANNOTATION_LIB}, "bin", "1.5");
307
			p.setOption(JavaCore.COMPILER_ANNOTATION_NULL_ANALYSIS, JavaCore.ENABLED);
308
			p.setOption(JavaCore.COMPILER_NONNULL_ANNOTATION_NAME, "invalid");
309
310
			this.createFolder("/P/p1");
311
			String piSourceString =
312
				"@org.eclipse.jdt.annotation.NonNullByDefault\n" +
313
				"package p1;\n";
314
			this.createFile(
315
				"/P/p1/package-info.java",
316
	    			piSourceString);
317
318
			this.problemRequestor.initialize(piSourceString.toCharArray());
319
320
			// Challenge CompilationUnitProblemFinder:
321
			final ICompilationUnit unit = getCompilationUnit("/P/p1/package-info.java").getWorkingCopy(this.wcOwner, null);
322
// This error is not raised currently:
323
//			String expectedError = "----------\n" +
324
//								   "1. ERROR in /P/p1/package-info.java (at line 0)\n" +
325
//								   "	@org.eclipse.jdt.annotation.NonNullByDefault\n" +
326
//								   "	^\n" +
327
//								   "Cannot use the unqualified name \'invalid\' as an annotation name for null specification\n" +
328
//								   "----------\n";
329
//			assertProblems("Unexpected problems from CompilationUnitProblemFinder", expectedError);
330
			assertNoProblem(unit.getBuffer().getCharacters(), unit);
331
332
			// Challenge JavaBuilder:
333
			p.getProject().build(IncrementalProjectBuilder.FULL_BUILD, null);
334
			IMarker[] markers = p.getProject().findMarkers(IJavaModelMarker.JAVA_MODEL_PROBLEM_MARKER, true, IResource.DEPTH_INFINITE);
335
//			assertMarkers("Unexpected markers",
336
//					"Cannot use the unqualified name 'invalid' as an annotation name for null specification",
337
//					markers);
338
//			assertEquals("Unexpected marker path", "/P", markers[0].getResource().getFullPath().toString());
339
			assertEquals("Should have no markers", 0, markers.length);
340
341
			// Challenge CompilationUnitResolver:
342
			ASTParser parser = ASTParser.newParser(AST.JLS4);
343
			parser.setProject(p);
344
			parser.setResolveBindings(true);
345
			parser.setSource(unit);
346
			CompilationUnit ast = (CompilationUnit) parser.createAST(null);
347
			assertNotNull("ast should not be null", ast);
348
//			this.problemRequestor.reset();
349
//			this.problemRequestor.beginReporting();
350
//			IProblem[] problems = ast.getProblems();
351
//			for (int i=0; i<problems.length; i++)
352
//				this.problemRequestor.acceptProblem(problems[i]);
353
//			assertProblems("Unexpected problems from CompilationUnitResolver", expectedError);
354
			assertEquals("Should have no problems", 0, ast.getProblems().length);
355
    	} finally {
356
    		deleteProject("P");
357
    	}
358
	}
359
360
	// initialization of null annotations is
361
	// - triggered from resolveTypesFor(MethodBinding)
362
	// - default is defined in package-info.java:
363
	// must detect missing non-null annotation and report against the project
364
	// DISABLED: no longer a problem since bug 365531 - [compiler][null] investigate alternative strategy for internally encoding nullness defaults
365
	public void _testMissingAnnotation5() throws CoreException, InterruptedException {
366
    	try {
367
			// Resources creation
368
			IJavaProject p = createJavaProject("P", new String[] {""}, new String[] {"JCL15_LIB", this.ANNOTATION_LIB}, "bin", "1.5");
369
			p.setOption(JavaCore.COMPILER_ANNOTATION_NULL_ANALYSIS, JavaCore.ENABLED);
370
			p.setOption(JavaCore.COMPILER_NONNULL_ANNOTATION_NAME, "pack.Missing");
371
372
			this.createFolder("/P/p1");
373
			String piSourceString =
374
				"@org.eclipse.jdt.annotation.NonNullByDefault\n" +
375
				"package p1;\n";
376
			this.createFile("/P/p1/package-info.java", piSourceString);
377
378
			String c1SourceString =
379
				"package p1;\n" +
380
				"public class C1 {\n" +
381
				"    String foo(String arg) { return arg; }\n" +
382
				"}\n";
383
			this.createFile("/P/p1/C1.java", c1SourceString);
384
385
			this.problemRequestor.initialize(piSourceString.toCharArray());
386
387
			// Challenge CompilationUnitProblemFinder:
388
			assertNoProblem(piSourceString.toCharArray(), getCompilationUnit("/P/p1/package-info.java"));
389
390
			this.problemRequestor.initialize(c1SourceString.toCharArray());
391
392
			// Challenge CompilationUnitProblemFinder:
393
			ICompilationUnit unit = getCompilationUnit("/P/p1/C1.java").getWorkingCopy(this.wcOwner, null);
394
			String expectedError = "----------\n" +
395
								   "1. ERROR in /P/p1/C1.java (at line 1)\n" +
396
								   "	package p1;\n" +
397
								   "	^\n" +
398
								   "Buildpath problem: the type pack.Missing, which is configured as a null annotation type, cannot be resolved\n" +
399
								   "----------\n";
400
			assertProblems("Unexpected problems", expectedError);
401
402
			// Challenge JavaBuilder:
403
			p.getProject().build(IncrementalProjectBuilder.FULL_BUILD, null);
404
			IMarker[] markers = p.getProject().findMarkers(IJavaModelMarker.JAVA_MODEL_PROBLEM_MARKER, true, IResource.DEPTH_INFINITE);
405
			assertMarkers("Unexpected markers",
406
					"Buildpath problem: the type pack.Missing, which is configured as a null annotation type, cannot be resolved",
407
					markers);
408
// toggle expectation depending on how CAT_BUILDPATH problems are reported (see AbstractImageBuilder.storeProblemsFor(..))
409
//			assertEquals("Unexpected marker path", "/P", markers[0].getResource().getFullPath().toString());
410
			assertEquals("Unexpected marker path", "/P/p1/C1.java", markers[0].getResource().getFullPath().toString());
411
412
			// Challenge CompilationUnitResolver:
413
			ASTParser parser = ASTParser.newParser(AST.JLS4);
414
			parser.setProject(p);
415
			parser.setResolveBindings(true);
416
			parser.setSource(unit);
417
			CompilationUnit ast = (CompilationUnit) parser.createAST(null);
418
			assertNotNull("ast should not be null", ast);
419
			this.problemRequestor.reset();
420
			this.problemRequestor.beginReporting();
421
			IProblem[] problems = ast.getProblems();
422
			for (int i=0; i<problems.length; i++)
423
				this.problemRequestor.acceptProblem(problems[i]);
424
			assertProblems("Unexpected problems (2)", expectedError);
425
    	} finally {
426
    		deleteProject("P");
427
    	}
428
	}
429
430
	// A synthetic annotation from a default should not be converted to DOM AST
431
	public void testAnnotationAST1() throws CoreException, InterruptedException {
432
    	try {
433
			// Resources creation
434
			IJavaProject p = createJavaProject("P", new String[] {""}, new String[] {"JCL15_LIB", this.ANNOTATION_LIB}, "bin", "1.5");
435
			p.setOption(JavaCore.COMPILER_ANNOTATION_NULL_ANALYSIS, JavaCore.ENABLED);
436
437
			this.createFolder("/P/p1");
438
			// bug could only be triggered if ASTConvert actually finds a '@'
439
			// so in addition to the synthetic annotation there must also be a real one:
440
			String annotSourceString =
441
				"package p1;\n" +
442
				"import java.lang.annotation.ElementType;\n" + 
443
				"import java.lang.annotation.Target;\n" + 
444
				"@Target({ElementType.PARAMETER,ElementType.METHOD})\n" +
445
				"public @interface Annot {}\n";
446
			this.createFile(
447
				"/P/p1/Annot.java",
448
	    			annotSourceString);
449
			String c1SourceString =
450
				"package p1;\n" +
451
				"@org.eclipse.jdt.annotation.NonNullByDefault\n" +
452
				"public class C1 {\n" +
453
				"	 public @Annot Object foo(@Annot Object arg) {\n" +
454
				"         return this;\n" +
455
				"	 }\n" +
456
				"}\n";
457
			this.createFile(
458
				"/P/p1/C1.java",
459
	    			c1SourceString);
460
461
			this.problemRequestor.initialize(c1SourceString.toCharArray());
462
463
			final ICompilationUnit unit = getCompilationUnit("/P/p1/C1.java").getWorkingCopy(this.wcOwner, null);
464
			assertNoProblem(c1SourceString.toCharArray(), unit);
465
466
			ASTParser parser = ASTParser.newParser(AST.JLS4);
467
			parser.setProject(p);
468
			parser.setResolveBindings(true);
469
			parser.setSource(unit);
470
			CompilationUnit ast = (CompilationUnit) parser.createAST(null);
471
			assertNotNull("ast should not be null", ast);
472
			TypeDeclaration type = (TypeDeclaration) ast.types().get(0);
473
			assertNotNull("type should not be null", type);
474
			MethodDeclaration method = (MethodDeclaration) type.bodyDeclarations().get(0);
475
			assertNotNull("method should not be null", method);
476
			SingleVariableDeclaration arg = (SingleVariableDeclaration) method.parameters().get(0);
477
			assertNotNull("argument should not be null", arg);
478
			List modifiers = arg.modifiers();
479
			assertEquals("Should have exactly one modifier", 1, modifiers.size());
480
			assertEquals("Unexpected modifier", "@Annot", ((MarkerAnnotation)modifiers.get(0)).toString());
481
			modifiers = method.modifiers();
482
			assertEquals("Method should have exactly two modifiers", 2, modifiers.size());
483
			assertEquals("Unexpected modifier #1 for method", "public", ((Modifier)modifiers.get(0)).toString());
484
			assertEquals("Unexpected modifier #2 for method", "@Annot", ((MarkerAnnotation)modifiers.get(1)).toString());
485
    	} finally {
486
    		deleteProject("P");
487
    	}
488
	}
489
}
(-)a/org.eclipse.jdt.core.tests.model/src/org/eclipse/jdt/core/tests/model/RenameTests.java (-7 / +8 lines)
Lines 115-123 Link Here
115
			assertTrue("moved from handle should be original", destDelta.getMovedFromElement().equals(e.getParent()));
115
			assertTrue("moved from handle should be original", destDelta.getMovedFromElement().equals(e.getParent()));
116
		} else {
116
		} else {
117
			assertTrue("Destination container not changed", destDelta != null && deltaChildrenChanged(destDelta));
117
			assertTrue("Destination container not changed", destDelta != null && deltaChildrenChanged(destDelta));
118
			IJavaElementDelta[] deltas = destDelta.getAddedChildren();
118
			IJavaElementDelta[] deltas = force ? destDelta.getChangedChildren() : destDelta.getAddedChildren();
119
			assertTrue("Added children not correct for element rename", deltas.length > i && deltas[i].getElement().equals(renamed));
119
			assertTrue("Added children not correct for element rename", deltas.length > i && deltas[i].getElement().equals(renamed));
120
			assertTrue("kind should be K_ADDED", deltas[i].getKind() == IJavaElementDelta.ADDED);
120
			assertTrue("kind should be K_ADDED", deltas[i].getKind() == (force? IJavaElementDelta.CHANGED : IJavaElementDelta.ADDED));
121
			deltas = destDelta.getRemovedChildren();
121
			deltas = destDelta.getRemovedChildren();
122
			assertTrue("Removed children not correct for element rename", deltas.length > i && deltas[i].getElement().equals(e));
122
			assertTrue("Removed children not correct for element rename", deltas.length > i && deltas[i].getElement().equals(e));
123
			assertTrue("kind should be K_REMOVED", deltas[i].getKind() == IJavaElementDelta.REMOVED);
123
			assertTrue("kind should be K_REMOVED", deltas[i].getKind() == IJavaElementDelta.REMOVED);
Lines 364-374 Link Here
364
364
365
	assertDeltas(
365
	assertDeltas(
366
		"Unexpected deltas",
366
		"Unexpected deltas",
367
		"P[*]: {CHILDREN}\n" +
367
		"P[*]: {CHILDREN}\n" + 
368
		"	src[*]: {CHILDREN}\n" +
368
				"	src[*]: {CHILDREN}\n" + 
369
		"		<default>[*]: {CHILDREN}\n" +
369
				"		<default>[*]: {CHILDREN}\n" + 
370
		"			X.java[-]: {MOVED_TO(Y.java [in <default> [in src [in P]]])}\n" +
370
				"			X.java[-]: {MOVED_TO(Y.java [in <default> [in src [in P]]])}\n" + 
371
		"			Y.java[+]: {MOVED_FROM(X.java [in <default> [in src [in P]]])}"
371
				"			Y.java[*]: {CHILDREN | FINE GRAINED | PRIMARY RESOURCE}\n" + 
372
				"				Y[+]: {MOVED_FROM(X [in X.java [in <default> [in src [in P]]]])}"
372
	);
373
	);
373
}
374
}
374
/*
375
/*
(-)a/org.eclipse.jdt.core.tests.model/src/org/eclipse/jdt/core/tests/model/ResolveTests.java (-1 / +40 lines)
Lines 1-5 Link Here
1
/*******************************************************************************
1
/*******************************************************************************
2
 * Copyright (c) 2000, 2011 IBM Corporation and others.
2
 * Copyright (c) 2000, 2012 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 2686-2689 Link Here
2686
		);
2686
		);
2687
	assertTrue("Not a parameter", ((ILocalVariable)elements[0]).isParameter());
2687
	assertTrue("Not a parameter", ((ILocalVariable)elements[0]).isParameter());
2688
}
2688
}
2689
// https://bugs.eclipse.org/bugs/show_bug.cgi?id=244544
2690
public void testConstantInLocal() throws JavaModelException {
2691
	this.workingCopies = new ICompilationUnit[2];
2692
	this.workingCopies[0] = getWorkingCopy(
2693
			"/Resolve/src/Test2.java",
2694
			"class X {\n" +
2695
			"    public static void main(String[] args) {\n" +
2696
			"        class Local {\n" +
2697
			"            private static final long CONSTANT = 1L; // code select fails\n" +
2698
			"        }\n" +
2699
			"        new X() {\n" +
2700
			"            private static final long FINAL = 1L; // code select fails\n" +
2701
			"        };\n" +
2702
			"    }\n" +
2703
			"}\n");
2704
2705
	String str = this.workingCopies[0].getSource();
2706
	String selectAt = "FINAL";
2707
	String selection = "FINAL";
2708
	int start = str.indexOf(selectAt);
2709
	int length = selection.length();
2710
	IJavaElement[] elements = this.workingCopies[0].codeSelect(start, length, this.wcOwner);
2711
2712
	assertElementsEqual(
2713
			"Unexpected elements",
2714
			"FINAL [in <anonymous #1> [in main(String[]) [in X [in [Working copy] Test2.java [in <default> [in src [in Resolve]]]]]]]",
2715
			elements);
2716
2717
	selectAt = "CONSTANT";
2718
	selection = "CONSTANT";
2719
	start = str.indexOf(selectAt);
2720
	length = selection.length();
2721
	elements = this.workingCopies[0].codeSelect(start, length, this.wcOwner);
2722
2723
	assertElementsEqual(
2724
			"Unexpected elements",
2725
			"CONSTANT [in Local [in main(String[]) [in X [in [Working copy] Test2.java [in <default> [in src [in Resolve]]]]]]]",
2726
			elements);
2727
}
2689
}
2728
}
(-)a/org.eclipse.jdt.core.tests.model/src/org/eclipse/jdt/core/tests/model/ResolveTests2.java (+44 lines)
Lines 1203-1206 Link Here
1203
		this.deleteProject("P1");
1203
		this.deleteProject("P1");
1204
	}
1204
	}
1205
}
1205
}
1206
public void testBug356325() throws Exception{
1207
	try {
1208
		// create P1
1209
		this.createJavaProject(
1210
			"P1",
1211
			new String[]{"src"},
1212
			new String[]{"JCL15_LIB"},
1213
			 "bin",
1214
			 "1.5");
1215
1216
		this.createFolder("/P1/src/p");
1217
		this.createFile("/P1/src/p/C.java",
1218
				"package p;" + 
1219
				"\n" + 
1220
				"public class C {\n" + 
1221
				"	public void m() {\n" +
1222
				"		class Inner<T> {\n" +
1223
				"			Inner() {\n"+
1224
				"       }\n"+
1225
				"		Inner<String> i = new Inner<String>();\n"+
1226
				"	}\n" +
1227
				"}\n");
1228
		
1229
		waitUntilIndexesReady();
1230
1231
		// do code select
1232
		ICompilationUnit cu= getCompilationUnit("P1", "src", "p", "C.java");
1233
1234
		String str = cu.getSource();
1235
1236
		String selection = "Inner";
1237
		int start = str.lastIndexOf(selection);
1238
		int length = selection.length();
1239
		IJavaElement[] elements = cu.codeSelect(start, length);
1240
1241
		assertElementsEqual(
1242
			"Unexpected elements",
1243
			"Inner() [in Inner [in m() [in C [in C.java [in p [in src [in P1]]]]]]]",
1244
			elements
1245
		);
1246
	} finally {
1247
		this.deleteProject("P1");
1248
	}
1249
}
1206
}
1250
}
(-)a/org.eclipse.jdt.core.tests.model/src/org/eclipse/jdt/core/tests/model/RunJavaSearchGenericTests.java (-1 / +2 lines)
Lines 1-5 Link Here
1
/*******************************************************************************
1
/*******************************************************************************
2
 * Copyright (c) 2000, 2006 IBM Corporation and others.
2
 * Copyright (c) 2000, 2012 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 45-50 Link Here
45
	AbstractJavaSearchTests.JAVA_SEARCH_SUITES = new ArrayList(Arrays.asList(getJavaSearchTestClasses()));
45
	AbstractJavaSearchTests.JAVA_SEARCH_SUITES = new ArrayList(Arrays.asList(getJavaSearchTestClasses()));
46
	List allClasses = new ArrayList(AbstractJavaSearchTests.JAVA_SEARCH_SUITES);
46
	List allClasses = new ArrayList(AbstractJavaSearchTests.JAVA_SEARCH_SUITES);
47
	allClasses.add(JavaSearchBugsTests.class);
47
	allClasses.add(JavaSearchBugsTests.class);
48
	allClasses.add(JavaSearchBugsTests2.class);
48
49
49
	// Reset forgotten subsets of tests
50
	// Reset forgotten subsets of tests
50
	TestCase.TESTS_PREFIX = null;
51
	TestCase.TESTS_PREFIX = null;
(-)a/org.eclipse.jdt.core.tests.model/src/org/eclipse/jdt/core/tests/model/RunJavaSearchTests.java (-1 / +3 lines)
Lines 1-5 Link Here
1
/*******************************************************************************
1
/*******************************************************************************
2
 * Copyright (c) 2000, 2009 IBM Corporation and others.
2
 * Copyright (c) 2000, 2012 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 58-67 Link Here
58
		// Get all classes
58
		// Get all classes
59
		List allClasses = new ArrayList(TEST_CLASSES);
59
		List allClasses = new ArrayList(TEST_CLASSES);
60
		allClasses.add(JavaSearchBugsTests.class);
60
		allClasses.add(JavaSearchBugsTests.class);
61
		allClasses.add(JavaSearchBugsTests2.class);
61
		allClasses.add(JavaSearchMultipleProjectsTests.class);
62
		allClasses.add(JavaSearchMultipleProjectsTests.class);
62
		allClasses.add(SearchTests.class);
63
		allClasses.add(SearchTests.class);
63
		allClasses.add(JavaSearchScopeTests.class);
64
		allClasses.add(JavaSearchScopeTests.class);
64
		allClasses.add(MatchingRegionsTest.class);
65
		allClasses.add(MatchingRegionsTest.class);
66
		allClasses.add(JavaIndexTests.class);
65
67
66
		// Reset forgotten subsets of tests
68
		// Reset forgotten subsets of tests
67
		TestCase.TESTS_PREFIX = null;
69
		TestCase.TESTS_PREFIX = null;
(-)a/org.eclipse.jdt.core.tests.model/src/org/eclipse/jdt/core/tests/model/TypeResolveTests.java (+104 lines)
Lines 33-38 Link Here
33
import org.eclipse.jdt.core.JavaModelException;
33
import org.eclipse.jdt.core.JavaModelException;
34
import org.eclipse.jdt.core.tests.util.Util;
34
import org.eclipse.jdt.core.tests.util.Util;
35
import org.eclipse.jdt.internal.core.LocalVariable;
35
import org.eclipse.jdt.internal.core.LocalVariable;
36
import org.eclipse.jdt.internal.core.SourceType;
36
37
37
public class TypeResolveTests extends ModifyingResourceTests {
38
public class TypeResolveTests extends ModifyingResourceTests {
38
	ICompilationUnit cu;
39
	ICompilationUnit cu;
Lines 700-703 Link Here
700
		deleteProject("P");
701
		deleteProject("P");
701
	}
702
	}
702
}
703
}
704
/**
705
 * @bug 342393: Anonymous class' occurrence count is incorrect when two methods in a class have the same name.
706
 *
707
 * @see "https://bugs.eclipse.org/bugs/show_bug.cgi?id=342393"
708
 */
709
public void testBug342393() throws Exception {
710
	try {
711
		IJavaProject project = createJavaProject("Test342393", new String[] {"src"}, new String[] {"JCL15_LIB"}, "bin", "1.5");
712
		project.open(null);
713
			String fileContent =  "package p;\n"
714
					 + "public class Test {\n"
715
					 + "Test() {\n"
716
					 + "    class A {\n"
717
					 + "    	// one \n"
718
					 + "        public void foo() {\n"
719
					 + "            Throwable a1 = new Throwable(){ // two \n"
720
					 + "            };\n"
721
					 + "            Throwable b1 = new Throwable(){ // three \n"
722
					 + "            };\n"
723
					 + "        }\n"
724
					 + "        public void bar() {\n"
725
					 + "            Throwable b2 = new Throwable(){ // four\n"
726
					 + "            	Throwable bi2 = new Throwable() { // five\n"
727
					 + "            	};\n"
728
					 + "            };\n"
729
					 + "        }\n"
730
					 + "        class B {\n"
731
					 + "        	Throwable t1 = new Throwable() { // six\n"
732
					 + "        	};\n"
733
					 + "        	Throwable t2 = new Throwable() { // seven\n"
734
					 + "        	};\n"
735
					 + "        }\n"
736
					 + "    };\n"
737
					 + "    {\n"
738
					 + "        Throwable a3 = new Throwable(){ // eight\n"
739
					 + "        	Throwable ai3 = new Throwable() { // nine\n"
740
					 + "        	};\n"
741
					 + "        };\n"
742
					 + "    }\n"
743
					 + "}\n"
744
					 + "public static void main(String[] args) throws Exception {\n"
745
					 + "	Throwable c1 = new Throwable() { // ten\n"
746
					 + "	};\n"
747
					 + "	Throwable c2 = new Throwable() { // eleven\n"
748
					 + "	};\n"
749
					 + "}\n"
750
					 + "}\n";
751
			createFolder("/Test342393/src/p");
752
			createFile(	"/Test342393/src/p/Test.java",	fileContent);
753
754
			ICompilationUnit unit = getCompilationUnit("/Test342393/src/p/Test.java");
755
			int index = fileContent.indexOf("// one");
756
			IJavaElement element = unit.getElementAt(index);
757
			assertEquals("Incorrect Type selected", "p.Test$A", ((SourceType)element.getParent()).getFullyQualifiedName());
758
			index = fileContent.indexOf("// two");
759
			element = unit.getElementAt(index);
760
			assertEquals("Incorrect Type selected", "p.Test$A$1", ((SourceType)element).getFullyQualifiedName());
761
			index = fileContent.indexOf("// three");
762
			element = unit.getElementAt(index);
763
			assertEquals("Incorrect Type selected", "p.Test$A$2", ((SourceType)element).getFullyQualifiedName());
764
			index = fileContent.indexOf("// four");
765
			element = unit.getElementAt(index);
766
			assertEquals("Incorrect Type selected", "p.Test$A$3", ((SourceType)element).getFullyQualifiedName());
767
			index = fileContent.indexOf("// five");
768
			element = unit.getElementAt(index);
769
			assertEquals("Incorrect Type selected", "p.Test$A$3$1", ((SourceType)element).getFullyQualifiedName());
770
			index = fileContent.indexOf("// six");
771
			element = unit.getElementAt(index);
772
			assertEquals("Incorrect Type selected", "p.Test$A$B$1", ((SourceType)element).getFullyQualifiedName());
773
			index = fileContent.indexOf("// seven");
774
			element = unit.getElementAt(index);
775
			assertEquals("Incorrect Type selected", "p.Test$A$B$2", ((SourceType)element).getFullyQualifiedName());
776
777
			String handleId = ((SourceType)element).getHandleMemento();
778
			IJavaElement newElement = JavaCore.create(handleId);
779
			assertEquals("Incorrect Element", element, newElement);
780
781
			index = fileContent.indexOf("// eight");
782
			element = unit.getElementAt(index);
783
			assertEquals("Incorrect Type selected", "p.Test$1", ((SourceType)element).getFullyQualifiedName());
784
			index = fileContent.indexOf("// nine");
785
			element = unit.getElementAt(index);
786
			assertEquals("Incorrect Type selected", "p.Test$1$1", ((SourceType)element).getFullyQualifiedName());
787
788
			handleId = ((SourceType)element).getHandleMemento();
789
			newElement = JavaCore.create(handleId);
790
			assertEquals("Incorrect Element", element, newElement);
791
792
			index = fileContent.indexOf("// ten");
793
			element = unit.getElementAt(index);
794
			assertEquals("Incorrect Type selected", "p.Test$2", ((SourceType)element).getFullyQualifiedName());
795
			index = fileContent.indexOf("// eleven");
796
			element = unit.getElementAt(index);
797
			assertEquals("Incorrect Type selected", "p.Test$3", ((SourceType)element).getFullyQualifiedName());
798
799
			handleId = ((SourceType)element).getHandleMemento();
800
			newElement = JavaCore.create(handleId);
801
			assertEquals("Incorrect Element", element, newElement);
802
	}
803
	finally {
804
		deleteProject("Test342393");
805
	}
806
}
703
}
807
}
(-)a/org.eclipse.jdt.core.tests.model/src/org/eclipse/jdt/core/tests/model/WorkingCopyTests.java (-2 / +3 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 202-209 Link Here
202
202
203
/**
203
/**
204
 * Test creating a working copy on a class file with a customized buffer.
204
 * Test creating a working copy on a class file with a customized buffer.
205
 * As of https://bugs.eclipse.org/337935 this test is no longer valid.
205
 */
206
 */
206
public void testOnClassFile() throws JavaModelException, IOException {
207
public void _testOnClassFile() throws JavaModelException, IOException {
207
	// ensure the external JCL is copied
208
	// ensure the external JCL is copied
208
	setupExternalJCL("jclMin");
209
	setupExternalJCL("jclMin");
209
210
(-)a/org.eclipse.jdt.core.tests.model/src/org/eclipse/jdt/core/tests/rewrite/describing/ASTRewritingStatementsTest.java (+151 lines)
Lines 15-20 Link Here
15
import junit.framework.TestSuite;
15
import junit.framework.TestSuite;
16
16
17
import org.eclipse.jdt.core.ICompilationUnit;
17
import org.eclipse.jdt.core.ICompilationUnit;
18
import org.eclipse.jdt.core.IJavaProject;
18
import org.eclipse.jdt.core.IPackageFragment;
19
import org.eclipse.jdt.core.IPackageFragment;
19
import org.eclipse.jdt.core.IPackageFragmentRoot;
20
import org.eclipse.jdt.core.IPackageFragmentRoot;
20
import org.eclipse.jdt.core.JavaCore;
21
import org.eclipse.jdt.core.JavaCore;
Lines 5694-5700 Link Here
5694
		assertEqualString(preview, buf.toString());
5695
		assertEqualString(preview, buf.toString());
5695
5696
5696
	}
5697
	}
5698
	
5699
	
5700
	// https://bugs.eclipse.org/bugs/show_bug.cgi?id=350285
5701
	// Test that converting a multi catch into a normal catch using complete block copy doesn't change indentation
5702
	public void testTryStatementWithMultiCatch1() throws Exception {
5703
		createProject("P_17", JavaCore.VERSION_1_7);
5704
		IPackageFragmentRoot currentSourceFolder = getPackageFragmentRoot("P_17", "src");
5705
		try {
5706
			IPackageFragment pack1= currentSourceFolder.createPackageFragment("test1", false, null);
5707
			StringBuffer buf= new StringBuffer();
5708
			buf.append("package test1;\n");
5709
			buf.append("public class E {\n");
5710
			buf.append("    public void foo(int i) {\n");
5711
			buf.append("        try {\n");
5712
			buf.append("            System.out.println(\"foo\");\n");
5713
			buf.append("        } catch (IllegalArgumentException | NullPointerException exe) {\n");
5714
			buf.append("            System.out.println(exe);\n");
5715
			buf.append("        }\n");
5716
			buf.append("    }\n");
5717
			buf.append("}\n");
5718
			ICompilationUnit cu= pack1.createCompilationUnit("E.java", buf.toString(), false, null);
5697
5719
5720
			CompilationUnit astRoot= createAST(AST.JLS4, cu, false);
5721
			AST ast= astRoot.getAST();
5722
			ASTRewrite rewrite= ASTRewrite.create(ast);
5723
5724
			assertTrue("Parse errors", (astRoot.getFlags() & ASTNode.MALFORMED) == 0);
5725
			TypeDeclaration type= findTypeDeclaration(astRoot, "E");
5726
			MethodDeclaration methodDecl= findMethodDeclaration(type, "foo");
5727
			Block block= methodDecl.getBody();
5728
			List blockStatements= block.statements();
5729
			assertTrue("Number of statements not 1", blockStatements.size() == 1);
5730
			{ // convert multicatch to normal catch blocks
5731
				TryStatement tryStatement= (TryStatement) blockStatements.get(0);
5732
				List catchClauses= tryStatement.catchClauses();
5733
				assertTrue("Number of catch clauses not 1", catchClauses.size() == 1);
5734
				CatchClause catchClause = (CatchClause) catchClauses.get(0);
5735
				
5736
				SingleVariableDeclaration singleVariableDeclaration= catchClause.getException();
5737
				UnionType unionType = (UnionType) singleVariableDeclaration.getType();
5738
				List types = unionType.types();
5739
				assertTrue("Number of union types", types.size() == 2);
5740
				for (int i= types.size() - 1; i >= 0; i--) {
5741
					Type type2= (Type)types.get(i);
5742
					CatchClause newCatchClause= ast.newCatchClause();
5743
					SingleVariableDeclaration newSingleVariableDeclaration= ast.newSingleVariableDeclaration();
5744
					newSingleVariableDeclaration.setType((Type) rewrite.createCopyTarget(type2));
5745
					newSingleVariableDeclaration.setName((SimpleName) rewrite.createCopyTarget(singleVariableDeclaration.getName()));
5746
					newCatchClause.setException(newSingleVariableDeclaration);
5747
					newCatchClause.setBody((Block) rewrite.createCopyTarget(catchClause.getBody()));
5748
					rewrite.getListRewrite(tryStatement, TryStatement.CATCH_CLAUSES_PROPERTY).insertAfter(newCatchClause, catchClause, null);
5749
				}
5750
				rewrite.remove(catchClause, null);
5751
			}
5752
			String preview= evaluateRewrite(cu, rewrite);
5753
5754
			buf= new StringBuffer();
5755
			buf.append("package test1;\n");
5756
			buf.append("public class E {\n");
5757
			buf.append("    public void foo(int i) {\n");
5758
			buf.append("        try {\n");
5759
			buf.append("            System.out.println(\"foo\");\n");
5760
			buf.append("        } catch (IllegalArgumentException exe) {\n");
5761
			buf.append("            System.out.println(exe);\n");
5762
			buf.append("        } catch (NullPointerException exe) {\n");
5763
			buf.append("            System.out.println(exe);\n");
5764
			buf.append("        }\n");
5765
			buf.append("    }\n");
5766
			buf.append("}\n");
5767
			assertEqualString(preview, buf.toString());
5768
		} finally {
5769
			deleteProject("P_17");
5770
		}
5771
	}
5772
5773
	// https://bugs.eclipse.org/bugs/show_bug.cgi?id=350285
5774
	// similar to testTryStatementWithMultiCatch1() but has a different brace position
5775
	public void testTryStatementWithMultiCatch2() throws Exception {
5776
		IJavaProject project = createProject("P_17", JavaCore.VERSION_1_7);
5777
		project.setOption(DefaultCodeFormatterConstants.FORMATTER_BRACE_POSITION_FOR_BLOCK, DefaultCodeFormatterConstants.NEXT_LINE);
5778
		IPackageFragmentRoot currentSourceFolder = getPackageFragmentRoot("P_17", "src");
5779
		try {
5780
			IPackageFragment pack1= currentSourceFolder.createPackageFragment("test1", false, null);
5781
			StringBuffer buf= new StringBuffer();
5782
			buf.append("package test1;\n");
5783
			buf.append("public class E {\n");
5784
			buf.append("    public void foo(int i) {\n");
5785
			buf.append("        try {\n");
5786
			buf.append("            System.out.println(\"foo\");\n");
5787
			buf.append("        } catch (IllegalArgumentException | NullPointerException exe)\n");
5788
			buf.append("        {\n");
5789
			buf.append("            System.out.println(exe);\n");
5790
			buf.append("        }\n");
5791
			buf.append("    }\n");
5792
			buf.append("}\n");
5793
			ICompilationUnit cu= pack1.createCompilationUnit("E.java", buf.toString(), false, null);
5794
5795
			CompilationUnit astRoot= createAST(AST.JLS4, cu, false);
5796
			AST ast= astRoot.getAST();
5797
			ASTRewrite rewrite= ASTRewrite.create(ast);
5798
5799
			assertTrue("Parse errors", (astRoot.getFlags() & ASTNode.MALFORMED) == 0);
5800
			TypeDeclaration type= findTypeDeclaration(astRoot, "E");
5801
			MethodDeclaration methodDecl= findMethodDeclaration(type, "foo");
5802
			Block block= methodDecl.getBody();
5803
			List blockStatements= block.statements();
5804
			assertTrue("Number of statements not 1", blockStatements.size() == 1);
5805
			{ // convert multicatch to normal catch blocks
5806
				TryStatement tryStatement= (TryStatement) blockStatements.get(0);
5807
				List catchClauses= tryStatement.catchClauses();
5808
				assertTrue("Number of catch clauses not 1", catchClauses.size() == 1);
5809
				CatchClause catchClause = (CatchClause) catchClauses.get(0);
5810
				
5811
				SingleVariableDeclaration singleVariableDeclaration= catchClause.getException();
5812
				UnionType unionType = (UnionType) singleVariableDeclaration.getType();
5813
				List types = unionType.types();
5814
				assertTrue("Number of union types", types.size() == 2);
5815
				for (int i= types.size() - 1; i >= 0; i--) {
5816
					Type type2= (Type)types.get(i);
5817
					CatchClause newCatchClause= ast.newCatchClause();
5818
					SingleVariableDeclaration newSingleVariableDeclaration= ast.newSingleVariableDeclaration();
5819
					newSingleVariableDeclaration.setType((Type) rewrite.createCopyTarget(type2));
5820
					newSingleVariableDeclaration.setName((SimpleName) rewrite.createCopyTarget(singleVariableDeclaration.getName()));
5821
					newCatchClause.setException(newSingleVariableDeclaration);
5822
					newCatchClause.setBody((Block) rewrite.createCopyTarget(catchClause.getBody()));
5823
					rewrite.getListRewrite(tryStatement, TryStatement.CATCH_CLAUSES_PROPERTY).insertAfter(newCatchClause, catchClause, null);
5824
				}
5825
				rewrite.remove(catchClause, null);
5826
			}
5827
			String preview= evaluateRewrite(cu, rewrite);
5828
5829
			buf= new StringBuffer();
5830
			buf.append("package test1;\n");
5831
			buf.append("public class E {\n");
5832
			buf.append("    public void foo(int i) {\n");
5833
			buf.append("        try {\n");
5834
			buf.append("            System.out.println(\"foo\");\n");
5835
			buf.append("        } catch (IllegalArgumentException exe)\n");
5836
			buf.append("        {\n");
5837
			buf.append("            System.out.println(exe);\n");
5838
			buf.append("        } catch (NullPointerException exe)\n");
5839
			buf.append("        {\n");
5840
			buf.append("            System.out.println(exe);\n");
5841
			buf.append("        }\n");
5842
			buf.append("    }\n");
5843
			buf.append("}\n");
5844
			assertEqualString(preview, buf.toString());
5845
		} finally {
5846
			deleteProject("P_17");
5847
		}
5848
	}
5698
}
5849
}
5699
5850
5700
5851
(-)a/org.eclipse.jdt.core.tests.model/test.xml (-3 / +4 lines)
Lines 1-6 Link Here
1
<?xml version="1.0"?>
1
<?xml version="1.0" encoding="UTF-8"?>
2
<!--
2
3
    Copyright (c) 2002, 2009 IBM Corporation and others.
3
<!--
4
    Copyright (c) 2002, 2011 IBM Corporation and others.
4
    All rights reserved. This program and the accompanying materials
5
    All rights reserved. This program and the accompanying materials
5
    are made available under the terms of the Eclipse Public License v1.0
6
    are made available under the terms of the Eclipse Public License v1.0
6
    which accompanies this distribution, and is available at
7
    which accompanies this distribution, and is available at
(-)a/org.eclipse.jdt.core.tests.performance/.settings/org.eclipse.core.runtime.prefs (+2 lines)
Added Link Here
1
eclipse.preferences.version=1
2
line.separator=\n
(-)a/org.eclipse.jdt.core.tests.performance/META-INF/MANIFEST.MF (-2 / +3 lines)
Lines 2-8 Link Here
2
Bundle-ManifestVersion: 2
2
Bundle-ManifestVersion: 2
3
Bundle-Name: %pluginName
3
Bundle-Name: %pluginName
4
Bundle-SymbolicName: org.eclipse.jdt.core.tests.performance
4
Bundle-SymbolicName: org.eclipse.jdt.core.tests.performance
5
Bundle-Version: 3.8.0.qualifier
5
Bundle-Version: 3.8.1.qualifier
6
Bundle-ClassPath: jdtcoretestsperf.jar
6
Bundle-ClassPath: jdtcoretestsperf.jar
7
Bundle-Vendor: %providerName
7
Bundle-Vendor: %providerName
8
Bundle-Localization: plugin
8
Bundle-Localization: plugin
Lines 16-20 Link Here
16
 org.eclipse.jdt.core.tests.model;bundle-version="[3.4.0,4.0.0)",
16
 org.eclipse.jdt.core.tests.model;bundle-version="[3.4.0,4.0.0)",
17
 org.junit;bundle-version="3.8.1",
17
 org.junit;bundle-version="3.8.1",
18
 org.eclipse.test.performance;bundle-version="[3.1.0,4.0.0)",
18
 org.eclipse.test.performance;bundle-version="[3.1.0,4.0.0)",
19
 org.eclipse.text;bundle-version="[3.1.0,4.0.0)"
19
 org.eclipse.text;bundle-version="[3.1.0,4.0.0)",
20
 org.eclipse.jdt.core.tests.binaries;bundle-version="1.0.0"
20
Bundle-RequiredExecutionEnvironment: J2SE-1.4
21
Bundle-RequiredExecutionEnvironment: J2SE-1.4
(-)a/org.eclipse.jdt.core.tests.performance/build.properties (-4 / +1 lines)
Lines 13-22 Link Here
13
               jdtcoretestsperf.jar,\
13
               jdtcoretestsperf.jar,\
14
               local_test.xml,\
14
               local_test.xml,\
15
               META-INF/,\
15
               META-INF/,\
16
               plugin.properties,\
16
               plugin.properties
17
               full-source-R3_0.zip,\
18
               GenericTypeTest.java,\
19
               EclipseVisitorBug.java
20
src.includes = about.html
17
src.includes = about.html
21
source.jdtcoretestsperf.jar = src/
18
source.jdtcoretestsperf.jar = src/
22
output.jdtcoretestsperf.jar = bin/
19
output.jdtcoretestsperf.jar = bin/
(-)a/org.eclipse.jdt.core.tests.performance/local_test.xml (-2 / +3 lines)
Lines 1-5 Link Here
1
<?xml version="1.0"?>
1
<?xml version="1.0" encoding="UTF-8"?>
2
<!--
2
3
<!--
3
    Copyright (c) 2006, 2009 IBM Corporation and others.
4
    Copyright (c) 2006, 2009 IBM Corporation and others.
4
    All rights reserved. This program and the accompanying materials
5
    All rights reserved. This program and the accompanying materials
5
    are made available under the terms of the Eclipse Public License v1.0
6
    are made available under the terms of the Eclipse Public License v1.0
(-)a/org.eclipse.jdt.core.tests.performance/src/org/eclipse/jdt/core/tests/performance/FullSourceWorkspaceBuildTests.java (-2 / +2 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 281-287 Link Here
281
		final String targetWorkspacePath = ResourcesPlugin.getWorkspace().getRoot().getLocation().toFile().getCanonicalPath();
281
		final String targetWorkspacePath = ResourcesPlugin.getWorkspace().getRoot().getLocation().toFile().getCanonicalPath();
282
		String logFileName = targetWorkspacePath + File.separator + getName()+".log";
282
		String logFileName = targetWorkspacePath + File.separator + getName()+".log";
283
		
283
		
284
		String pluginDir = getPluginDirectoryPath();
284
		String pluginDir = getPluginBinariesDirectoryPath();
285
		String sources = "";
285
		String sources = "";
286
		for (int i=0, l=srcPaths.length; i<l; i++) {
286
		for (int i=0, l=srcPaths.length; i<l; i++) {
287
			String path = pluginDir + File.separator + srcPaths[i];
287
			String path = pluginDir + File.separator + srcPaths[i];
(-)a/org.eclipse.jdt.core.tests.performance/src/org/eclipse/jdt/core/tests/performance/FullSourceWorkspaceFormatterTests.java (-2 / +2 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 65-71 Link Here
65
	// Read big file
65
	// Read big file
66
	System.out.print("	- Read big file source...");
66
	System.out.print("	- Read big file source...");
67
	long start = System.currentTimeMillis();
67
	long start = System.currentTimeMillis();
68
	FORMAT_TYPE_SOURCE = Util.fileContent(getPluginDirectoryPath()+File.separator+"GenericTypeTest.java");
68
	FORMAT_TYPE_SOURCE = Util.fileContent(getPluginBinariesDirectoryPath()+File.separator+"GenericTypeTest.java");
69
	System.out.println("("+(System.currentTimeMillis()-start)+"ms)");
69
	System.out.println("("+(System.currentTimeMillis()-start)+"ms)");
70
}
70
}
71
71
(-)a/org.eclipse.jdt.core.tests.performance/src/org/eclipse/jdt/core/tests/performance/FullSourceWorkspaceModelTests.java (-1 / +58 lines)
Lines 347-353 Link Here
347
	}
347
	}
348
	assertEquals(message, expected, actual);
348
	assertEquals(message, expected, actual);
349
}
349
}
350
350
private void touchFiles(File[] files) {
351
	for(int index=0; index < files.length; index++) {
352
		files[index].setLastModified(System.currentTimeMillis());
353
	}
354
}
351
/*
355
/*
352
 * Creates a simple Java project with no source folder and only rt.jar on its classpath.
356
 * Creates a simple Java project with no source folder and only rt.jar on its classpath.
353
 */
357
 */
Lines 1371-1376 Link Here
1371
		System.out.println((System.currentTimeMillis()-startTime)+"ms");
1375
		System.out.println((System.currentTimeMillis()-startTime)+"ms");
1372
	}
1376
	}
1373
}
1377
}
1378
//https://bugs.eclipse.org/bugs/show_bug.cgi?id=354332
1379
public void testRefreshExternalArchives() throws Exception {
1380
	int jarCount = 100;
1381
	File[] files = new File[jarCount];
1382
	IJavaModel model = JavaCore.create(ResourcesPlugin.getWorkspace().getRoot());
1383
	IClasspathEntry[] oldClasspath = BIG_PROJECT.getRawClasspath();
1384
	try {
1385
		IClasspathEntry[] classpath = new IClasspathEntry[jarCount];
1386
		for (int index = 0; index < jarCount; index++) {
1387
			String filePath = getExternalResourcePath("lib"+ index +".jar");
1388
			org.eclipse.jdt.core.tests.util.Util.createJar(new String[0],
1389
				new String[] {
1390
					"META-INF/MANIFEST.MF",
1391
					"Manifest-Version: 1.0\n",
1392
				},
1393
				filePath,
1394
				JavaCore.VERSION_1_4);
1395
			classpath[index] = JavaCore.newLibraryEntry(new Path(filePath), null, null);
1396
			files[index]  = new File(filePath);
1397
		}
1398
		BIG_PROJECT.setRawClasspath(classpath, null);
1399
		
1400
		// warm up
1401
		int max = 20;
1402
		int warmup = WARMUP_COUNT / 10;
1403
		for (int i = 0; i < warmup; i++) {
1404
			for (int j = 0; j < max; j++) {
1405
				touchFiles(files);
1406
				model.refreshExternalArchives(new IJavaElement[] {BIG_PROJECT}, null);
1407
			}
1408
		}
1409
1410
		// measure performance
1411
		for (int i = 0; i < MEASURES_COUNT; i++) {
1412
			runGc();
1413
			startMeasuring();
1414
			for (int j = 0; j < max; j++) {
1415
				touchFiles(files);
1416
				model.refreshExternalArchives(new IJavaElement[] {BIG_PROJECT}, null);
1417
			}
1418
			stopMeasuring();
1419
		}
1420
1421
		commitMeasurements();
1422
		assertPerformance();		
1423
		
1424
	} finally {
1425
		BIG_PROJECT.setRawClasspath(oldClasspath, null);
1426
		for(int index=0; index < files.length; index++) {
1427
			files[index].delete();
1428
		}
1429
	}
1430
}
1374
1431
1375
protected void resetCounters() {
1432
protected void resetCounters() {
1376
	// do nothing
1433
	// do nothing
(-)a/org.eclipse.jdt.core.tests.performance/src/org/eclipse/jdt/core/tests/performance/FullSourceWorkspaceTests.java (-3 / +19 lines)
Lines 405-413 Link Here
405
	/*
405
	/*
406
	 * Returns the OS path to the directory that contains this plugin.
406
	 * Returns the OS path to the directory that contains this plugin.
407
	 */
407
	 */
408
	static String getPluginDirectoryPath() {
408
	static String getPluginBinariesDirectoryPath() {
409
		try {
409
		try {
410
			URL platformURL = Platform.getBundle("org.eclipse.jdt.core.tests.performance").getEntry("/");
410
			URL platformURL = Platform.getBundle("org.eclipse.jdt.core.tests.binaries").getEntry("/");
411
			return new File(FileLocator.toFileURL(platformURL).getFile()).getAbsolutePath();
411
			return new File(FileLocator.toFileURL(platformURL).getFile()).getAbsolutePath();
412
		} catch (IOException e) {
412
		} catch (IOException e) {
413
			e.printStackTrace();
413
			e.printStackTrace();
Lines 621-627 Link Here
621
		long start = System.currentTimeMillis();
621
		long start = System.currentTimeMillis();
622
		int dirLength = directories.length;
622
		int dirLength = directories.length;
623
		if (dirLength < 62) {
623
		if (dirLength < 62) {
624
			String fullSourceZipPath = getPluginDirectoryPath() + File.separator + "full-source-R3_0.zip";
624
			String fullSourceZipPath = getPluginBinariesDirectoryPath() + File.separator + "full-source-R3_0.zip";
625
			System.out.println("Unzipping "+fullSourceZipPath);
625
			System.out.println("Unzipping "+fullSourceZipPath);
626
			System.out.print("	in "+targetWorkspacePath+"...");
626
			System.out.print("	in "+targetWorkspacePath+"...");
627
			Util.unzip(fullSourceZipPath, targetWorkspacePath);
627
			Util.unzip(fullSourceZipPath, targetWorkspacePath);
Lines 1246-1249 Link Here
1246
		// Return created options map
1246
		// Return created options map
1247
		return optionsMap;
1247
		return optionsMap;
1248
	}
1248
	}
1249
1250
	protected String getExternalPath() {
1251
		String path = "";
1252
		try {
1253
			path = ResourcesPlugin.getWorkspace().getRoot().getLocation().toFile().getParentFile().getCanonicalPath();
1254
			if (path.charAt(path.length()-1) != File.separatorChar)
1255
				path += File.separatorChar;
1256
		} catch (IOException e) {
1257
			e.printStackTrace();
1258
		}
1259
		return path;
1260
	}
1261
1262
	protected String getExternalResourcePath(String relativePath) {
1263
		return getExternalPath() + relativePath;
1264
	}
1249
}
1265
}
(-)a/org.eclipse.jdt.core.tests.performance/test.xml (-3 / +4 lines)
Lines 1-6 Link Here
1
<?xml version="1.0"?>
1
<?xml version="1.0" encoding="UTF-8"?>
2
<!--
2
3
    Copyright (c) 2004, 2009 IBM Corporation and others.
3
<!--
4
    Copyright (c) 2004, 2011 IBM Corporation and others.
4
    All rights reserved. This program and the accompanying materials
5
    All rights reserved. This program and the accompanying materials
5
    are made available under the terms of the Eclipse Public License v1.0
6
    are made available under the terms of the Eclipse Public License v1.0
6
    which accompanies this distribution, and is available at
7
    which accompanies this distribution, and is available at
(-)a/org.eclipse.jdt.core/.cvsignore (-3 lines)
Lines 1-3 Link Here
1
bin
2
antbin
3
jdtCompilerAdapter.jar
(-)a/org.eclipse.jdt.core/.settings/.api_filters (-359 / +26 lines)
Lines 1-359 Link Here
1
<?xml version="1.0" encoding="UTF-8" standalone="no"?>
1
<?xml version="1.0" encoding="UTF-8"?><component id="org.eclipse.jdt.core" version="2">
2
<component id="org.eclipse.jdt.core" version="2">
2
    <resource path="model/org/eclipse/jdt/core/IJavaModelMarker.java" type="org.eclipse.jdt.core.IJavaModelMarker">
3
    <resource path="compiler/org/eclipse/jdt/core/compiler/CharOperation.java" type="org.eclipse.jdt.core.compiler.CharOperation">
3
        <filter id="1210056707">
4
        <filter comment="new APIs added for Java7 support post 3.7.0" id="1142947843">
4
            <message_arguments>
5
            <message_arguments>
5
                <message_argument value="3.6.4"/>
6
                <message_argument value="3.7.1"/>
6
                <message_argument value="OUTPUT_OVERLAPPING_SOURCE"/>
7
                <message_argument value="compareTo(char[], char[], int, int)"/>
7
            </message_arguments>
8
            </message_arguments>
8
        </filter>
9
        </filter>
9
    </resource>
10
    </resource>
10
    <resource path="model/org/eclipse/jdt/core/IJavaModelStatusConstants.java" type="org.eclipse.jdt.core.IJavaModelStatusConstants">
11
    <resource path="compiler/org/eclipse/jdt/core/compiler/IProblem.java" type="org.eclipse.jdt.core.compiler.IProblem">
11
        <filter id="1210056707">
12
        <filter comment="new APIs added for Java7 support post 3.7.0" id="1210056707">
12
            <message_arguments>
13
            <message_arguments>
13
                <message_argument value="3.6.4"/>
14
                <message_argument value="3.7.1"/>
14
                <message_argument value="OUTPUT_LOCATION_OVERLAPPING_ANOTHER_SOURCE"/>
15
                <message_argument value="AssignmentToMultiCatchParameter"/>
15
            </message_arguments>
16
            </message_arguments>
16
        </filter>
17
        </filter>
17
    </resource>
18
        <filter comment="new APIs added for Java7 support post 3.7.0" id="1210056707">
18
    <resource path="model/org/eclipse/jdt/core/JavaCore.java" type="org.eclipse.jdt.core.JavaCore">
19
            <message_arguments>
19
        <filter id="1142947843">
20
                <message_argument value="3.7.1"/>
20
            <message_arguments>
21
                <message_argument value="AssignmentToResource"/>
21
                <message_argument value="3.6.4"/>
22
            </message_arguments>
22
                <message_argument value="CORE_OUTPUT_LOCATION_OVERLAPPING_ANOTHER_SOURCE"/>
23
        </filter>
23
            </message_arguments>
24
        <filter comment="new APIs added for Java7 support post 3.7.0" id="1210056707">
24
        </filter>
25
            <message_arguments>
25
    </resource>
26
                <message_argument value="3.7.1"/>
26
</component>
27
                <message_argument value="AutoManagedResourceNotBelow17"/>
28
            </message_arguments>
29
        </filter>
30
        <filter comment="new APIs added for Java7 support post 3.7.0" id="1210056707">
31
            <message_arguments>
32
                <message_argument value="3.7.1"/>
33
                <message_argument value="BinaryLiteralNotBelow17"/>
34
            </message_arguments>
35
        </filter>
36
        <filter comment="new APIs added for Java7 support post 3.7.0" id="1210056707">
37
            <message_arguments>
38
                <message_argument value="3.7.1"/>
39
                <message_argument value="CannotInferElidedTypes"/>
40
            </message_arguments>
41
        </filter>
42
        <filter comment="new APIs added for Java7 support post 3.7.0" id="1210056707">
43
            <message_arguments>
44
                <message_argument value="3.7.1"/>
45
                <message_argument value="CannotUseDiamondWithAnonymousClasses"/>
46
            </message_arguments>
47
        </filter>
48
        <filter comment="new APIs added for Java7 support post 3.7.0" id="1210056707">
49
            <message_arguments>
50
                <message_argument value="3.7.1"/>
51
                <message_argument value="CannotUseDiamondWithExplicitTypeArguments"/>
52
            </message_arguments>
53
        </filter>
54
        <filter comment="new APIs added for Java7 support post 3.7.0" id="1210056707">
55
            <message_arguments>
56
                <message_argument value="3.7.1"/>
57
                <message_argument value="DiamondNotBelow17"/>
58
            </message_arguments>
59
        </filter>
60
        <filter comment="new APIs added for Java7 support post 3.7.0" id="1210056707">
61
            <message_arguments>
62
                <message_argument value="3.7.1"/>
63
                <message_argument value="DuplicateInheritedMethods"/>
64
            </message_arguments>
65
        </filter>
66
        <filter comment="new APIs added for Java7 support post 3.7.0" id="1210056707">
67
            <message_arguments>
68
                <message_argument value="3.7.1"/>
69
                <message_argument value="IllegalHexaLiteral"/>
70
            </message_arguments>
71
        </filter>
72
        <filter comment="new APIs added for Java7 support post 3.7.0" id="1210056707">
73
            <message_arguments>
74
                <message_argument value="3.7.1"/>
75
                <message_argument value="IllegalUnderscorePosition"/>
76
            </message_arguments>
77
        </filter>
78
        <filter comment="new APIs added for Java7 support post 3.7.0" id="1210056707">
79
            <message_arguments>
80
                <message_argument value="3.7.1"/>
81
                <message_argument value="IncorrectSwitchType17"/>
82
            </message_arguments>
83
        </filter>
84
        <filter comment="new APIs added for Java7 support post 3.7.0" id="1210056707">
85
            <message_arguments>
86
                <message_argument value="3.7.1"/>
87
                <message_argument value="InvalidBinary"/>
88
            </message_arguments>
89
        </filter>
90
        <filter comment="new APIs added for Java7 support post 3.7.0" id="1210056707">
91
            <message_arguments>
92
                <message_argument value="3.7.1"/>
93
                <message_argument value="InvalidUnionTypeReferenceSequence"/>
94
            </message_arguments>
95
        </filter>
96
        <filter comment="new APIs added for Java7 support post 3.7.0" id="1210056707">
97
            <message_arguments>
98
                <message_argument value="3.7.1"/>
99
                <message_argument value="MultiCatchNotBelow17"/>
100
            </message_arguments>
101
        </filter>
102
        <filter comment="new APIs added for Java7 support post 3.7.0" id="1210056707">
103
            <message_arguments>
104
                <message_argument value="3.7.1"/>
105
                <message_argument value="PolymorphicMethodNotBelow17"/>
106
            </message_arguments>
107
        </filter>
108
        <filter comment="new APIs added for Java7 support post 3.7.0" id="1210056707">
109
            <message_arguments>
110
                <message_argument value="3.7.1"/>
111
                <message_argument value="PotentialHeapPollutionFromVararg"/>
112
            </message_arguments>
113
        </filter>
114
        <filter comment="new APIs added for Java7 support post 3.7.0" id="1210056707">
115
            <message_arguments>
116
                <message_argument value="3.7.1"/>
117
                <message_argument value="RedundantSpecificationOfTypeArguments"/>
118
            </message_arguments>
119
        </filter>
120
        <filter comment="new APIs added for Java7 support post 3.7.0" id="1210056707">
121
            <message_arguments>
122
                <message_argument value="3.7.1"/>
123
                <message_argument value="ResourceHasToImplementAutoCloseable"/>
124
            </message_arguments>
125
        </filter>
126
        <filter comment="new APIs added for Java7 support post 3.7.0" id="1210056707">
127
            <message_arguments>
128
                <message_argument value="3.7.1"/>
129
                <message_argument value="SafeVarargsOnFixedArityMethod"/>
130
            </message_arguments>
131
        </filter>
132
        <filter comment="new APIs added for Java7 support post 3.7.0" id="1210056707">
133
            <message_arguments>
134
                <message_argument value="3.7.1"/>
135
                <message_argument value="SafeVarargsOnNonFinalInstanceMethod"/>
136
            </message_arguments>
137
        </filter>
138
        <filter comment="new APIs added for Java7 support post 3.7.0" id="1210056707">
139
            <message_arguments>
140
                <message_argument value="3.7.1"/>
141
                <message_argument value="SwitchOnStringsNotBelow17"/>
142
            </message_arguments>
143
        </filter>
144
        <filter comment="new APIs added for Java7 support post 3.7.0" id="1210056707">
145
            <message_arguments>
146
                <message_argument value="3.7.1"/>
147
                <message_argument value="UnderscoresInLiteralsNotBelow17"/>
148
            </message_arguments>
149
        </filter>
150
        <filter comment="new APIs added for Java7 support post 3.7.0" id="1210056707">
151
            <message_arguments>
152
                <message_argument value="3.7.1"/>
153
                <message_argument value="UnhandledExceptionOnAutoClose"/>
154
            </message_arguments>
155
        </filter>
156
    </resource>
157
    <resource path="dom/org/eclipse/jdt/core/dom/AST.java" type="org.eclipse.jdt.core.dom.AST">
158
        <filter comment="new APIs added for Java7 support post 3.7.0" id="1142947843">
159
            <message_arguments>
160
                <message_argument value="3.7.1"/>
161
                <message_argument value="JLS4"/>
162
            </message_arguments>
163
        </filter>
164
        <filter comment="new APIs added for Java7 support post 3.7.0" id="1142947843">
165
            <message_arguments>
166
                <message_argument value="3.7.1"/>
167
                <message_argument value="newUnionType()"/>
168
            </message_arguments>
169
        </filter>
170
    </resource>
171
    <resource path="dom/org/eclipse/jdt/core/dom/ASTMatcher.java" type="org.eclipse.jdt.core.dom.ASTMatcher">
172
        <filter comment="new APIs added for Java7 support post 3.7.0" id="1142947843">
173
            <message_arguments>
174
                <message_argument value="3.7.1"/>
175
                <message_argument value="match(UnionType, Object)"/>
176
            </message_arguments>
177
        </filter>
178
    </resource>
179
    <resource path="dom/org/eclipse/jdt/core/dom/ASTNode.java" type="org.eclipse.jdt.core.dom.ASTNode">
180
        <filter comment="new APIs added for Java7 support post 3.7.0" id="1142947843">
181
            <message_arguments>
182
                <message_argument value="3.7.1"/>
183
                <message_argument value="UNION_TYPE"/>
184
            </message_arguments>
185
        </filter>
186
    </resource>
187
    <resource path="dom/org/eclipse/jdt/core/dom/ASTVisitor.java" type="org.eclipse.jdt.core.dom.ASTVisitor">
188
        <filter comment="new APIs added for Java7 support post 3.7.0" id="1142947843">
189
            <message_arguments>
190
                <message_argument value="3.7.1"/>
191
                <message_argument value="endVisit(UnionType)"/>
192
            </message_arguments>
193
        </filter>
194
        <filter comment="new APIs added for Java7 support post 3.7.0" id="1142947843">
195
            <message_arguments>
196
                <message_argument value="3.7.1"/>
197
                <message_argument value="visit(UnionType)"/>
198
            </message_arguments>
199
        </filter>
200
    </resource>
201
    <resource path="dom/org/eclipse/jdt/core/dom/ClassInstanceCreation.java" type="org.eclipse.jdt.core.dom.ClassInstanceCreation">
202
        <filter comment="new APIs added for Java7 support post 3.7.0" id="1142947843">
203
            <message_arguments>
204
                <message_argument value="3.7.1"/>
205
                <message_argument value="isResolvedTypeInferredFromExpectedType()"/>
206
            </message_arguments>
207
        </filter>
208
    </resource>
209
    <resource path="dom/org/eclipse/jdt/core/dom/TryStatement.java" type="org.eclipse.jdt.core.dom.TryStatement">
210
        <filter comment="new APIs added for Java7 support post 3.7.0" id="1142947843">
211
            <message_arguments>
212
                <message_argument value="3.7.1"/>
213
                <message_argument value="RESOURCES_PROPERTY"/>
214
            </message_arguments>
215
        </filter>
216
        <filter comment="new APIs added for Java7 support post 3.7.0" id="1142947843">
217
            <message_arguments>
218
                <message_argument value="3.7.1"/>
219
                <message_argument value="resources()"/>
220
            </message_arguments>
221
        </filter>
222
    </resource>
223
    <resource path="dom/org/eclipse/jdt/core/dom/Type.java" type="org.eclipse.jdt.core.dom.Type">
224
        <filter comment="new APIs added for Java7 support post 3.7.0" id="1142947843">
225
            <message_arguments>
226
                <message_argument value="3.7.1"/>
227
                <message_argument value="isUnionType()"/>
228
            </message_arguments>
229
        </filter>
230
    </resource>
231
    <resource path="dom/org/eclipse/jdt/core/dom/UnionType.java" type="org.eclipse.jdt.core.dom.UnionType">
232
        <filter comment="new APIs added for Java7 support post 3.7.0" id="1109393411">
233
            <message_arguments>
234
                <message_argument value="3.7.1"/>
235
                <message_argument value="org.eclipse.jdt.core.dom.UnionType"/>
236
            </message_arguments>
237
        </filter>
238
    </resource>
239
    <resource path="formatter/org/eclipse/jdt/core/formatter/DefaultCodeFormatterConstants.java" type="org.eclipse.jdt.core.formatter.DefaultCodeFormatterConstants">
240
        <filter comment="new APIs added for Java7 support post 3.7.0" id="1142947843">
241
            <message_arguments>
242
                <message_argument value="3.7.1"/>
243
                <message_argument value="FORMATTER_ALIGNMENT_FOR_RESOURCES_IN_TRY"/>
244
            </message_arguments>
245
        </filter>
246
        <filter comment="new APIs added for Java7 support post 3.7.0" id="1142947843">
247
            <message_arguments>
248
                <message_argument value="3.7.1"/>
249
                <message_argument value="FORMATTER_ALIGNMENT_FOR_UNION_TYPE_IN_MULTICATCH"/>
250
            </message_arguments>
251
        </filter>
252
        <filter comment="new APIs added for Java7 support post 3.7.0" id="1142947843">
253
            <message_arguments>
254
                <message_argument value="3.7.1"/>
255
                <message_argument value="FORMATTER_INSERT_SPACE_AFTER_OPENING_PAREN_IN_TRY"/>
256
            </message_arguments>
257
        </filter>
258
        <filter comment="new APIs added for Java7 support post 3.7.0" id="1142947843">
259
            <message_arguments>
260
                <message_argument value="3.7.1"/>
261
                <message_argument value="FORMATTER_INSERT_SPACE_AFTER_SEMICOLON_IN_TRY_RESOURCES"/>
262
            </message_arguments>
263
        </filter>
264
        <filter comment="new APIs added for Java7 support post 3.7.0" id="1142947843">
265
            <message_arguments>
266
                <message_argument value="3.7.1"/>
267
                <message_argument value="FORMATTER_INSERT_SPACE_BEFORE_CLOSING_PAREN_IN_TRY"/>
268
            </message_arguments>
269
        </filter>
270
        <filter comment="new APIs added for Java7 support post 3.7.0" id="1142947843">
271
            <message_arguments>
272
                <message_argument value="3.7.1"/>
273
                <message_argument value="FORMATTER_INSERT_SPACE_BEFORE_OPENING_PAREN_IN_TRY"/>
274
            </message_arguments>
275
        </filter>
276
        <filter comment="new APIs added for Java7 support post 3.7.0" id="1142947843">
277
            <message_arguments>
278
                <message_argument value="3.7.1"/>
279
                <message_argument value="FORMATTER_INSERT_SPACE_BEFORE_SEMICOLON_IN_TRY_RESOURCES"/>
280
            </message_arguments>
281
        </filter>
282
        <filter comment="new APIs added for Java7 support post 3.7.0" id="1142947843">
283
            <message_arguments>
284
                <message_argument value="3.7.1"/>
285
                <message_argument value="FORMATTER_WRAP_BEFORE_OR_OPERATOR_MULTICATCH"/>
286
            </message_arguments>
287
        </filter>
288
    </resource>
289
    <resource path="model/org/eclipse/jdt/core/BindingKey.java" type="org.eclipse.jdt.core.BindingKey">
290
        <filter comment="new APIs added for Java7 support post 3.7.0" id="1142947843">
291
            <message_arguments>
292
                <message_argument value="3.7.1"/>
293
                <message_argument value="getDeclaringType()"/>
294
            </message_arguments>
295
        </filter>
296
    </resource>
297
    <resource path="model/org/eclipse/jdt/core/CompletionProposal.java" type="org.eclipse.jdt.core.CompletionProposal">
298
        <filter comment="new APIs added for Java7 support post 3.7.0" id="1142947843">
299
            <message_arguments>
300
                <message_argument value="3.7.1"/>
301
                <message_argument value="canUseDiamond(CompletionContext)"/>
302
            </message_arguments>
303
        </filter>
304
    </resource>
305
    <resource path="model/org/eclipse/jdt/core/JavaCore.java" type="org.eclipse.jdt.core.JavaCore">
306
        <filter comment="new APIs added for Java7 support post 3.7.0" id="1142947843">
307
            <message_arguments>
308
                <message_argument value="3.7.1"/>
309
                <message_argument value="COMPILER_PB_REDUNDANT_TYPE_ARGUMENTS"/>
310
            </message_arguments>
311
        </filter>
312
    </resource>
313
    <resource path="model/org/eclipse/jdt/core/Signature.java" type="org.eclipse.jdt.core.Signature">
314
        <filter comment="new APIs added for Java7 support post 3.7.0" id="1142947843">
315
            <message_arguments>
316
                <message_argument value="3.7.1"/>
317
                <message_argument value="C_INTERSECTION"/>
318
            </message_arguments>
319
        </filter>
320
        <filter comment="new APIs added for Java7 support post 3.7.0" id="1142947843">
321
            <message_arguments>
322
                <message_argument value="3.7.1"/>
323
                <message_argument value="INTERSECTION_TYPE_SIGNATURE"/>
324
            </message_arguments>
325
        </filter>
326
        <filter comment="new APIs added for Java7 support post 3.7.0" id="1142947843">
327
            <message_arguments>
328
                <message_argument value="3.7.1"/>
329
                <message_argument value="createIntersectionTypeSignature(String[])"/>
330
            </message_arguments>
331
        </filter>
332
        <filter comment="new APIs added for Java7 support post 3.7.0" id="1142947843">
333
            <message_arguments>
334
                <message_argument value="3.7.1"/>
335
                <message_argument value="createIntersectionTypeSignature(char[][])"/>
336
            </message_arguments>
337
        </filter>
338
        <filter comment="new APIs added for Java7 support post 3.7.0" id="1142947843">
339
            <message_arguments>
340
                <message_argument value="3.7.1"/>
341
                <message_argument value="getIntersectionTypeBounds(String)"/>
342
            </message_arguments>
343
        </filter>
344
        <filter comment="new APIs added for Java7 support post 3.7.0" id="1142947843">
345
            <message_arguments>
346
                <message_argument value="3.7.1"/>
347
                <message_argument value="getIntersectionTypeBounds(char[])"/>
348
            </message_arguments>
349
        </filter>
350
    </resource>
351
    <resource path="model/org/eclipse/jdt/core/compiler/ReconcileContext.java" type="org.eclipse.jdt.core.compiler.ReconcileContext">
352
        <filter comment="new APIs added for Java7 support post 3.7.0" id="1142947843">
353
            <message_arguments>
354
                <message_argument value="3.7.1"/>
355
                <message_argument value="getAST4()"/>
356
            </message_arguments>
357
        </filter>
358
    </resource>
359
</component>
(-)a/org.eclipse.jdt.core/.settings/org.eclipse.core.runtime.prefs (+2 lines)
Added Link Here
1
eclipse.preferences.version=1
2
line.separator=\n
(-)a/org.eclipse.jdt.core/META-INF/MANIFEST.MF (-1 / +2 lines)
Lines 3-9 Link Here
3
Bundle-ManifestVersion: 2
3
Bundle-ManifestVersion: 2
4
Bundle-Name: %pluginName
4
Bundle-Name: %pluginName
5
Bundle-SymbolicName: org.eclipse.jdt.core; singleton:=true
5
Bundle-SymbolicName: org.eclipse.jdt.core; singleton:=true
6
Bundle-Version: 3.8.0.qualifier
6
Bundle-Version: 3.8.1.qualifier
7
Bundle-Activator: org.eclipse.jdt.core.JavaCore
7
Bundle-Activator: org.eclipse.jdt.core.JavaCore
8
Bundle-Vendor: %providerName
8
Bundle-Vendor: %providerName
9
Bundle-Localization: plugin
9
Bundle-Localization: plugin
Lines 17-22 Link Here
17
 org.eclipse.jdt.core.jdom,
17
 org.eclipse.jdt.core.jdom,
18
 org.eclipse.jdt.core.search,
18
 org.eclipse.jdt.core.search,
19
 org.eclipse.jdt.core.util,
19
 org.eclipse.jdt.core.util,
20
 org.eclipse.jdt.core.index,
20
 org.eclipse.jdt.internal.codeassist;x-internal:=true,
21
 org.eclipse.jdt.internal.codeassist;x-internal:=true,
21
 org.eclipse.jdt.internal.codeassist.complete;x-internal:=true,
22
 org.eclipse.jdt.internal.codeassist.complete;x-internal:=true,
22
 org.eclipse.jdt.internal.codeassist.impl;x-internal:=true,
23
 org.eclipse.jdt.internal.codeassist.impl;x-internal:=true,
(-)a/org.eclipse.jdt.core/antadapter/org/eclipse/jdt/core/BuildJarIndex.java (+62 lines)
Added Link Here
1
/*******************************************************************************
2
 * Copyright (c) 2011 IBM Corporation and others.
3
 * All rights reserved. This program and the accompanying materials
4
 * are made available under the terms of the Eclipse Public License v1.0
5
 * which accompanies this distribution, and is available at
6
 * http://www.eclipse.org/legal/epl-v10.html
7
 *
8
 * Contributors:
9
 *     IBM Corporation - initial API and implementation
10
 *******************************************************************************/
11
package org.eclipse.jdt.core;
12
13
import java.io.IOException;
14
15
import org.apache.tools.ant.BuildException;
16
import org.apache.tools.ant.Task;
17
import org.eclipse.jdt.core.index.JavaIndexer;
18
import org.eclipse.jdt.internal.antadapter.AntAdapterMessages;
19
20
/**
21
 * <p>
22
 * An Ant task to generate the index file for the given jar path.
23
 * </p>
24
 * <p>
25
 * <code>&lt;eclipse.buildJarIndex jarPath="Test.jar" indexPath="Test.index"/&gt;</code>
26
 * </p>
27
 * <p>
28
 * For more information on Ant check out the website at http://jakarta.apache.org/ant/ .
29
 * </p>
30
 * <p>
31
 * This is not intended to be subclassed by users.
32
 * </p>
33
 * @since 3.8
34
 */
35
public class BuildJarIndex extends Task {
36
37
	private String jarPath;
38
	private String indexPath;
39
40
	public void execute() throws BuildException {
41
		if (this.jarPath == null) {
42
			throw new BuildException(AntAdapterMessages.getString("buildJarIndex.jarFile.cannot.be.null")); //$NON-NLS-1$
43
		}
44
		if (this.indexPath == null) {
45
			throw new BuildException(AntAdapterMessages.getString("buildJarIndex.indexFile.cannot.be.null")); //$NON-NLS-1$
46
		}
47
48
		try {
49
			JavaIndexer.generateIndexForJar(this.jarPath, this.indexPath);
50
		} catch (IOException e) {
51
			throw new BuildException(AntAdapterMessages.getString("buildJarIndex.ioexception.occured", e.getLocalizedMessage())); //$NON-NLS-1$
52
		}
53
	}
54
55
	public void setJarPath(String path) {
56
		this.jarPath = path;
57
	}
58
59
	public void setIndexPath(String path) {
60
		this.indexPath = path;
61
	}
62
}
(-)a/org.eclipse.jdt.core/antadapter/org/eclipse/jdt/internal/antadapter/messages.properties (-1 / +5 lines)
Lines 1-5 Link Here
1
###############################################################################
1
###############################################################################
2
# Copyright (c) 2000, 2006 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 19-21 Link Here
19
checkDebugAttributes.property.argument.cannot.be.null=The property argument cannot be null
19
checkDebugAttributes.property.argument.cannot.be.null=The property argument cannot be null
20
checkDebugAttributes.ioexception.occured=IOException occurred while reading 
20
checkDebugAttributes.ioexception.occured=IOException occurred while reading 
21
checkDebugAttributes.file.argument.must.be.a.classfile.or.a.jarfile=The file argument must be a .class or a .jar file
21
checkDebugAttributes.file.argument.must.be.a.classfile.or.a.jarfile=The file argument must be a .class or a .jar file
22
23
buildJarIndex.jarFile.cannot.be.null=The jar file argument cannot be null
24
buildJarIndex.indexFile.cannot.be.null=The index file argument cannot be null
25
buildJarIndex.ioexception.occured=IOException - {0}
(-)a/org.eclipse.jdt.core/batch/org/eclipse/jdt/core/compiler/batch/package.html (+16 lines)
Added Link Here
1
<!doctype html public "-//w3c//dtd html 4.0 transitional//en">
2
<html>
3
<head>
4
   <meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1">
5
   <meta name="Author" content="IBM">
6
   <meta name="GENERATOR" content="Mozilla/4.73 [en] (Windows NT 5.0; U) [Netscape]">
7
   <title>Package-level Javadoc</title>
8
</head>
9
<body>
10
This package contains the batch compiler API.
11
<h2>
12
Package Specification</h2>
13
14
<p><br>This package contains the batch compiler API.
15
</body>
16
</html>
(-)a/org.eclipse.jdt.core/batch/org/eclipse/jdt/internal/compiler/batch/CompilationUnit.java (-1 / +10 lines)
Lines 1-5 Link Here
1
/*******************************************************************************
1
/*******************************************************************************
2
 * Copyright (c) 2000, 2009 IBM Corporation and others.
2
 * Copyright (c) 2000, 2012 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 31-42 Link Here
31
		// == Main.NONE: absorbent element, do not output class files;
31
		// == Main.NONE: absorbent element, do not output class files;
32
		// else: use as the path of the directory into which class files must
32
		// else: use as the path of the directory into which class files must
33
		//       be written.
33
		//       be written.
34
	private boolean ignoreOptionalProblems;
34
35
35
public CompilationUnit(char[] contents, String fileName, String encoding) {
36
public CompilationUnit(char[] contents, String fileName, String encoding) {
36
	this(contents, fileName, encoding, null);
37
	this(contents, fileName, encoding, null);
37
}
38
}
38
public CompilationUnit(char[] contents, String fileName, String encoding,
39
public CompilationUnit(char[] contents, String fileName, String encoding,
39
		String destinationPath) {
40
		String destinationPath) {
41
	this(contents, fileName, encoding, destinationPath, false);
42
}
43
public CompilationUnit(char[] contents, String fileName, String encoding,
44
		String destinationPath, boolean ignoreOptionalProblems) {
40
	this.contents = contents;
45
	this.contents = contents;
41
	char[] fileNameCharArray = fileName.toCharArray();
46
	char[] fileNameCharArray = fileName.toCharArray();
42
	switch(File.separatorChar) {
47
	switch(File.separatorChar) {
Lines 61-66 Link Here
61
	this.mainTypeName = CharOperation.subarray(fileNameCharArray, start, end);
66
	this.mainTypeName = CharOperation.subarray(fileNameCharArray, start, end);
62
	this.encoding = encoding;
67
	this.encoding = encoding;
63
	this.destinationPath = destinationPath;
68
	this.destinationPath = destinationPath;
69
	this.ignoreOptionalProblems = ignoreOptionalProblems;
64
}
70
}
65
public char[] getContents() {
71
public char[] getContents() {
66
	if (this.contents != null)
72
	if (this.contents != null)
Lines 86-91 Link Here
86
public char[][] getPackageName() {
92
public char[][] getPackageName() {
87
	return null;
93
	return null;
88
}
94
}
95
public boolean ignoreOptionalProblems() {
96
	return this.ignoreOptionalProblems;
97
}
89
public String toString() {
98
public String toString() {
90
	return "CompilationUnit[" + new String(this.fileName) + "]";  //$NON-NLS-2$ //$NON-NLS-1$
99
	return "CompilationUnit[" + new String(this.fileName) + "]";  //$NON-NLS-2$ //$NON-NLS-1$
91
}
100
}
(-)a/org.eclipse.jdt.core/batch/org/eclipse/jdt/internal/compiler/batch/Main.java (-55 / +186 lines)
Lines 1-5 Link Here
1
/*******************************************************************************
1
/*******************************************************************************
2
 * Copyright (c) 2000, 2011 IBM Corporation and others.
2
 * Copyright (c) 2000, 2012 IBM Corporation and others.
3
 * All rights reserved. This program and the accompanying materials
3
 * All rights reserved. This program and the accompanying materials
4
 * are made available under the terms of the Eclipse Public License v1.0
4
 * are made available under the terms of the Eclipse Public License v1.0
5
 * which accompanies this distribution, and is available at
5
 * which accompanies this distribution, and is available at
Lines 10-17 Link Here
10
 *     Tom Tromey - Contribution for bug 125961
10
 *     Tom Tromey - Contribution for bug 125961
11
 *     Tom Tromey - Contribution for bug 159641
11
 *     Tom Tromey - Contribution for bug 159641
12
 *     Benjamin Muskalla - Contribution for bug 239066
12
 *     Benjamin Muskalla - Contribution for bug 239066
13
 *     Stephan Herrmann  - Contribution for bug 236385
13
 *     Stephan Herrmann  - Contributions for 
14
 *     Stephan Herrmann  - Contribution for bug 295551
14
 *     							bug 236385 - [compiler] Warn for potential programming problem if an object is created but not used
15
 *     							bug 295551 - Add option to automatically promote all warnings to errors
16
 *     							bug 359721 - [options] add command line option for new warning token "resource"
17
 *								bug 365208 - [compiler][batch] command line options for annotation based null analysis
15
 *******************************************************************************/
18
 *******************************************************************************/
16
package org.eclipse.jdt.internal.compiler.batch;
19
package org.eclipse.jdt.internal.compiler.batch;
17
20
Lines 1320-1325 Link Here
1320
	public Logger logger;
1323
	public Logger logger;
1321
	public int maxProblems;
1324
	public int maxProblems;
1322
	public Map options;
1325
	public Map options;
1326
	public char[][] ignoreOptionalProblemsFromFolders;
1323
	protected PrintWriter out;
1327
	protected PrintWriter out;
1324
	public boolean proceed = true;
1328
	public boolean proceed = true;
1325
	public boolean proceedOnError = false;
1329
	public boolean proceedOnError = false;
Lines 1836-1841 Link Here
1836
1840
1837
		switch(mode) {
1841
		switch(mode) {
1838
			case DEFAULT :
1842
			case DEFAULT :
1843
				if (currentArg.startsWith("-nowarn")) { //$NON-NLS-1$
1844
					switch (currentArg.length()) {
1845
						case 7:
1846
							disableAll(ProblemSeverities.Warning);
1847
							break;
1848
						case 8:
1849
							throw new IllegalArgumentException(this.bind(
1850
									"configure.invalidNowarnOption", currentArg)); //$NON-NLS-1$
1851
						default:
1852
							int foldersStart = currentArg.indexOf('[') + 1;
1853
							int foldersEnd = currentArg.lastIndexOf(']');
1854
							if (foldersStart <= 8 || foldersEnd == -1 || foldersStart > foldersEnd
1855
									|| foldersEnd < currentArg.length() - 1) {
1856
								throw new IllegalArgumentException(this.bind(
1857
										"configure.invalidNowarnOption", currentArg)); //$NON-NLS-1$
1858
							}
1859
							String folders = currentArg.substring(foldersStart, foldersEnd);
1860
							if (folders.length() > 0) {
1861
								char[][] currentFolders = decodeIgnoreOptionalProblemsFromFolders(folders);
1862
								if (this.ignoreOptionalProblemsFromFolders != null) {
1863
									int length = this.ignoreOptionalProblemsFromFolders.length + currentFolders.length;
1864
									char[][] tempFolders = new char[length][];
1865
									System.arraycopy(this.ignoreOptionalProblemsFromFolders, 0, tempFolders, 0, this.ignoreOptionalProblemsFromFolders.length);
1866
									System.arraycopy(currentFolders, 0, tempFolders, this.ignoreOptionalProblemsFromFolders.length, currentFolders.length);
1867
									this.ignoreOptionalProblemsFromFolders = tempFolders;
1868
								} else {
1869
									this.ignoreOptionalProblemsFromFolders = currentFolders;
1870
								}
1871
							} else {
1872
								throw new IllegalArgumentException(this.bind(
1873
										"configure.invalidNowarnOption", currentArg)); //$NON-NLS-1$
1874
							}
1875
					}
1876
					mode = DEFAULT;
1877
					continue;
1878
				}
1839
				if (currentArg.startsWith("[")) { //$NON-NLS-1$
1879
				if (currentArg.startsWith("[")) { //$NON-NLS-1$
1840
					throw new IllegalArgumentException(
1880
					throw new IllegalArgumentException(
1841
						this.bind("configure.unexpectedBracket", //$NON-NLS-1$
1881
						this.bind("configure.unexpectedBracket", //$NON-NLS-1$
Lines 2186-2202 Link Here
2186
					throw new IllegalArgumentException(
2226
					throw new IllegalArgumentException(
2187
						this.bind("configure.invalidDebugOption", debugOption)); //$NON-NLS-1$
2227
						this.bind("configure.invalidDebugOption", debugOption)); //$NON-NLS-1$
2188
				}
2228
				}
2189
				if (currentArg.startsWith("-nowarn")) { //$NON-NLS-1$
2190
					disableWarnings();
2191
					mode = DEFAULT;
2192
					continue;
2193
				}
2194
				if (currentArg.startsWith("-warn")) { //$NON-NLS-1$
2229
				if (currentArg.startsWith("-warn")) { //$NON-NLS-1$
2195
					mode = DEFAULT;
2230
					mode = DEFAULT;
2196
					String warningOption = currentArg;
2231
					String warningOption = currentArg;
2197
					int length = currentArg.length();
2232
					int length = currentArg.length();
2198
					if (length == 10 && warningOption.equals("-warn:" + NONE)) { //$NON-NLS-1$
2233
					if (length == 10 && warningOption.equals("-warn:" + NONE)) { //$NON-NLS-1$
2199
						disableWarnings();
2234
						disableAll(ProblemSeverities.Warning);
2200
						continue;
2235
						continue;
2201
					}
2236
					}
2202
					if (length <= 6) {
2237
					if (length <= 6) {
Lines 2204-2226 Link Here
2204
							this.bind("configure.invalidWarningConfiguration", warningOption)); //$NON-NLS-1$
2239
							this.bind("configure.invalidWarningConfiguration", warningOption)); //$NON-NLS-1$
2205
					}
2240
					}
2206
					int warnTokenStart;
2241
					int warnTokenStart;
2207
					boolean isEnabling, allowPlusOrMinus;
2242
					boolean isEnabling;
2208
					switch (warningOption.charAt(6)) {
2243
					switch (warningOption.charAt(6)) {
2209
						case '+' :
2244
						case '+' :
2210
							warnTokenStart = 7;
2245
							warnTokenStart = 7;
2211
							isEnabling = true;
2246
							isEnabling = true;
2212
							allowPlusOrMinus = true;
2213
							break;
2247
							break;
2214
						case '-' :
2248
						case '-' :
2215
							warnTokenStart = 7;
2249
							warnTokenStart = 7;
2216
							isEnabling = false; // specified warnings are disabled
2250
							isEnabling = false; // specified warnings are disabled
2217
							allowPlusOrMinus = true;
2218
							break;
2251
							break;
2219
						default:
2252
						default:
2220
							disableWarnings();
2253
							disableAll(ProblemSeverities.Warning);
2221
							warnTokenStart = 6;
2254
							warnTokenStart = 6;
2222
							isEnabling = true;
2255
							isEnabling = true;
2223
							allowPlusOrMinus = false;
2224
					}
2256
					}
2225
2257
2226
					StringTokenizer tokenizer =
2258
					StringTokenizer tokenizer =
Lines 2236-2257 Link Here
2236
						tokenCounter++;
2268
						tokenCounter++;
2237
						switch(token.charAt(0)) {
2269
						switch(token.charAt(0)) {
2238
							case '+' :
2270
							case '+' :
2239
								if (allowPlusOrMinus) {
2271
								isEnabling = true;
2240
									isEnabling = true;
2272
								token = token.substring(1);
2241
									token = token.substring(1);
2242
								} else {
2243
									throw new IllegalArgumentException(
2244
											this.bind("configure.invalidUsageOfPlusOption", token)); //$NON-NLS-1$
2245
								}
2246
								break;
2273
								break;
2247
							case '-' :
2274
							case '-' :
2248
								if (allowPlusOrMinus) {
2275
								isEnabling = false;
2249
									isEnabling = false;
2276
								token = token.substring(1);
2250
									token = token.substring(1);
2251
								} else {
2252
									throw new IllegalArgumentException(
2253
											this.bind("configure.invalidUsageOfMinusOption", token)); //$NON-NLS-1$
2254
								}
2255
						}
2277
						}
2256
						handleWarningToken(token, isEnabling);
2278
						handleWarningToken(token, isEnabling);
2257
					}
2279
					}
Lines 2270-2292 Link Here
2270
							this.bind("configure.invalidErrorConfiguration", errorOption)); //$NON-NLS-1$
2292
							this.bind("configure.invalidErrorConfiguration", errorOption)); //$NON-NLS-1$
2271
					}
2293
					}
2272
					int errorTokenStart;
2294
					int errorTokenStart;
2273
					boolean isEnabling, allowPlusOrMinus;
2295
					boolean isEnabling;
2274
					switch (errorOption.charAt(5)) {
2296
					switch (errorOption.charAt(5)) {
2275
						case '+' :
2297
						case '+' :
2276
							errorTokenStart = 6;
2298
							errorTokenStart = 6;
2277
							isEnabling = true;
2299
							isEnabling = true;
2278
							allowPlusOrMinus = true;
2279
							break;
2300
							break;
2280
						case '-' :
2301
						case '-' :
2281
							errorTokenStart = 6;
2302
							errorTokenStart = 6;
2282
							isEnabling = false; // specified errors are disabled
2303
							isEnabling = false; // specified errors are disabled
2283
							allowPlusOrMinus = true;
2284
							break;
2304
							break;
2285
						default:
2305
						default:
2286
							disableErrors();
2306
							disableAll(ProblemSeverities.Error);
2287
							errorTokenStart = 5;
2307
							errorTokenStart = 5;
2288
							isEnabling = true;
2308
							isEnabling = true;
2289
							allowPlusOrMinus = false;
2290
					}
2309
					}
2291
2310
2292
					StringTokenizer tokenizer =
2311
					StringTokenizer tokenizer =
Lines 2298-2319 Link Here
2298
						tokenCounter++;
2317
						tokenCounter++;
2299
						switch(token.charAt(0)) {
2318
						switch(token.charAt(0)) {
2300
							case '+' :
2319
							case '+' :
2301
								if (allowPlusOrMinus) {
2320
								isEnabling = true;
2302
									isEnabling = true;
2321
								token = token.substring(1);
2303
									token = token.substring(1);
2304
								} else {
2305
									throw new IllegalArgumentException(
2306
											this.bind("configure.invalidUsageOfPlusOption", token)); //$NON-NLS-1$
2307
								}
2308
								break;
2322
								break;
2309
							case '-' :
2323
							case '-' :
2310
								if (allowPlusOrMinus) {
2324
								isEnabling = false;
2311
									isEnabling = false;
2325
								token = token.substring(1);
2312
									token = token.substring(1);
2313
								} else {
2314
									throw new IllegalArgumentException(
2315
											this.bind("configure.invalidUsageOfMinusOption", token)); //$NON-NLS-1$
2316
								}
2317
								break;
2326
								break;
2318
						}
2327
						}
2319
						handleErrorToken(token, isEnabling);
2328
						handleErrorToken(token, isEnabling);
Lines 2401-2406 Link Here
2401
				}
2410
				}
2402
				if (currentArg.equals("-properties")) { //$NON-NLS-1$
2411
				if (currentArg.equals("-properties")) { //$NON-NLS-1$
2403
					mode = INSIDE_WARNINGS_PROPERTIES;
2412
					mode = INSIDE_WARNINGS_PROPERTIES;
2413
					continue;
2414
				}
2415
				if (currentArg.equals("-nonNullByDefault")) { //$NON-NLS-1$
2416
					this.options.put(CompilerOptions.OPTION_NonNullIsDefault, CompilerOptions.ENABLED);
2404
					continue;
2417
					continue;
2405
				}
2418
				}
2406
				break;
2419
				break;
Lines 2778-2783 Link Here
2778
		this.pendingErrors = null;
2791
		this.pendingErrors = null;
2779
	}
2792
	}
2780
}
2793
}
2794
2795
private static char[][] decodeIgnoreOptionalProblemsFromFolders(String folders) {
2796
	StringTokenizer tokenizer = new StringTokenizer(folders, File.pathSeparator);
2797
	char[][] result = new char[tokenizer.countTokens()][];
2798
	int count = 0;
2799
	while (tokenizer.hasMoreTokens()) {
2800
		String fileName = tokenizer.nextToken();
2801
		// relative folder names are created relative to the current user dir
2802
		File file = new File(fileName);
2803
		if (file.exists()) {
2804
			// if the file exists, we should try to use its canonical path
2805
			try {
2806
				result[count++] = file.getCanonicalPath().toCharArray();
2807
			} catch (IOException e) {
2808
				// if we got exception during canonicalization, fall back to the name that was specified
2809
				result[count++] = fileName.toCharArray();
2810
			}
2811
		} else {
2812
			// if the file does not exist, use the name that was specified
2813
			result[count++] = fileName.toCharArray();
2814
		}
2815
	}
2816
	return result;
2817
}
2818
2781
private static String getAllEncodings(Set encodings) {
2819
private static String getAllEncodings(Set encodings) {
2782
	int size = encodings.size();
2820
	int size = encodings.size();
2783
	String[] allEncodings = new String[size];
2821
	String[] allEncodings = new String[size];
Lines 2824-2830 Link Here
2824
		}
2862
		}
2825
	}
2863
	}
2826
}
2864
}
2827
protected void disableWarnings() {
2865
protected void enableAll(int severity) {
2866
	String newValue = null;
2867
	switch(severity) {
2868
		case ProblemSeverities.Error :
2869
			newValue = CompilerOptions.ERROR;
2870
			break;
2871
		case ProblemSeverities.Warning :
2872
			newValue = CompilerOptions.WARNING;
2873
			break;
2874
	}
2828
	Object[] entries = this.options.entrySet().toArray();
2875
	Object[] entries = this.options.entrySet().toArray();
2829
	for (int i = 0, max = entries.length; i < max; i++) {
2876
	for (int i = 0, max = entries.length; i < max; i++) {
2830
		Map.Entry entry = (Map.Entry) entries[i];
2877
		Map.Entry entry = (Map.Entry) entries[i];
Lines 2832-2844 Link Here
2832
			continue;
2879
			continue;
2833
		if (!(entry.getValue() instanceof String))
2880
		if (!(entry.getValue() instanceof String))
2834
			continue;
2881
			continue;
2835
		if (((String) entry.getValue()).equals(CompilerOptions.WARNING)) {
2882
		if (((String) entry.getValue()).equals(CompilerOptions.IGNORE)) {
2836
			this.options.put(entry.getKey(), CompilerOptions.IGNORE);
2883
			this.options.put(entry.getKey(), newValue);
2837
		}
2884
		}
2838
	}
2885
	}
2839
	this.options.put(CompilerOptions.OPTION_TaskTags, Util.EMPTY_STRING);
2886
	this.options.put(CompilerOptions.OPTION_TaskTags, Util.EMPTY_STRING);
2840
}
2887
}
2841
protected void disableErrors() {
2888
protected void disableAll(int severity) {
2889
	String checkedValue = null;
2890
	switch(severity) {
2891
		case ProblemSeverities.Error :
2892
			checkedValue = CompilerOptions.ERROR;
2893
			break;
2894
		case ProblemSeverities.Warning :
2895
			checkedValue = CompilerOptions.WARNING;
2896
			break;
2897
	}
2842
	Object[] entries = this.options.entrySet().toArray();
2898
	Object[] entries = this.options.entrySet().toArray();
2843
	for (int i = 0, max = entries.length; i < max; i++) {
2899
	for (int i = 0, max = entries.length; i < max; i++) {
2844
		Map.Entry entry = (Map.Entry) entries[i];
2900
		Map.Entry entry = (Map.Entry) entries[i];
Lines 2846-2852 Link Here
2846
			continue;
2902
			continue;
2847
		if (!(entry.getValue() instanceof String))
2903
		if (!(entry.getValue() instanceof String))
2848
			continue;
2904
			continue;
2849
		if (((String) entry.getValue()).equals(CompilerOptions.ERROR)) {
2905
		if (((String) entry.getValue()).equals(checkedValue)) {
2850
			this.options.put(entry.getKey(), CompilerOptions.IGNORE);
2906
			this.options.put(entry.getKey(), CompilerOptions.IGNORE);
2851
		}
2907
		}
2852
	}
2908
	}
Lines 2914-2921 Link Here
2914
		String encoding = this.encodings[i];
2970
		String encoding = this.encodings[i];
2915
		if (encoding == null)
2971
		if (encoding == null)
2916
			encoding = defaultEncoding;
2972
			encoding = defaultEncoding;
2917
		units[i] = new CompilationUnit(null, this.filenames[i], encoding,
2973
		String fileName;
2918
				this.destinationPaths[i]);
2974
		try {
2975
			fileName = file.getCanonicalPath();
2976
		} catch (IOException e) {
2977
			// if we got exception during canonicalization, fall back to the name that was specified
2978
			fileName = this.filenames[i];
2979
		}
2980
		units[i] = new CompilationUnit(null, fileName, encoding, this.destinationPaths[i],
2981
				shouldIgnoreOptionalProblems(this.ignoreOptionalProblemsFromFolders, fileName.toCharArray()));
2919
	}
2982
	}
2920
	return units;
2983
	return units;
2921
}
2984
}
Lines 3251-3256 Link Here
3251
				setSeverity(CompilerOptions.OPTION_ReportMethodCanBeStatic, severity, isEnabling);
3314
				setSeverity(CompilerOptions.OPTION_ReportMethodCanBeStatic, severity, isEnabling);
3252
				setSeverity(CompilerOptions.OPTION_ReportMethodCanBePotentiallyStatic, severity, isEnabling);
3315
				setSeverity(CompilerOptions.OPTION_ReportMethodCanBePotentiallyStatic, severity, isEnabling);
3253
				return;
3316
				return;
3317
			} else if (token.equals("all")) { //$NON-NLS-1$
3318
				if (isEnabling) {
3319
					enableAll(severity);
3320
				} else {
3321
					disableAll(severity);
3322
				}
3323
				return;
3254
			}
3324
			}
3255
			break;
3325
			break;
3256
		case 'b' :
3326
		case 'b' :
Lines 3403-3409 Link Here
3403
					setSeverity(CompilerOptions.OPTION_ReportRedundantNullCheck, ProblemSeverities.Ignore, isEnabling);
3473
					setSeverity(CompilerOptions.OPTION_ReportRedundantNullCheck, ProblemSeverities.Ignore, isEnabling);
3404
				}
3474
				}
3405
				return;
3475
				return;
3476
			} else if (token.startsWith("nullAnnot")) { //$NON-NLS-1$
3477
				String annotationNames = Util.EMPTY_STRING;
3478
				int start = token.indexOf('(');
3479
				int end = token.indexOf(')');
3480
				String nonNullAnnotName = null, nullableAnnotName = null, nonNullByDefaultAnnotName = null;
3481
				if (isEnabling && start >= 0 && end >= 0 && start < end){
3482
					annotationNames = token.substring(start+1, end).trim();
3483
					int separator1 = annotationNames.indexOf('|');
3484
					if (separator1 == -1) throw new IllegalArgumentException(this.bind("configure.invalidNullAnnot", token)); //$NON-NLS-1$
3485
					nullableAnnotName = annotationNames.substring(0, separator1).trim();
3486
					if (nullableAnnotName.length() == 0) throw new IllegalArgumentException(this.bind("configure.invalidNullAnnot", token)); //$NON-NLS-1$
3487
					int separator2 = annotationNames.indexOf('|', separator1 + 1);
3488
					if (separator2 == -1) throw new IllegalArgumentException(this.bind("configure.invalidNullAnnot", token)); //$NON-NLS-1$
3489
					nonNullAnnotName = annotationNames.substring(separator1 + 1, separator2).trim();
3490
					if (nonNullAnnotName.length() == 0) throw new IllegalArgumentException(this.bind("configure.invalidNullAnnot", token)); //$NON-NLS-1$
3491
					nonNullByDefaultAnnotName = annotationNames.substring(separator2 + 1).trim();
3492
					if (nonNullByDefaultAnnotName.length() == 0) throw new IllegalArgumentException(this.bind("configure.invalidNullAnnot", token)); //$NON-NLS-1$
3493
					this.options.put(CompilerOptions.OPTION_NullableAnnotationName, nullableAnnotName);
3494
					this.options.put(CompilerOptions.OPTION_NonNullAnnotationName, nonNullAnnotName);
3495
					this.options.put(CompilerOptions.OPTION_NonNullByDefaultAnnotationName, nonNullByDefaultAnnotName);
3496
				}
3497
				this.options.put(
3498
						CompilerOptions.OPTION_AnnotationBasedNullAnalysis,
3499
						isEnabling ? CompilerOptions.ENABLED : CompilerOptions.DISABLED);
3500
				setSeverity(CompilerOptions.OPTION_ReportNullSpecViolation, severity, isEnabling);
3501
				setSeverity(CompilerOptions.OPTION_ReportPotentialNullSpecViolation, severity, isEnabling);
3502
				setSeverity(CompilerOptions.OPTION_ReportNullSpecInsufficientInfo, severity, isEnabling);
3503
				setSeverity(CompilerOptions.OPTION_ReportRedundantNullAnnotation, severity, isEnabling);
3504
				return;
3406
			}
3505
			}
3506
			
3407
			break;
3507
			break;
3408
		case 'o' :
3508
		case 'o' :
3409
			if (token.equals("over-sync") /*|| token.equals("syncOverride")*/) { //$NON-NLS-1$ 
3509
			if (token.equals("over-sync") /*|| token.equals("syncOverride")*/) { //$NON-NLS-1$ 
Lines 3432-3437 Link Here
3432
				return;
3532
				return;
3433
			} else if (/*token.equals("intfRedundant") ||*/ token.equals("redundantSuperinterface")) { //$NON-NLS-1$
3533
			} else if (/*token.equals("intfRedundant") ||*/ token.equals("redundantSuperinterface")) { //$NON-NLS-1$
3434
				setSeverity(CompilerOptions.OPTION_ReportRedundantSuperinterface, severity, isEnabling);
3534
				setSeverity(CompilerOptions.OPTION_ReportRedundantSuperinterface, severity, isEnabling);
3535
				return;
3536
			} else if (token.equals("resource")) { //$NON-NLS-1$
3537
				setSeverity(CompilerOptions.OPTION_ReportUnclosedCloseable, severity, isEnabling);
3538
				setSeverity(CompilerOptions.OPTION_ReportPotentiallyUnclosedCloseable, severity, isEnabling);
3539
				setSeverity(CompilerOptions.OPTION_ReportExplicitlyClosedAutoCloseable, severity, isEnabling);
3435
				return;
3540
				return;
3436
			}
3541
			}
3437
			break;
3542
			break;
Lines 3610-3615 Link Here
3610
	this.err = errWriter;
3715
	this.err = errWriter;
3611
	this.systemExitWhenFinished = systemExit;
3716
	this.systemExitWhenFinished = systemExit;
3612
	this.options = new CompilerOptions().getMap();
3717
	this.options = new CompilerOptions().getMap();
3718
	this.ignoreOptionalProblemsFromFolders = null;
3613
3719
3614
	this.progress = compilationProgress;
3720
	this.progress = compilationProgress;
3615
	if (customDefaultOptions != null) {
3721
	if (customDefaultOptions != null) {
Lines 3646-3652 Link Here
3646
		this.logger.logIncorrectVMVersionForAnnotationProcessing();
3752
		this.logger.logIncorrectVMVersionForAnnotationProcessing();
3647
	}
3753
	}
3648
}
3754
}
3649
3755
private static boolean isParentOf(char[] folderName, char[] fileName) {
3756
	if (folderName.length >= fileName.length) {
3757
		return false;
3758
	}
3759
	if (fileName[folderName.length] != '\\' && fileName[folderName.length] != '/') {
3760
		return false;
3761
	}
3762
	for (int i = folderName.length - 1; i >= 0; i--) {
3763
		if (folderName[i] != fileName[i]) {
3764
			return false;
3765
		}
3766
	}
3767
	return true;
3768
}
3650
// Dump classfiles onto disk for all compilation units that where successful
3769
// Dump classfiles onto disk for all compilation units that where successful
3651
// and do not carry a -d none spec, either directly or inherited from Main.
3770
// and do not carry a -d none spec, either directly or inherited from Main.
3652
public void outputClassFiles(CompilationResult unitResult) {
3771
public void outputClassFiles(CompilationResult unitResult) {
Lines 4192-4197 Link Here
4192
	classpaths.toArray(this.checkedClasspaths);
4311
	classpaths.toArray(this.checkedClasspaths);
4193
	this.logger.logClasspath(this.checkedClasspaths);
4312
	this.logger.logClasspath(this.checkedClasspaths);
4194
}
4313
}
4314
private static boolean shouldIgnoreOptionalProblems(char[][] folderNames, char[] fileName) {
4315
	if (folderNames == null || fileName == null) {
4316
		return false;
4317
	}
4318
	for (int i = 0, max = folderNames.length; i < max; i++) {
4319
		char[] folderName = folderNames[i];
4320
		if (isParentOf(folderName, fileName)) {
4321
			return true;
4322
		}
4323
	}
4324
	return false;
4325
}
4195
protected void validateOptions(boolean didSpecifyCompliance) {
4326
protected void validateOptions(boolean didSpecifyCompliance) {
4196
	if (didSpecifyCompliance) {
4327
	if (didSpecifyCompliance) {
4197
		Object version = this.options.get(CompilerOptions.OPTION_Compliance);
4328
		Object version = this.options.get(CompilerOptions.OPTION_Compliance);
(-)a/org.eclipse.jdt.core/batch/org/eclipse/jdt/internal/compiler/batch/messages.properties (-4 / +24 lines)
Lines 1-5 Link Here
1
###############################################################################
1
###############################################################################
2
# Copyright (c) 2000, 2011 IBM Corporation and others.
2
# Copyright (c) 2000, 2012 IBM Corporation and others.
3
# All rights reserved. This program and the accompanying materials
3
# All rights reserved. This program and the accompanying materials
4
# are made available under the terms of the Eclipse Public License v1.0
4
# are made available under the terms of the Eclipse Public License v1.0
5
# which accompanies this distribution, and is available at
5
# which accompanies this distribution, and is available at
Lines 8-13 Link Here
8
# Contributors:
8
# Contributors:
9
#     IBM Corporation - initial API and implementation
9
#     IBM Corporation - initial API and implementation
10
#		Benjamin Muskalla - Contribution for bug 239066
10
#		Benjamin Muskalla - Contribution for bug 239066
11
#		Stephan Herrmann - Contributions for
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 359721 - [options] add command line option for new warning token "resource"
15
#								bug 365208 - [compiler][batch] command line options for annotation based null analysis
11
###############################################################################
16
###############################################################################
12
### JavaBatchCompiler messages.
17
### JavaBatchCompiler messages.
13
18
Lines 15-21 Link Here
15
#Format: compiler.name = word1 word2 word3
20
#Format: compiler.name = word1 word2 word3
16
compiler.name = Eclipse Compiler for Java(TM)
21
compiler.name = Eclipse Compiler for Java(TM)
17
#Format: compiler.version = 0.XXX[, other words (don't forget the comma if adding other words)]
22
#Format: compiler.version = 0.XXX[, other words (don't forget the comma if adding other words)]
18
compiler.version = 0.C08, 3.8.0 M2
23
compiler.version = 0.C36, 3.8.0 M6
19
compiler.copyright = Copyright IBM Corp 2000, 2011. All rights reserved.
24
compiler.copyright = Copyright IBM Corp 2000, 2011. All rights reserved.
20
25
21
### progress
26
### progress
Lines 62-73 Link Here
62
configure.incompatibleComplianceForTarget = Compliance level ''{0}'' is incompatible with target level ''{1}''. A compliance level ''{1}'' or better is required
67
configure.incompatibleComplianceForTarget = Compliance level ''{0}'' is incompatible with target level ''{1}''. A compliance level ''{1}'' or better is required
63
configure.repetition = repetition must be a positive integer: {0}
68
configure.repetition = repetition must be a positive integer: {0}
64
configure.maxProblems = max problems must be a positive integer: {0}
69
configure.maxProblems = max problems must be a positive integer: {0}
70
configure.invalidNowarnOption = invalid syntax for nowarn option: {0}
65
71
66
configure.invalidErrorConfiguration = invalid error configuration: ''{0}''
72
configure.invalidErrorConfiguration = invalid error configuration: ''{0}''
67
configure.invalidError = invalid error token: ''{0}''. Ignoring this error token and compiling
73
configure.invalidError = invalid error token: ''{0}''. Ignoring this error token and compiling
68
configure.invalidErrorOption = invalid error option: ''{0}''. Must specify an error token
74
configure.invalidErrorOption = invalid error option: ''{0}''. Must specify an error token
69
configure.invalidUsageOfPlusOption=usage of ''+'' for ''{0}'' is illegal there
70
configure.invalidUsageOfMinusOption=usage of ''-'' for ''{0}'' is illegal there
71
75
72
## configure.directoryNotExist = directory does not exist: {0}
76
## configure.directoryNotExist = directory does not exist: {0}
73
configure.unrecognizedOption = Unrecognized option : {0}
77
configure.unrecognizedOption = Unrecognized option : {0}
Lines 100-105 Link Here
100
configure.multipleencodings=Multiple encoding specified: {1}. The default encoding has been set to {0}
104
configure.multipleencodings=Multiple encoding specified: {1}. The default encoding has been set to {0}
101
configure.differentencodings=Found encoding {0}. Different encodings were specified: {1}
105
configure.differentencodings=Found encoding {0}. Different encodings were specified: {1}
102
configure.differentencoding=Found encoding {0}. A different encoding was specified: {1}
106
configure.differentencoding=Found encoding {0}. A different encoding was specified: {1}
107
108
### null annotations
109
configure.invalidNullAnnot = Token {0} is not in the expected format "nullAnnot(<non null annotation name> | <nullable annotation name> | <non-null by default annotation name>)"
103
110
104
### requestor
111
### requestor
105
requestor.error = {0}. ERROR in {1}
112
requestor.error = {0}. ERROR in {1}
Lines 181-186 Link Here
181
\    -deprecation     + deprecation outside deprecated code (equivalent to\n\
188
\    -deprecation     + deprecation outside deprecated code (equivalent to\n\
182
\                       -warn:+deprecation)\n\
189
\                       -warn:+deprecation)\n\
183
\    -nowarn -warn:none disable all warnings\n\
190
\    -nowarn -warn:none disable all warnings\n\
191
\    -nowarn:[<directories separated by {0}>]\n\
192
\                       specify directories from which optional problems should\n\
193
\                       be ignored\n\
184
\    -?:warn -help:warn display advanced warning options\n\
194
\    -?:warn -help:warn display advanced warning options\n\
185
\ \n\
195
\ \n\
186
\ Error options:\n\
196
\ Error options:\n\
Lines 245-250 Link Here
245
\    -enableJavadoc     consider references in javadoc\n\
255
\    -enableJavadoc     consider references in javadoc\n\
246
\    -Xemacs            used to enable emacs-style output in the console.\n\
256
\    -Xemacs            used to enable emacs-style output in the console.\n\
247
\                       It does not affect the xml log output\n\
257
\                       It does not affect the xml log output\n\
258
\    -nonNullByDefault  for annotation based null analysis assume nonnull\n\
259
\                       as the global default\n\
248
\ \n\
260
\ \n\
249
\    -? -help           print this help message\n\
261
\    -? -help           print this help message\n\
250
\    -v -version        print compiler version\n\
262
\    -v -version        print compiler version\n\
Lines 262-270 Link Here
262
\ Warning options:\n\
274
\ Warning options:\n\
263
\    -deprecation         + deprecation outside deprecated code\n\
275
\    -deprecation         + deprecation outside deprecated code\n\
264
\    -nowarn -warn:none disable all warnings\n\
276
\    -nowarn -warn:none disable all warnings\n\
277
\    -nowarn:[<directories separated by {0}>]\n\
278
\                       specify directories from which optional problems should\n\
279
\                       be ignored\n\
265
\    -warn:<warnings separated by ,>    enable exactly the listed warnings\n\
280
\    -warn:<warnings separated by ,>    enable exactly the listed warnings\n\
266
\    -warn:+<warnings separated by ,>   enable additional warnings\n\
281
\    -warn:+<warnings separated by ,>   enable additional warnings\n\
267
\    -warn:-<warnings separated by ,>   disable specific warnings\n\
282
\    -warn:-<warnings separated by ,>   disable specific warnings\n\
283
\      all                  enable all warnings\n\
268
\      allDeadCode          dead code including trivial if(DEBUG) check\n\
284
\      allDeadCode          dead code including trivial if(DEBUG) check\n\
269
\      allDeprecation       deprecation including inside deprecated code\n\
285
\      allDeprecation       deprecation including inside deprecated code\n\
270
\      allJavadoc           invalid or missing javadoc\n\
286
\      allJavadoc           invalid or missing javadoc\n\
Lines 303-313 Link Here
303
\      nls                  string literal lacking non-nls tag //$NON-NLS-<n>$\n\
319
\      nls                  string literal lacking non-nls tag //$NON-NLS-<n>$\n\
304
\      noEffectAssign     + assignment without effect\n\
320
\      noEffectAssign     + assignment without effect\n\
305
\      null                 potential missing or redundant null check\n\
321
\      null                 potential missing or redundant null check\n\
322
\      nullAnnot(<annot. names separated by |>) + annotation based null analysis,\n\
323
\                           nullable|nonnull|nonnullbydefault annotation types\n\
324
\                           optionally specified using fully qualified names\n\
306
\      nullDereference    + missing null check\n\
325
\      nullDereference    + missing null check\n\
307
\      over-ann             missing @Override annotation (superclass)\n\
326
\      over-ann             missing @Override annotation (superclass)\n\
308
\      paramAssign          assignment to a parameter\n\
327
\      paramAssign          assignment to a parameter\n\
309
\      pkgDefaultMethod   + attempt to override package-default method\n\
328
\      pkgDefaultMethod   + attempt to override package-default method\n\
310
\      raw                + usage of raw type\n\
329
\      raw                + usage of raw type\n\
330
\      resource           + (pot.) unsafe usage of resource of type Closeable\n\
311
\      semicolon            unnecessary semicolon, empty statement\n\
331
\      semicolon            unnecessary semicolon, empty statement\n\
312
\      serial             + missing serialVersionUID\n\
332
\      serial             + missing serialVersionUID\n\
313
\      specialParamHiding   constructor or setter parameter hiding a field\n\
333
\      specialParamHiding   constructor or setter parameter hiding a field\n\
(-)a/org.eclipse.jdt.core/build.properties (-2 / +3 lines)
Lines 1-5 Link Here
1
###############################################################################
1
###############################################################################
2
# Copyright (c) 2000, 2010 IBM Corporation and others.
2
# Copyright (c) 2000, 2011 IBM Corporation and others.
3
# All rights reserved. This program and the accompanying materials
3
# All rights reserved. This program and the accompanying materials
4
# are made available under the terms of the Eclipse Public License v1.0
4
# are made available under the terms of the Eclipse Public License v1.0
5
# which accompanies this distribution, and is available at
5
# which accompanies this distribution, and is available at
Lines 24-30 Link Here
24
                   org.eclipse.jdt.core.jdom.*,\
24
                   org.eclipse.jdt.core.jdom.*,\
25
                   org.eclipse.jdt.core.dom.*,\
25
                   org.eclipse.jdt.core.dom.*,\
26
                   org.eclipse.jdt.core.dom.rewrite.*,\
26
                   org.eclipse.jdt.core.dom.rewrite.*,\
27
                   org.eclipse.jdt.core.search.*
27
                   org.eclipse.jdt.core.search.*,\
28
                   org.eclipse.jdt.core.index.*
28
source.. =   batch/,\
29
source.. =   batch/,\
29
	         codeassist/,\
30
	         codeassist/,\
30
	         compiler/,\
31
	         compiler/,\
(-)a/org.eclipse.jdt.core/buildnotes_jdt-core.html (-5 / +1108 lines)
Lines 42-58 Link Here
42
	</td>
42
	</td>
43
  </tr>
43
  </tr>
44
</table>
44
</table>
45
<a name="v_C36"></a>
46
<hr><h1>
47
Eclipse Platform Build Notes<br>
48
Java development tools core</h1>
49
Eclipse SDK 3.8.0 - %date% - 3.8.0 M6
50
<br>Project org.eclipse.jdt.core v_C36
51
(<a href="http://dev.eclipse.org/viewcvs/index.cgi/org.eclipse.jdt.core/?only_with_tag=v_C36">cvs</a>).
52
<h2>What's new in this drop</h2>
53
54
<h3>Problem Reports Fixed</h3>
55
<a href="https://bugs.eclipse.org/bugs/show_bug.cgi?id=372351">372351</a>
56
Illegal implementation of 'org.eclipse.jdt.internal.compiler.env.ICompilationUnit' in Tomcat Jasper
57
<br><a href="https://bugs.eclipse.org/bugs/show_bug.cgi?id=220928">220928</a>
58
[buildpath] Should be able to ignore warnings from certain source folders
59
60
<a name="v_C35"></a>
61
<hr><h1>
62
Eclipse Platform Build Notes<br>
63
Java development tools core</h1>
64
Eclipse SDK 3.8.0 - February 21, 2012
65
<br>Project org.eclipse.jdt.core v_C35
66
(<a href="http://dev.eclipse.org/viewcvs/index.cgi/org.eclipse.jdt.core/?only_with_tag=v_C35">cvs</a>).
67
<h2>What's new in this drop</h2>
68
69
<h3>Problem Reports Fixed</h3>
70
<a href="https://bugs.eclipse.org/bugs/show_bug.cgi?id=365499">365499</a>
71
Add a system property to control for JavaModelManager's jar type cache size
72
<br><a href="https://bugs.eclipse.org/bugs/show_bug.cgi?id=368152">368152</a>
73
ConcurrentModificationException on startup in ExternalFoldersManager.createPendingFolders
74
<br><a href="https://bugs.eclipse.org/bugs/show_bug.cgi?id=244544">244544</a>
75
codeSelect fails on constant declaration in anonymous and local classes
76
<br><a href="https://bugs.eclipse.org/bugs/show_bug.cgi?id=291040">291040</a>
77
codeSelect(..) does not work for a deeply nested method invocation in nested and anonymous class
78
<br><a href="https://bugs.eclipse.org/bugs/show_bug.cgi?id=370930">370930</a>
79
NonNull annotation not considered for enhanced for loops
80
<br><a href="https://bugs.eclipse.org/bugs/show_bug.cgi?id=366063">366063</a>
81
Compiler should not add synthetic @NonNull annotations
82
<br><a href="https://bugs.eclipse.org/bugs/show_bug.cgi?id=365531">365531</a>
83
[compiler][null] investigate alternative strategy for internally encoding nullness defaults
84
<br><a href="https://bugs.eclipse.org/bugs/show_bug.cgi?id=370639">370639</a>
85
[compiler][resource] restore the default for resource leak warnings
86
87
<a name="v_C34"></a>
88
<hr><h1>
89
Eclipse Platform Build Notes<br>
90
Java development tools core</h1>
91
Eclipse SDK 3.8.0 - February 14, 2012
92
<br>
93
<h2>What's new in this drop</h2>
94
95
<h3>Problem Reports Fixed</h3>
96
<a href="https://bugs.eclipse.org/bugs/show_bug.cgi?id=123836">123836</a>
97
[1.5][search] for references to overriding method with bound type variable is not polymorphic
98
<br><a href="https://bugs.eclipse.org/bugs/show_bug.cgi?id=368546">368546</a>
99
[compiler][resource] Avoid remaining false positives found when compiling the Eclipse SDK
100
<br><a href="https://bugs.eclipse.org/bugs/show_bug.cgi?id=364254">364254</a>
101
Reduce console output during JDT/Core junits execution.
102
<br><a href="https://bugs.eclipse.org/bugs/show_bug.cgi?id=362633">362633</a>
103
NPE while trying to rename a class
104
105
<a name="v_C33"></a>
106
<hr><h1>
107
Eclipse Platform Build Notes<br>
108
Java development tools core</h1>
109
Eclipse SDK 3.8.0 - January 25, 2012 - 3.8.0 M5
110
<br>
111
<h2>What's new in this drop</h2>
112
113
<h3>Problem Reports Fixed</h3>
114
<a href="https://bugs.eclipse.org/bugs/show_bug.cgi?id=369595">369595</a>
115
Javadoc fixes for IClasspathAttribute.SOURCE_ATTACHMENT_ENCODING
116
117
<a name="v_C32"></a>
118
<hr><h1>
119
Eclipse Platform Build Notes<br>
120
Java development tools core</h1>
121
Eclipse SDK 3.8.0 - January 24, 2012
122
<br>
123
<h2>What's new in this drop</h2>
124
125
<h3>Problem Reports Fixed</h3>
126
<a href="https://bugs.eclipse.org/bugs/show_bug.cgi?id=366829">366829</a>
127
Batch compiler option and SuppressWarnings token for Overriding a Synchronized Method with a Non-synchronized Method
128
129
<a name="v_C31"></a>
130
<hr><h1>
131
Eclipse Platform Build Notes<br>
132
Java development tools core</h1>
133
Eclipse SDK 3.8.0 - January 22, 2012
134
<br>
135
<h2>What's new in this drop</h2>
136
137
<h3>Problem Reports Fixed</h3>
138
<a href="https://bugs.eclipse.org/bugs/show_bug.cgi?id=369251">369251</a>
139
Starved worker threads
140
<br><a href="https://bugs.eclipse.org/bugs/show_bug.cgi?id=365208">365208</a>
141
[compiler][batch] command line options for annotation based null analysis
142
143
<a name="v_C30"></a>
144
<hr><h1>
145
Eclipse Platform Build Notes<br>
146
Java development tools core</h1>
147
Eclipse SDK 3.8.0 - January 20, 2012
148
<br>
149
<h2>What's new in this drop</h2>
150
<ul>
151
<li>New constant for the name of the encoding to be used for source attachments in IClasspathAttribute (see bug <a href="https://bugs.eclipse.org/bugs/show_bug.cgi?id=361356">361356</a> for details)
152
<pre>
153
	/**
154
	 * Constant for the name of the encoding to be used for source attachments.
155
	 *
156
	 * &lt;p&gt;The value of this attribute has to be a string representation of a valid encoding. The encoding
157
	 * for a source attachment is determined in the following order:  &lt;/p&gt;
158
	 *
159
	 * &lt;ul&gt;
160
	 * &lt;li&gt; Encoding explicitly set on the source file (java or zip), i.e. <code>org.eclipse.core.resources.IFile#getCharset(false)</code> &lt;/li&gt;
161
	 * &lt;li&gt; Encoding set on the corresponding classpath entry &lt;/li&gt;
162
	 * &lt;li&gt; If the source attachment is a member of the project, then the project's default charSet&lt;/li&gt;
163
	 * &lt;li&gt; Workspace default charSet &lt;/li&gt;
164
	 * &lt;/ul&gt;
165
	 *
166
	 * @since 3.8
167
	 */
168
	String SOURCE_ATTACHMENT_ENCODING = "source_encoding";
169
</pre>
170
</li>
171
<li> New IProblems for messages relating to contradictory or redundant null annotations
172
<pre>
173
	/** @since 3.8 */
174
	int RedundantNullDefaultAnnotation = Internal + 925;
175
	/** @since 3.8 */
176
	int RedundantNullDefaultAnnotationPackage = Internal + 926;
177
	/** @since 3.8 */
178
	int RedundantNullDefaultAnnotationType = Internal + 927;
179
	/** @since 3.8 */
180
	int RedundantNullDefaultAnnotationMethod = Internal + 928;
181
	/** @since 3.8 */
182
	int ContradictoryNullAnnotations = Internal + 929;
183
</pre>
184
</li>
185
</ul>
186
<h3>Problem Reports Fixed</h3>
187
<a href="https://bugs.eclipse.org/bugs/show_bug.cgi?id=361356">361356</a>
188
Allow to specify encoding for source attachments
189
<br><a href="https://bugs.eclipse.org/bugs/show_bug.cgi?id=365582">365582</a>
190
FUP of bug 361938: Other error code pattern
191
<br><a href="https://bugs.eclipse.org/bugs/show_bug.cgi?id=365662">365662</a>
192
[compiler][null] warn on contradictory and redundant null annotations
193
194
<a name="v_C29"></a>
195
<hr><h1>
196
Eclipse Platform Build Notes<br>
197
Java development tools core</h1>
198
Eclipse SDK 3.8.0 - January 17, 2012
199
<br>
200
<h2>What's new in this drop</h2>
201
202
<h3>Problem Reports Fixed</h3>
203
<a href="https://bugs.eclipse.org/bugs/show_bug.cgi?id=368842">368842</a>
204
test failure because test case refers to java.util.Objects
205
<br><a href="https://bugs.eclipse.org/bugs/show_bug.cgi?id=368709">368709</a>
206
Endless loop in FakedTrackingVariable.markPassedToOutside
207
<br><a href="https://bugs.eclipse.org/bugs/show_bug.cgi?id=361407">361407</a>
208
Resource leak warning when resource is assigned to a field outside of constructor
209
<br><a href="https://bugs.eclipse.org/bugs/show_bug.cgi?id=362331">362331</a>
210
Resource leak not detected when closeable not assigned to variable
211
<br><a href="https://bugs.eclipse.org/bugs/show_bug.cgi?id=362332">362332</a>
212
Only report potential leak when closeable not created in the local scope
213
<br><a href="https://bugs.eclipse.org/bugs/show_bug.cgi?id=360908">360908</a>
214
Avoid resource leak warning when the underlying/chained resource is closed explicitly
215
<br><a href="https://bugs.eclipse.org/bugs/show_bug.cgi?id=361073">361073</a>
216
Avoid resource leak warning when the top level resource is closed explicitly
217
<br><a href="https://bugs.eclipse.org/bugs/show_bug.cgi?id=358903">358903</a>
218
Filter practically unimportant resource leak warnings
219
<br><a href="https://bugs.eclipse.org/bugs/show_bug.cgi?id=365387">365387</a>
220
[compiler][null] bug 186342: Issues to follow up post review and verification.
221
<br><a href="https://bugs.eclipse.org/bugs/show_bug.cgi?id=365519">365519</a>
222
editorial cleanup after bug 186342 and bug 365387
223
<br><a href="https://bugs.eclipse.org/bugs/show_bug.cgi?id=368435">368435</a>
224
[compiler] NPE while compile a method with unused local
225
<br><a href="https://bugs.eclipse.org/bugs/show_bug.cgi?id=361963">361963</a>
226
Stack overflow when trying to code complete a generic list
227
<br><a href="https://bugs.eclipse.org/bugs/show_bug.cgi?id=365437">365437</a>
228
Private methods tagged with @Inject should not be flagged with unused warning
229
<br><a href="https://bugs.eclipse.org/bugs/show_bug.cgi?id=366131">366131</a>
230
[1.5][compiler] New generics compile error in Indigo SR1 for code that compiles in earlier Eclipse and javac
231
232
<a name="v_C28"></a>
233
<hr><h1>
234
Eclipse Platform Build Notes<br>
235
Java development tools core</h1>
236
Eclipse SDK 3.8.0 - January 10, 2012
237
<h2>What's new in this drop</h2>
238
239
<h3>Problem Reports Fixed</h3>
240
<a href="https://bugs.eclipse.org/bugs/show_bug.cgi?id=367023">367023</a>
241
Error in JDT Core during AST creation
242
<br><a href="https://bugs.eclipse.org/bugs/show_bug.cgi?id=354229">354229</a>
243
[compiler][1.7] Name clash error not being reported by ecj.
244
<br><a href="https://bugs.eclipse.org/bugs/show_bug.cgi?id=367879">367879</a>
245
Incorrect &quot;Potential null pointer access&quot; warning on statement after try-with-resources within try-finally
246
<br><a href="https://bugs.eclipse.org/bugs/show_bug.cgi?id=366999">366999</a>
247
VerifyError: Inconsistent stackmap frames
248
<br><a href="https://bugs.eclipse.org/bugs/show_bug.cgi?id=346175">346175</a>
249
@SuppressWarnings should clear all errors including fatal optional errors
250
<br><a href="https://bugs.eclipse.org/bugs/show_bug.cgi?id=366544">366544</a>
251
[index] Test testUseIndexInternalJarAfterRestart failed on Mac and Linux
252
<br><a href="https://bugs.eclipse.org/bugs/show_bug.cgi?id=302850">302850</a>
253
13 failures in JavaModel tests for the N20100214-2000 Mac OS X - Cocoa test machine
254
255
<a name="v_C27"></a>
256
<hr><h1>
257
Eclipse Platform Build Notes<br>
258
Java development tools core</h1>
259
Eclipse SDK 3.8.0 - January 3, 2012 - 3.8.0 M5
260
<br>
261
<h2>What's new in this drop</h2>
262
263
<h3>Problem Reports Fixed</h3>
264
<a href="https://bugs.eclipse.org/bugs/show_bug.cgi?id=367566">367566</a>
265
In try-with-resources statement close() method of resource is not called
266
<br><a href="https://bugs.eclipse.org/bugs/show_bug.cgi?id=364890">364890</a>
267
BinaryTypeBinding should use char constants from Util
268
<br><a href="https://bugs.eclipse.org/bugs/show_bug.cgi?id=365992">365992</a>
269
[builder] [null] Change of nullness for a parameter doesn't trigger a build for the files that call the method
270
<br><a href="https://bugs.eclipse.org/bugs/show_bug.cgi?id=367203">367203</a>
271
[compiler][null] detect assigning null to nonnull argument
272
<br><a href="https://bugs.eclipse.org/bugs/show_bug.cgi?id=367154">367154</a>
273
[compiler][null]  Problem in propagating null defaults.
274
275
<a name="v_C26"></a>
276
<hr><h1>
277
Eclipse Platform Build Notes<br>
278
Java development tools core</h1>
279
Eclipse SDK 3.8.0 - December 20, 2011
280
<h2>What's new in this drop</h2>
281
282
<h3>Problem Reports Fixed</h3>
283
<a href="https://bugs.eclipse.org/bugs/show_bug.cgi?id=362711">362711</a>
284
possibly incorrect JDT POST_CHANGE event fired when a file is replaced
285
<br><a href="https://bugs.eclipse.org/bugs/show_bug.cgi?id=365835">365835</a>
286
[compiler][null] inconsistent error reporting.
287
<br><a href="https://bugs.eclipse.org/bugs/show_bug.cgi?id=365836">365836</a>
288
[compiler][null] Incomplete propagation of null defaults.
289
<br><a href="https://bugs.eclipse.org/bugs/show_bug.cgi?id=365983">365983</a>
290
[compiler][null] AIOOB with null annotation analysis and varargs
291
<br><a href="https://bugs.eclipse.org/bugs/show_bug.cgi?id=366003">366003</a>
292
CCE in ASTNode.resolveAnnotations(ASTNode.java:639)
293
<br><a href="https://bugs.eclipse.org/bugs/show_bug.cgi?id=366829">366829</a>
294
Batch compiler option and SuppressWarnings token for Overriding a Synchronized Method with a Non-synchronized Method
295
<br><a href="https://bugs.eclipse.org/bugs/show_bug.cgi?id=364450">364450</a>
296
Dubious class path error triggers a full rebuild
297
298
<a name="v_C25"></a>
299
<hr><h1>
300
Eclipse Platform Build Notes<br>
301
Java development tools core</h1>
302
Eclipse SDK 3.8.0 - December 13, 2011
303
<h2>What's new in this drop</h2>
304
<ul>
305
<li>New constant for the name of index location class path attribute in IClasspathAttribute(see bug <a href="https://bugs.eclipse.org/bugs/show_bug.cgi?id=356620">356620</a> for details)
306
<pre>
307
   /**
308
     * Constant for the name of the index location attribute.
309
     * 
310
     * The value for this attribute has to be the string representation of a URL.
311
     * It should point to an existing index file in a folder or a jar. The URL can also be of platform protocol.
312
     * 
313
     * @since 3.8
314
     */
315
     String INDEX_LOCATION_ATTRIBUTE_NAME = "index_location"; 
316
</pre>
317
</li>
318
<li>New API org.eclipse.jdt.core.index.JavaIndexer.generateIndexForJar to generate the index file for a given jar
319
<pre>
320
   /**
321
     * Generates the index file for the specified jar.
322
     *
323
     * @param pathToJar The full path to the jar that needs to be indexed
324
     * @param pathToIndexFile The full path to the index file that needs to be generated
325
     * @throws IOException if the jar is not found or could not write into the index file
326
     * @since 3.8
327
     */
328
     public static void generateIndexForJar(String pathToJar, String pathToIndexFile) throws IOException;
329
</pre>
330
</li>
331
<li> New application org.eclipse.jdt.core.JavaIndexer to generate index file for the given jar
332
</li>
333
<li> New ant task eclipse.buildJarIndex to generate the index file for the given jar </li>
334
</ul>
335
<h3>Problem Reports Fixed</h3>
336
<a href="https://bugs.eclipse.org/bugs/show_bug.cgi?id=356620">356620</a>
337
Make it possible to provide indexes for defined libraries
338
339
<a name="v_C24"></a>
340
<hr><h1>
341
Eclipse Platform Build Notes<br>
342
Java development tools core</h1>
343
Eclipse SDK 3.8.0 - December 5, 2011 - 3.8.1 M4
344
345
<h2>What's new in this drop</h2>
346
347
<h3>Problem Reports Fixed</h3>
348
<a href="https://bugs.eclipse.org/bugs/show_bug.cgi?id=365566">365566</a>
349
set resource leak diagnostic to &quot;ignore&quot; until bug 358903 is fixed
350
351
<a name="v_C23"></a>
352
<hr><h1>
353
Eclipse Platform Build Notes<br>
354
Java development tools core</h1>
355
Eclipse SDK 3.8.0
356
<h2>What's new in this drop</h2>
357
<ul>
358
<li>New Javacore option org.eclipse.jdt.core.JavaCore.COMPILER_ANNOTATION_NULL_ANALYSIS (see bug <a href="https://bugs.eclipse.org/bugs/show_bug.cgi?id=186342">186342</a> for details):
359
<pre>
360
    /**
361
     * Compiler option ID: Annotation-based Null Analysis.
362
     * 
363
     * This option controls whether the compiler will use null annotations for
364
     * improved analysis of (potential) null references.
365
     * 
366
     * When enabled, the compiler will interpret the annotation types defined using
367
     * {@link #COMPILER_NONNULL_ANNOTATION_NAME} and {@link #COMPILER_NULLABLE_ANNOTATION_NAME}
368
     * as specifying whether or not a given type includes the value <code>null</code>.
369
     * 
370
     * The effect of these analyses is further controlled by the options
371
     * {@link #COMPILER_PB_NULL_SPECIFICATION_VIOLATION},
372
     * {@link #COMPILER_PB_POTENTIAL_NULL_SPECIFICATION_VIOLATION} and
373
     * {@link #COMPILER_PB_NULL_SPECIFICATION_INSUFFICIENT_INFO}.
374
     * 
375
     * Option id: <code>"org.eclipse.jdt.core.compiler.annotation.nullanalysis"</code>
376
     * Possible values: <code>{ "disabled", "enabled" }</code>
377
     * Default: <code>"disabled"</code>
378
     * @since 3.8
379
     * @category CompilerOptionID
380
     */
381
    public static final String COMPILER_ANNOTATION_NULL_ANALYSIS = PLUGIN_ID + ".compiler.annotation.nullanalysis";
382
</pre></li>
383
<li>New Javacore option org.eclipse.jdt.core.JavaCore.COMPILER_NULLABLE_ANNOTATION_NAME (see bug <a href="https://bugs.eclipse.org/bugs/show_bug.cgi?id=186342">186342</a> for details):
384
<pre>
385
    /**
386
     * Compiler option ID: Name of Annotation Type for Nullable Types.
387
     * 
388
     * This option defines a fully qualified Java type name that the compiler may use
389
     * to perform special null analysis.
390
     * 
391
     * If the annotation specified by this option is applied to a type in a method
392
     * signature or variable declaration, this will be interpreted as a specification
393
     * that <code>null</code> is a legal value in that position. Currently supported
394
     * positions are: method parameters, method return type and local variables.
395
     * 
396
     * If a value whose type
397
     * is annotated with this annotation is dereferenced without checking for null,
398
     * the compiler will trigger a diagnostic as further controlled by
399
     * {@link #COMPILER_PB_POTENTIAL_NULL_REFERENCE}.
400
     * 
401
     * The compiler may furthermore check adherence to the null specification as
402
     * further controlled by {@link #COMPILER_PB_NULL_SPECIFICATION_VIOLATION},
403
     * {@link #COMPILER_PB_POTENTIAL_NULL_SPECIFICATION_VIOLATION} and
404
     * {@link #COMPILER_PB_NULL_SPECIFICATION_INSUFFICIENT_INFO}.
405
     * 
406
     * This option only has an effect if the the option {@link #COMPILER_ANNOTATION_NULL_ANALYSIS} is enabled.
407
     * 
408
     * Option id: <code>"org.eclipse.jdt.core.compiler.annotation.nullable"</code>
409
     * Possible values: any legal, fully qualified Java type name; must resolve to an annotation type.
410
     * Default: <code>"org.eclipse.jdt.annotation.Nullable"</code>
411
     * @since 3.8
412
     * @category CompilerOptionID
413
     */
414
    public static final String COMPILER_NULLABLE_ANNOTATION_NAME = PLUGIN_ID + ".compiler.annotation.nullable";
415
</pre></li>
416
<li>New Javacore option org.eclipse.jdt.core.JavaCore.COMPILER_NONNULL_ANNOTATION_NAME (see bug <a href="https://bugs.eclipse.org/bugs/show_bug.cgi?id=186342">186342</a> for details):
417
<pre>
418
    /**
419
     * Compiler option ID: Name of Annotation Type for Non-Null Types.
420
     * 
421
     * This option defines a fully qualified Java type name that the compiler may use
422
     * to perform special null analysis.
423
     * 
424
     * If the annotation specified by this option is applied to a type in a method
425
     * signature or variable declaration, this will be interpreted as a specification
426
     * that <code>null</code> is <b>not</b> a legal value in that position. Currently
427
     * supported positions are: method parameters, method return type and local variables.
428
     * 
429
     * For values declared with this annotation, the compiler will never trigger a null
430
     * reference diagnostic (as controlled by {@link #COMPILER_PB_POTENTIAL_NULL_REFERENCE}
431
     * and {@link #COMPILER_PB_NULL_REFERENCE}), because the assumption is made that null
432
     * will never occur at runtime in these positions.
433
     * 
434
     * The compiler may furthermore check adherence to the null specification as further
435
     * controlled by {@link #COMPILER_PB_NULL_SPECIFICATION_VIOLATION},
436
     * {@link #COMPILER_PB_POTENTIAL_NULL_SPECIFICATION_VIOLATION} and
437
     * {@link #COMPILER_PB_NULL_SPECIFICATION_INSUFFICIENT_INFO}.
438
     * 
439
     * This option only has an effect if the the option {@link #COMPILER_ANNOTATION_NULL_ANALYSIS} is enabled.
440
     * 
441
     * Option id: <code>"org.eclipse.jdt.core.compiler.annotation.nonnull"</code>
442
     * Possible values: any legal, fully qualified Java type name; must resolve to an annotation type.
443
     * Default: <code>"org.eclipse.jdt.annotation.NonNull"</code>
444
     * @since 3.8
445
     * @category CompilerOptionID
446
     */
447
    public static final String COMPILER_NONNULL_ANNOTATION_NAME = PLUGIN_ID + ".compiler.annotation.nonnull";
448
</pre></li>
449
<li>New Javacore option org.eclipse.jdt.core.JavaCore.COMPILER_NONNULL_BY_DEFAULT_ANNOTATION_NAME (see bug <a href="https://bugs.eclipse.org/bugs/show_bug.cgi?id=186342">186342</a> for details):
450
<pre>
451
    /**
452
     * Compiler option ID: Name of Annotation Type to specify a nullness default for unannotated types.
453
     * 
454
     * This option defines a fully qualified Java type name that the compiler may use
455
     * to perform special null analysis.
456
     * 
457
     * If the annotation is applied without an argument, all unannotated types in method signatures
458
     * within the annotated element will be treated as if they were specified with the non-null annotation
459
     * (see {@link #COMPILER_NONNULL_ANNOTATION_NAME}).
460
     * 
461
     * If the annotation is applied with the constant <code>false</code> as its argument
462
     * all corresponding defaults at outer scopes will be canceled for the annotated element.
463
     * This includes defaults specified using this annotation type or a default defined using
464
     * the compiler option {@link #COMPILER_NONNULL_IS_DEFAULT}.
465
     * 
466
     * This option only has an effect if the the option {@link #COMPILER_ANNOTATION_NULL_ANALYSIS} is enabled.
467
     * 
468
     * Option id: <code>"org.eclipse.jdt.core.compiler.annotation.nonnullbydefault"</code>
469
     * Possible values: any legal, fully qualified Java type name; must resolve to an annotation type.
470
     *     That annotation type should have exactly one boolean parameter.
471
     * Default: <code>"org.eclipse.jdt.annotation.NonNullByDefault"</code>
472
     * @since 3.8
473
     * @category CompilerOptionID
474
     */
475
    public static final String COMPILER_NONNULL_BY_DEFAULT_ANNOTATION_NAME = PLUGIN_ID + ".compiler.annotation.nonnullbydefault";
476
</pre></li>
477
<li>New Javacore option org.eclipse.jdt.core.JavaCore.COMPILER_NONNULL_IS_DEFAULT (see bug <a href="https://bugs.eclipse.org/bugs/show_bug.cgi?id=186342">186342</a> for details):
478
<pre>
479
    /**
480
     * Compiler option ID: Globally specify non-null as the assumed default for unannotated types.
481
     * 
482
     * When enabled this option globally achieves the same effect 
483
     * as specifying {@link #COMPILER_NONNULL_ANNOTATION_NAME} does for individual elements.
484
     * 
485
     * This option only has an effect if the the option {@link #COMPILER_ANNOTATION_NULL_ANALYSIS} is enabled.
486
     *
487
     * Option id: <code>"org.eclipse.jdt.core.compiler.annotation.nonnullisdefault"</code>
488
     * Possible values: <code>{ "disabled", "enabled" }</code>.
489
     * Default: <code>"disabled"</code>
490
     * @since 3.8
491
     * @category CompilerOptionID
492
     */
493
    public static final String COMPILER_NONNULL_IS_DEFAULT = PLUGIN_ID + ".compiler.annotation.nonnullisdefault";
494
</pre></li>
495
<li>New Javacore option org.eclipse.jdt.core.JavaCore.COMPILER_PB_NULL_SPECIFICATION_VIOLATION (see bug <a href="https://bugs.eclipse.org/bugs/show_bug.cgi?id=186342">186342</a> for details):
496
<pre>
497
    /**
498
     * Compiler option ID: Reporting Violations of Null Specifications.
499
     * 
500
     * Depending on this option, the compiler will issue either an error or a warning
501
     * whenever one of the following situations is detected:
502
     * 
503
     * 1. A method declared with a nonnull annotation returns an expression that is
504
     *    statically known to evaluate to a null value.
505
     * 2. An expression that is statically known to evaluate to a null value is passed
506
     *    as an argument in a method call where the corresponding parameter of the called
507
     *    method is declared with a nonnull annotation.
508
     * 3. An expression that is statically known to evaluate to a null value is assigned
509
     *    to a local variable that is declared with a nonnull annotation.
510
     * 4. A method that overrides an inherited method declared with a nonnull annotation
511
     *    tries to relax that contract by specifying a nullable annotation
512
     *    (prohibition of contravariant return).
513
     * 5. A method that overrides an inherited method which has a nullable declaration
514
     *    for at least one of its parameters, tries to tighten that null contract by
515
     *    specifying a nonnull annotation for its corresponding parameter
516
     *    (prohibition of covariant parameters).
517
     * 
518
     * The compiler options {@link #COMPILER_NONNULL_ANNOTATION_NAME} and
519
     * {@link #COMPILER_NULLABLE_ANNOTATION_NAME} control which annotations the compiler
520
     * shall interpret as nonnull or nullable annotations, respectively.
521
     * 
522
     * This option only has an effect if the the option {@link #COMPILER_ANNOTATION_NULL_ANALYSIS} is enabled.
523
     *
524
     * Option id: <code>"org.eclipse.jdt.core.compiler.problem.nullSpecViolation"</code>
525
     * Possible values: <code>{ "error", "warning" }</code>
526
     * Default: <code>"error"</code>
527
     * 
528
     * @since 3.8
529
     * @category CompilerOptionID
530
     */
531
    public static final String COMPILER_PB_NULL_SPECIFICATION_VIOLATION = PLUGIN_ID + ".compiler.problem.nullSpecViolation";
532
</pre></li>
533
<li>New Javacore option org.eclipse.jdt.core.JavaCore.COMPILER_PB_POTENTIAL_NULL_SPECIFICATION_VIOLATION (see bug <a href="https://bugs.eclipse.org/bugs/show_bug.cgi?id=186342">186342</a> for details):
534
<pre>
535
    /**
536
     * Compiler option ID: Reporting Violations of Null Specifications with Potential Null Value.
537
     * 
538
     * When enabled, the compiler will issue an error or a warning whenever one of the
539
     * following situations is detected:
540
     *
541
     * 1. A method declared with a nonnull annotation returns an expression that is
542
     *    statically known to evaluate to a null value on some flow.
543
     * 2. An expression that is statically known to evaluate to a null value on some flow
544
     *    is passed as an argument in a method call where the corresponding parameter of
545
     *    the called method is declared with a nonnull annotation.
546
     * 3. An expression that is statically known to evaluate to a null value on some flow
547
     *    is assigned to a local variable that is declared with a nonnull annotation.
548
     * 
549
     * The compiler options {@link #COMPILER_NONNULL_ANNOTATION_NAME} and
550
     * {@link #COMPILER_NULLABLE_ANNOTATION_NAME} control which annotations the compiler
551
     * shall interpret as nonnull or nullable annotations, respectively.
552
     * 
553
     * 
554
     * This option only has an effect if the the option {@link #COMPILER_ANNOTATION_NULL_ANALYSIS} is enabled.
555
     *
556
     * Option id: <code>"org.eclipse.jdt.core.compiler.problem.potentialNullSpecViolation"</code>
557
     * Possible values: <code>{ "error", "warning", "ignore" }</code>
558
     * Default: <code>"error"</code>
559
     * 
560
     * @since 3.8
561
     * @category CompilerOptionID
562
     */
563
    public static final String COMPILER_PB_POTENTIAL_NULL_SPECIFICATION_VIOLATION = PLUGIN_ID + ".compiler.problem.potentialNullSpecViolation";
564
</pre></li>
565
<li>New Javacore option org.eclipse.jdt.core.JavaCore.COMPILER_PB_NULL_SPECIFICATION_INSUFFICIENT_INFO (see bug <a href="https://bugs.eclipse.org/bugs/show_bug.cgi?id=186342">186342</a> for details):
566
<pre>
567
    /**
568
     * Compiler option ID: Reporting Insufficient Information for Analysing Adherence to Null Specifications.
569
     * 
570
     * When enabled, the compiler will issue an error or a warning whenever one of the
571
     * following situations is detected:
572
     *
573
     * 1. A method declared with a nonnull annotation returns an expression for which
574
     *    insufficient nullness information is available for statically proving that no
575
     *    flow will pass a null value at runtime.
576
     * 2. An expression for which insufficient nullness information is available for
577
     *    statically proving that it will never evaluate to a null value at runtime
578
     *    is passed as an argument in a method call where the corresponding parameter of
579
     *    the called method is declared with a nonnull annotation.
580
     * 3. An expression for which insufficient nullness information is available for
581
     *    statically proving that it will never evaluate to a null value at runtime
582
     *    is assigned to a local variable that is declared with a nonnull annotation.
583
     *
584
     * Insufficient nullness information is usually a consequence of using other unannotated
585
     * variables or methods.
586
     * 
587
     * The compiler options {@link #COMPILER_NONNULL_ANNOTATION_NAME} and
588
     * {@link #COMPILER_NULLABLE_ANNOTATION_NAME} control which annotations the compiler
589
     * shall interpret as nonnull or nullable annotations, respectively.
590
     * 
591
     * This option only has an effect if the the option {@link #COMPILER_ANNOTATION_NULL_ANALYSIS} is enabled.
592
     * 
593
     * Option id: <code>"org.eclipse.jdt.core.compiler.problem.nullSpecInsufficientInfo"</code>
594
     * Possible values: <code>{ "error", "warning", "ignore" }</code>
595
     * Default: <code>"warning"</code>
596
     * 
597
     * @since 3.8
598
     * @category CompilerOptionID
599
     */
600
    public static final String COMPILER_PB_NULL_SPECIFICATION_INSUFFICIENT_INFO = PLUGIN_ID + ".compiler.problem.nullSpecInsufficientInfo";
601
</pre></li>
602
<li>New Javacore option org.eclipse.jdt.core.JavaCore.COMPILER_PB_REDUNDANT_NULL_ANNOTATION (see bug <a href="https://bugs.eclipse.org/bugs/show_bug.cgi?id=186342">186342</a> for details):
603
<pre>
604
    /**
605
     * Compiler option ID: Reporting Redundant Null Annotations.
606
     * 
607
     * When enabled, the compiler will issue an error or a warning when a non-null annotation
608
     * (see {@link #COMPILER_NONNULL_ANNOTATION_NAME})
609
     * is applied although the same effect is already achieved by a default applicable at the
610
     * current location. Such a default may be effective by enabling the option
611
     * {@link #COMPILER_NONNULL_IS_DEFAULT} or by using the annotation specified by the option
612
     * {@link #COMPILER_NONNULL_BY_DEFAULT_ANNOTATION_NAME}.
613
     * 
614
     * This option only has an effect if the the option {@link #COMPILER_ANNOTATION_NULL_ANALYSIS} is enabled.
615
     * 
616
     * Option id: <code>"org.eclipse.jdt.core.compiler.problem.redundantNullAnnotation"</code>
617
     * Possible values: <code>{ "error", "warning", "ignore" }</code>
618
     * Default: <code>"warning"</code>
619
     * 
620
     * @since 3.8
621
     * @category CompilerOptionID
622
     */
623
    public static final String COMPILER_PB_REDUNDANT_NULL_ANNOTATION = PLUGIN_ID + ".compiler.problem.redundantNullAnnotation";
624
</pre>
625
</li>
626
<li>New API added to org.eclipse.jdt.core.compiler.IProblem to signal null-related issues:
627
	<ul>
628
	<li> int RequiredNonNullButProvidedNull</li>
629
	<li> int RequiredNonNullButProvidedPotentialNull</li>
630
	<li> int RequiredNonNullButProvidedUnknown</li>
631
	<li> int MissingNullAnnotationType</li>
632
	<li> int IllegalReturnNullityRedefinition</li>
633
	<li> int IllegalRedefinitionToNonNullParameter</li>
634
	<li> int IllegalDefinitionToNonNullParameter</li>
635
	<li> int ParameterLackingNonNullAnnotation</li>
636
	<li> int ParameterLackingNullableAnnotation</li>
637
	<li> int PotentialNullMessageSendReference</li>
638
	<li> int RedundantNullCheckOnNonNullMessageSend</li>
639
	<li> int CannotImplementIncompatibleNullness</li>
640
	<li> int RedundantNullAnnotation</li>
641
	<li> int IllegalAnnotationForBaseType</li>
642
	</ul>
643
</ul>
644
645
<h3>Problem Reports Fixed</h3>
646
<a href="https://bugs.eclipse.org/bugs/show_bug.cgi?id=363858">363858</a>
647
[dom] early throwing of AbortCompilation causes NPE in CompilationUnitResolver
648
<br><a href="https://bugs.eclipse.org/bugs/show_bug.cgi?id=331647">331647</a>
649
[compiler][null] support flexible default mechanism for null-annotations
650
<br><a href="https://bugs.eclipse.org/bugs/show_bug.cgi?id=334457">334457</a>
651
[compiler][null] check compatibility of inherited null contracts
652
<br><a href="https://bugs.eclipse.org/bugs/show_bug.cgi?id=186342">186342</a>
653
[compiler][null] Using annotations for null checking
654
655
<hr><h1>
656
Eclipse Platform Build Notes<br>
657
Java development tools core</h1>
658
Eclipse SDK 3.8.0 - November 29, 2011
659
<h2>What's new in this drop</h2>
660
661
<h3>Problem Reports Fixed</h3>
662
<a href="https://bugs.eclipse.org/bugs/show_bug.cgi?id=340945">340945</a>
663
Extension Request of JavaContentAssistInvocationContext
664
<br><a href="https://bugs.eclipse.org/bugs/show_bug.cgi?id=364672">364672</a>
665
[compiler] ecj fails to compile valid calls to varargs method
666
667
<a name="v_C21"></a>
668
<hr><h1>
669
Eclipse Platform Build Notes<br>
670
Java development tools core</h1>
671
Eclipse SDK 3.8.0 - November 22, 2011
672
<h2>What's new in this drop</h2>
673
674
<h3>Problem Reports Fixed</h3>
675
<a href="https://bugs.eclipse.org/bugs/show_bug.cgi?id=350738">350738</a>
676
&quot;The method is never used locally&quot; is not shown for parameterized recursive methods
677
<br><a href="https://bugs.eclipse.org/bugs/show_bug.cgi?id=361053">361053</a>
678
java.lang.VerifyError on try-with-resources
679
<br><a href="https://bugs.eclipse.org/bugs/show_bug.cgi?id=346038">346038</a>
680
[1.5][compiler] ecj vs. javac differ for methods using vararg parameters of different primitive types
681
<br><a href="https://bugs.eclipse.org/bugs/show_bug.cgi?id=346039">346039</a>
682
[1.5][compiler] ecj vs. javac differ for varargs overloading
683
<br><a href="https://bugs.eclipse.org/bugs/show_bug.cgi?id=362279">362279</a>
684
ecj vs. javac differ for automatic boxing of implicitly converted types
685
<br><a href="https://bugs.eclipse.org/bugs/show_bug.cgi?id=362591">362591</a>
686
VerifyError: Inconsistent stackmap frames
687
688
<a name="v_C20"></a>
689
<hr><h1>
690
Eclipse Platform Build Notes<br>
691
Java development tools core</h1>
692
Eclipse SDK 3.8.0 - November 15, 2011
693
<br>Project org.eclipse.jdt.core v_C20
694
(<a href="http://dev.eclipse.org/viewcvs/index.cgi/org.eclipse.jdt.core/?only_with_tag=v_C20">cvs</a>).
695
<h2>What's new in this drop</h2>
696
697
<h3>Problem Reports Fixed</h3>
698
<a href="https://bugs.eclipse.org/bugs/show_bug.cgi?id=361327">361327</a>
699
Static import resolution does not record all static elements being imported
700
<br><a href="https://bugs.eclipse.org/bugs/show_bug.cgi?id=346042">346042</a>
701
[1.5][compiler] ecj compiles code rejected by javac for varargs parameters of inaccessible type
702
<br><a href="https://bugs.eclipse.org/bugs/show_bug.cgi?id=361938">361938</a>
703
Formerly working JLS3 parser not working -- Scanner reports com.sun.jdi.InvocationException occurred invoking method.
704
<br><a href="https://bugs.eclipse.org/bugs/show_bug.cgi?id=359284">359284</a>
705
Unnecessary checkast from null
706
<br><a href="https://bugs.eclipse.org/bugs/show_bug.cgi?id=361441">361441</a>
707
Error in JDT Core during AST creation
708
<br><a href="https://bugs.eclipse.org/bugs/show_bug.cgi?id=363293">363293</a>
709
resource leaks in org.eclipse.jdt.compiler.tool.tests
710
711
<a name="v_C19"></a>
712
<hr><h1>
713
Eclipse Platform Build Notes<br>
714
Java development tools core</h1>
715
Eclipse SDK 3.8.0 - November 8, 2011
716
<br>Project org.eclipse.jdt.core v_C19
717
(<a href="http://dev.eclipse.org/viewcvs/index.cgi/org.eclipse.jdt.core/?only_with_tag=v_C19">cvs</a>).
718
<h2>What's new in this drop</h2>
719
720
<h3>Problem Reports Fixed</h3>
721
<a href="https://bugs.eclipse.org/bugs/show_bug.cgi?id=361922">361922</a>
722
Fup of 357425: ensure all reported regressions are witnessed by tests
723
<br><a href="https://bugs.eclipse.org/bugs/show_bug.cgi?id=354766">354766</a>
724
Javadoc content does not appear in content assist info window for non-static inner class constructors
725
726
<a name="v_C18"></a>
727
<hr><h1>
728
Eclipse Platform Build Notes<br>
729
Java development tools core</h1>
730
Eclipse SDK 3.8.0 - October 25, 2011 - 3.8.0 M3
731
<br>Project org.eclipse.jdt.core v_C18
732
(<a href="http://dev.eclipse.org/viewcvs/index.cgi/org.eclipse.jdt.core/?only_with_tag=v_C18">cvs</a>).
733
<h2>What's new in this drop</h2>
734
735
<h3>Problem Reports Fixed</h3>
736
737
<a name="v_C17"></a>
738
<hr><h1>
739
Eclipse Platform Build Notes<br>
740
Java development tools core</h1>
741
Eclipse SDK 3.8.0 - October 20, 2011
742
<br>Project org.eclipse.jdt.core v_C17
743
(<a href="http://dev.eclipse.org/viewcvs/index.cgi/org.eclipse.jdt.core/?only_with_tag=v_C17">cvs</a>).
744
<h2>What's new in this drop</h2>
745
<ul>
746
<li>Added a new API OUTPUT_LOCATION_OVERLAPPING_ANOTHER_SOURCE(see bug <a href="https://bugs.eclipse.org/bugs/show_bug.cgi?id=287164">287164</a> for details):
747
<pre>
748
/**
749
 * Status constant indicating that the default or specific output folder is overlapping
750
 * with another source location.
751
 * @since 3.8 
752
 */
753
public static final int OUTPUT_LOCATION_OVERLAPPING_ANOTHER_SOURCE = 1013;
754
</pre>
755
</li>
756
757
<li>Added a new option CORE_OUTPUT_LOCATION_OVERLAPPING_ANOTHER_SOURCE to report an output location overlapping another source location(see bug <a href="https://bugs.eclipse.org/bugs/show_bug.cgi?id=287164">287164</a> for details):
758
<pre>
759
/**
760
 * Core option ID: Reporting an output location overlapping another source location.
761
 * Indicate the severity of the problem reported when a source entry's output location overlaps another
762
 * source entry.
763
 * 
764
 * Option id:"org.eclipse.jdt.core.classpath.outputOverlappingAnotherSource"
765
 * Possible values:{ "error", "warning", "ignore" }
766
 * Default:"error"
767
 * 
768
 * @since 3.8
769
 */
770
public static final String CORE_OUTPUT_LOCATION_OVERLAPPING_ANOTHER_SOURCE = PLUGIN_ID + ".classpath.outputOverlappingAnotherSource";
771
</pre>
772
</li>
773
</ul>
774
<h3>Problem Reports Fixed</h3>
775
<a href="https://bugs.eclipse.org/bugs/show_bug.cgi?id=287164">287164</a>
776
Report build path error if source folder has other source folder as output folder
777
<br><a href="https://bugs.eclipse.org/bugs/show_bug.cgi?id=359721">359721</a>
778
[options] add command line option for new warning token &quot;resource&quot;
779
<br><a href="https://bugs.eclipse.org/bugs/show_bug.cgi?id=343480">343480</a>
780
[compiler] Incorrect/confusing error message on inner class static field declaration
781
<br><a href="https://bugs.eclipse.org/bugs/show_bug.cgi?id=318401">318401</a>
782
FUP of 317858: Clarify eclipse compiler behavior on imports &amp; shadowing
783
<br><a href="https://bugs.eclipse.org/bugs/show_bug.cgi?id=360317">360317</a>
784
[compiler] report switch over enum in 1.4- mode
785
<br><a href="https://bugs.eclipse.org/bugs/show_bug.cgi?id=360164">360164</a>
786
Compile error in XSDImpl
787
<br><a href="https://bugs.eclipse.org/bugs/show_bug.cgi?id=359727">359727</a>
788
[1.7][doc] Update doc for new resource leak warnings
789
790
<a name="v_C16"></a>
791
<hr><h1>
792
Eclipse Platform Build Notes<br>
793
Java development tools core</h1>
794
Eclipse SDK 3.8.0 - October 18, 2011
795
<br>Project org.eclipse.jdt.core v_C16
796
(<a href="http://dev.eclipse.org/viewcvs/index.cgi/org.eclipse.jdt.core/?only_with_tag=v_C16">cvs</a>).
797
<h2>What's new in this drop</h2>
798
<ul>
799
<li>Added a new API IBootstrapMethodsEntry to describe the bootstrap method table entry(see bug <a href="https://bugs.eclipse.org/bugs/show_bug.cgi?id=359943">359943</a> for details):
800
<pre>
801
/**
802
 * Description of a bootstrap method table entry as specified in the JVM specifications.
803
 *
804
 * This interface may be implemented by clients.
805
 *
806
 * @since 3.8
807
 */
808
public interface IBootstrapMethodsEntry;
809
</pre>
810
</li>
811
812
<li>Added a new API IBootstrapMethodsAttribute to describe the bootstrap method attribute(see bug <a href="https://bugs.eclipse.org/bugs/show_bug.cgi?id=359943">359943</a> for details):
813
<pre>
814
/**
815
 * Description of a bootstrap methods attribute as described in the JVM specifications.
816
 *
817
 * This interface may be implemented by clients.
818
 *
819
 * @since 3.8
820
 */
821
public interface IBootstrapMethodsAttribute
822
</pre>
823
</li>
824
825
<li>Added a new API in IBootstrapMethodsAttribute to obtain the number of bootstrap methods of this entry(see bug <a href="https://bugs.eclipse.org/bugs/show_bug.cgi?id=359943">359943</a> for details):
826
<pre>
827
/**
828
 * Answer back the number of bootstrap methods of this entry as specified in
829
 * the JVM specifications.
830
 *
831
 * @return the number of bootstrap methods of this entry as specified in
832
 * the JVM specifications
833
 */
834
int getBootstrapMethodsLength();
835
</pre>
836
</li>
837
838
<li>Added a new API in IBootstrapMethodsAttribute to obtain the bootstrap methods table of this entry(see bug <a href="https://bugs.eclipse.org/bugs/show_bug.cgi?id=359943">359943</a> for details):
839
<pre>
840
/**
841
 * Answer back the bootstrap methods table of this entry as specified in
842
 * the JVM specifications. Answer an empty array if none.
843
 *
844
 * @return the bootstrap methods table of this entry as specified in
845
 * the JVM specifications. Answer an empty array if none
846
 */
847
IBootstrapMethodsEntry[] getBootstrapMethods();
848
</pre>
849
</li>
850
851
<li>Added IConstantPoolEntry2 to describe the new constant pool entry from Java 7 onwards(see bug <a href="https://bugs.eclipse.org/bugs/show_bug.cgi?id=359943">359943</a> for details):
852
<pre>
853
/**
854
 * Description of the new constant pool entry as described in the JVM specifications
855
 * added for Java 7 support.
856
 * Its contents is initialized according to its kind.
857
 *
858
 * This interface may be implemented by clients.
859
 *
860
 * @since 3.8
861
 */
862
public interface IConstantPoolEntry2
863
</pre>
864
</li>
865
866
<li>Added new API in IConstantPoolEntry2 to return the descriptor index for MethodType entry(see bug <a href="https://bugs.eclipse.org/bugs/show_bug.cgi?id=359943">359943</a> for details):
867
<pre>
868
/**
869
 * Returns the descriptor index. This value is set only when decoding a MethodType entry.
870
 * The value is unspecified otherwise. The corresponding UTF8 value can be retrieved by using
871
 * {@link #getMethodDescriptor()}.
872
 *
873
 * @return the descriptor index. This value is set only when decoding a MethodType entry.
874
 * @see IConstantPoolConstant#CONSTANT_MethodType
875
 */
876
int getDescriptorIndex();
877
</pre>
878
</li>
879
880
<li>Added new API in IConstantPoolEntry2 to return the reference kind for MethodHandle entry(see bug <a href="https://bugs.eclipse.org/bugs/show_bug.cgi?id=359943">359943</a> for details):
881
<pre>
882
/**
883
 * Returns the reference kind. This value is set only when decoding a MethodHandle entry.
884
 * The value is unspecified otherwise.
885
 *
886
 * @return the reference kind. This value is set only when decoding a MethodHandle entry.
887
 * @see IConstantPoolConstant#CONSTANT_MethodHandle
888
 */
889
int getReferenceKind();
890
</pre>
891
</li>
892
893
<li>Added new API in IConstantPoolEntry2 to return the reference index for MethodHandle entry(see bug <a href="https://bugs.eclipse.org/bugs/show_bug.cgi?id=359943">359943</a> for details):
894
<pre>
895
/**
896
 * Returns the reference index. This value is set only when decoding a MethodHandle entry.
897
 * The value is unspecified otherwise.
898
 *
899
 * @return the reference kind. This value is set only when decoding a MethodHandle entry.
900
 * @see IConstantPoolConstant#CONSTANT_MethodHandle
901
 */
902
int getReferenceIndex();
903
</pre>
904
</li>
905
906
<li>Added new API in IConstantPoolEntry2 to return the bootstrap method attribute index(see bug <a href="https://bugs.eclipse.org/bugs/show_bug.cgi?id=359943">359943</a> for details):
907
<pre>
908
/**
909
 * Returns the bootstrap method attribute index. This value is set only when decoding a InvokeDynamic entry.
910
 * The value is unspecified otherwise.
911
 *
912
 * @return the reference kind. This value is set only when decoding a MethodHandle entry.
913
 * @see IConstantPoolConstant#CONSTANT_InvokeDynamic
914
 */
915
int getBootstrapMethodAttributeIndex();
916
</pre>
917
</li>
918
919
<li>Added new API in IByteCodeVisitor(see bug <a href="https://bugs.eclipse.org/bugs/show_bug.cgi?id=359943">359943</a> for details):
920
<pre>
921
	/**
922
	 * @since 3.8
923
	 */
924
	void _invokedynamic(
925
			int pc,
926
			int index,
927
			IConstantPoolEntry invokeDynamic);
928
</pre>
929
<p>
930
This has been added in place of the deprecated API
931
<pre>
932
	void _invokedynamic(
933
			int pc,
934
			int index,
935
			IConstantPoolEntry nameEntry,
936
			IConstantPoolEntry descriptorEntry);
937
</pre>
938
</li>
939
</ul>
940
<h3>Problem Reports Fixed</h3>
941
<a href="https://bugs.eclipse.org/bugs/show_bug.cgi?id=359943">359943</a>
942
invokedynamic in generated class file is not correctly recognized by the eclipse compiler
943
<br><a href="https://bugs.eclipse.org/bugs/show_bug.cgi?id=360644">360644</a>
944
Scope.isDefinedInSameUnit(ReferenceBinding) fails for a ParameterizedTypeBinding
945
<br><a href="https://bugs.eclipse.org/bugs/show_bug.cgi?id=358762">358762</a>
946
NPE in JDT compiler
947
<br><a href="https://bugs.eclipse.org/bugs/show_bug.cgi?id=360328">360328</a>
948
[compiler][null] detect null problems in nested code (local class inside a loop)
949
950
<a name="v_C15"></a>
951
<hr><h1>
952
Eclipse Platform Build Notes<br>
953
Java development tools core</h1>
954
Eclipse SDK 3.8.0 - October 11, 2011
955
<br>Project org.eclipse.jdt.core v_C15
956
(<a href="http://dev.eclipse.org/viewcvs/index.cgi/org.eclipse.jdt.core/?only_with_tag=v_C15">cvs</a>).
957
<h2>What's new in this drop</h2>
958
959
<h3>Problem Reports Fixed</h3>
960
<a href="https://bugs.eclipse.org/bugs/show_bug.cgi?id=350285">350285</a>
961
ASTRewrite destroys formatting on CatchClause#setBody(copyTarget)
962
<br><a href="https://bugs.eclipse.org/bugs/show_bug.cgi?id=353474">353474</a>
963
type converters should include more annotations
964
965
<a name="v_C14"></a>
966
<hr><h1>
967
Eclipse Platform Build Notes<br>
968
Java development tools core</h1>
969
Eclipse SDK 3.8.0 - October 5, 2011
970
<br>Project org.eclipse.jdt.core v_C14
971
(<a href="http://dev.eclipse.org/viewcvs/index.cgi/org.eclipse.jdt.core/?only_with_tag=v_C14">cvs</a>).
972
<h2>What's new in this drop</h2>
973
974
<h3>Problem Reports Fixed</h3>
975
<a href="https://bugs.eclipse.org/bugs/show_bug.cgi?id=354181">354181</a>
976
migrate jdt.core to git
977
<br><a href="https://bugs.eclipse.org/bugs/show_bug.cgi?id=359831">359831</a>
978
Fix messages for &quot;new warning for missing try-with-resources&quot;
979
980
<a name="v_C13"></a>
981
<hr><h1>
982
Eclipse Platform Build Notes<br>
983
Java development tools core</h1>
984
Eclipse SDK 3.8.0 - October 3, 2011
985
<br>Project org.eclipse.jdt.core v_C13
986
(<a href="http://dev.eclipse.org/viewcvs/index.cgi/org.eclipse.jdt.core/?only_with_tag=v_C13">cvs</a>).
987
<h2>What's new in this drop</h2>
988
<ul>
989
<li>New Javacore option org.eclipse.jdt.core.JavaCore.COMPILER_PB_UNCLOSED_CLOSEABLE to raise a warning or error
990
  when a resource of type Closeable or AutoCloseable is not closed locally.  
991
(see details in bug <a href="https://bugs.eclipse.org/bugs/show_bug.cgi?id=349326">349326</a>):
992
<pre>
993
	/**
994
	 * Compiler option ID: Reporting a resource that is not closed properly.
995
	 *
996
	 * When enabled, the compiler will issue an error or a warning if
997
	 * a local variable holds a value of type <code>java.lang.AutoCloseable</code> (compliance>=1.7) 
998
	 * or a value of type <code>java.io.Closeable</code> (compliance<=1.6) and if
999
	 * flow analysis shows that the method <code>close()</code> is not invoked locally on that value.
1000
	 * 
1001
	 * Option id: <code>"org.eclipse.jdt.core.compiler.problem.reportUnclosedCloseable"</code>
1002
	 * Possible values: <code>{ "error", "warning", "ignore" }</code>
1003
	 * Default: <code>"warning"</code>
1004
	 *
1005
	 * @since 3.8
1006
	 * @category CompilerOptionID
1007
	 */
1008
	public static final String COMPILER_PB_UNCLOSED_CLOSEABLE = PLUGIN_ID + ".compiler.problem.unclosedCloseable"; //$NON-NLS-1$
1009
</pre>
1010
</li>
1011
<li>New Javacore option org.eclipse.jdt.core.JavaCore.COMPILER_PB_POTENTIALLY_UNCLOSED_CLOSEABLE to raise a warning or error
1012
  when a resource of type Closeable or AutoCloseable is not definitely closed locally.
1013
(see details in bug <a href="https://bugs.eclipse.org/bugs/show_bug.cgi?id=349326">349326</a>):
1014
<pre>
1015
	/**
1016
	 * Compiler option ID: Reporting a resource that may not be closed properly.
1017
	 * 
1018
	 * When enabled, the compiler will issue an error or a warning if
1019
	 * a local variable holds a value of type <code>java.lang.AutoCloseable</code> (compliance>=1.7) 
1020
	 * or a value of type <code>java.io.Closeable</code> (compliance<=1.6) and if
1021
	 * flow analysis shows that the method <code>close()</code> is 
1022
	 * not invoked locally on that value for all execution paths.
1023
	 * 
1024
	 * Option id: <code>"org.eclipse.jdt.core.compiler.problem.reportPotentiallyUnclosedCloseable"</code>
1025
	 * Possible values: <code>{ "error", "warning", "ignore" }</code>
1026
	 * Default: <code>"ignore"</code>
1027
	 * 
1028
	 * @since 3.8
1029
	 * @category CompilerOptionID
1030
	 */
1031
	public static final String COMPILER_PB_POTENTIALLY_UNCLOSED_CLOSEABLE = PLUGIN_ID + ".compiler.problem.potentiallyUnclosedCloseable"; //$NON-NLS-1$
1032
</pre>
1033
</li>
1034
<li>New Javacore option org.eclipse.jdt.core.JavaCore.COMPILER_PB_EXPLICITLY_CLOSED_AUTOCLOSEABLE to raise a warning or error
1035
  when a resource of type AutoCloseable is closed explicitly rather than using a try-with-resources block.
1036
(see details in bug <a href="https://bugs.eclipse.org/bugs/show_bug.cgi?id=349326">349326</a>):
1037
<pre>
1038
	/**
1039
	 * Compiler option ID: Reporting a resource that is not managed by try-with-resources.
1040
	 * 
1041
	 * When enabled, the compiler will issue an error or a warning if a local variable 
1042
	 * holds a value of type <code>java.lang.AutoCloseable</code>, and if the method
1043
	 * <code>close()</code> is explicitly invoked on that resource, but the resource is
1044
	 * not managed by a try-with-resources block.
1045
	 * 
1046
	 * Option id: <code>"org.eclipse.jdt.core.compiler.problem.reportPotentiallyUnclosedCloseable"</code>
1047
	 * Possible values: <code>{ "error", "warning", "ignore" }</code>
1048
	 * Default: <code>"ignore"</code>
1049
	 * 
1050
	 * @since 3.8
1051
	 * @category CompilerOptionID
1052
	 */
1053
	public static final String COMPILER_PB_EXPLICITLY_CLOSED_AUTOCLOSEABLE = PLUGIN_ID + ".compiler.problem.explicitlyClosedAutoCloseable"; //$NON-NLS-1$
1054
</pre>
1055
</li>
1056
</ul>
1057
1058
<h3>Problem Reports Fixed</h3>
1059
<a href="https://bugs.eclipse.org/bugs/show_bug.cgi?id=359495">359495</a>
1060
[1.7][compiler] VerifyError in try-finally block with lock encompassing for-each block and unlock in finally clause
1061
<br><a href="https://bugs.eclipse.org/bugs/show_bug.cgi?id=161129">161129</a>
1062
[batch][compiler] Add -warn:all to report all warnings
1063
<br><a href="https://bugs.eclipse.org/bugs/show_bug.cgi?id=359646">359646</a>
1064
Formatter fails silently if Java source contains 0x8000000000000000L
1065
<br><a href="https://bugs.eclipse.org/bugs/show_bug.cgi?id=256796">256796</a>
1066
[compiler] dead code detection: &quot;if (DEBUG) return;&quot; should also be trivial IF stmt
1067
<br><a href="https://bugs.eclipse.org/bugs/show_bug.cgi?id=359334">359334</a>
1068
Analysis for resource leak warnings does not consider exceptions as method exit points
1069
<br><a href="https://bugs.eclipse.org/bugs/show_bug.cgi?id=359362">359362</a>
1070
FUP of bug 349326: Resource leak on non-Closeable resource.
1071
<br><a href="https://bugs.eclipse.org/bugs/show_bug.cgi?id=348186">348186</a>
1072
[compiler] Improve wording for the warning for masked/hidden catch block
1073
<br><a href="https://bugs.eclipse.org/bugs/show_bug.cgi?id=355838">355838</a>
1074
[compiler] ecj compiles the code that javac6 rejects
1075
<br><a href="https://bugs.eclipse.org/bugs/show_bug.cgi?id=349326">349326</a>
1076
[1.7] new warning for missing try-with-resources
1077
<br><a href="https://bugs.eclipse.org/bugs/show_bug.cgi?id=354502">354502</a>
1078
Incorrect Compiler Warning: &quot;Method can be declared as static&quot;
1079
<br><a href="https://bugs.eclipse.org/bugs/show_bug.cgi?id=241834">241834</a>
1080
[search] ClassCastException during move class refactoring
1081
<br><a href="https://bugs.eclipse.org/bugs/show_bug.cgi?id=358827">358827</a>
1082
[1.7] exception analysis for t-w-r spoils null analysis
1083
1084
<a name="v_C12"></a>
1085
<hr><h1>
1086
Eclipse Platform Build Notes<br>
1087
Java development tools core</h1>
1088
Eclipse SDK 3.8.0 - September 23, 2011
1089
<br>Project org.eclipse.jdt.core v_C12
1090
(<a href="http://dev.eclipse.org/viewcvs/index.cgi/org.eclipse.jdt.core/?only_with_tag=v_C12">cvs</a>).
1091
<h2>What's new in this drop</h2>
1092
<ul>
1093
<li>Tagging to prepare for the git migration</li>
1094
</ul>
1095
1096
<h3>Problem Reports Fixed</h3>
1097
1098
<a name="v_C11"></a>
1099
<hr><h1>
1100
Eclipse Platform Build Notes<br>
1101
Java development tools core</h1>
1102
Eclipse SDK 3.8.0 - September 20, 2011
1103
<br>Project org.eclipse.jdt.core v_C11
1104
(<a href="http://dev.eclipse.org/viewcvs/index.cgi/org.eclipse.jdt.core/?only_with_tag=v_C11">cvs</a>).
1105
<h2>What's new in this drop</h2>
1106
1107
<h3>Problem Reports Fixed</h3>
1108
<a href="https://bugs.eclipse.org/bugs/show_bug.cgi?id=357110">357110</a>
1109
Problem with inner classes referenced from jars or class folders: &quot;The type ... cannot be resolved&quot;
1110
<br><a href="https://bugs.eclipse.org/bugs/show_bug.cgi?id=357471">357471</a>
1111
ASTParser cannot resolve binding of PackageDeclaration if class name is equal to the first segment of the package name
1112
1113
<a name="v_C10"></a>
1114
<hr><h1>
1115
Eclipse Platform Build Notes<br>
1116
Java development tools core</h1>
1117
Eclipse SDK 3.8.0 - September 13, 2011 - 3.8.0 M2
1118
<br>Project org.eclipse.jdt.core v_C10
1119
(<a href="http://dev.eclipse.org/viewcvs/index.cgi/org.eclipse.jdt.core/?only_with_tag=v_C10">cvs</a>).
1120
<h2>What's new in this drop</h2>
1121
1122
<h3>Problem Reports Fixed</h3>
1123
<a href="https://bugs.eclipse.org/bugs/show_bug.cgi?id=357259">357259</a>
1124
[dom] AST#newArrayType(Type, int) should allow array type as argument
1125
1126
<a name="v_C09"></a>
1127
<hr><h1>
1128
Eclipse Platform Build Notes<br>
1129
Java development tools core</h1>
1130
Eclipse SDK 3.8.0 - September 9, 2011
1131
<br>Project org.eclipse.jdt.core v_C09
1132
(<a href="http://dev.eclipse.org/viewcvs/index.cgi/org.eclipse.jdt.core/?only_with_tag=v_C09">cvs</a>).
1133
<h2>What's new in this drop</h2>
1134
1135
<h3>Problem Reports Fixed</h3>
1136
<a href="https://bugs.eclipse.org/bugs/show_bug.cgi?id=354332">354332</a>
1137
DeltaProcessor exhibits O(N^2) behavior
1138
<br><a href="https://bugs.eclipse.org/bugs/show_bug.cgi?id=355605">355605</a>
1139
NPE in HierarchyResolver
1140
<br><a href="https://bugs.eclipse.org/bugs/show_bug.cgi?id=347396">347396</a>
1141
ASTParser returns empty or partial AST if we parse the the body contains empty for loop
1142
<br><a href="https://bugs.eclipse.org/bugs/show_bug.cgi?id=356746">356746</a>
1143
ECJ accepts illegal unicode escape sequences
1144
<br><a href="https://bugs.eclipse.org/bugs/show_bug.cgi?id=337935">337935</a>
1145
Test failures when run as an IDE (org.eclipse.sdk.ide)
1146
45
<a name="v_C08"></a>
1147
<a name="v_C08"></a>
46
<hr><h1>
1148
<hr><h1>
47
Eclipse Platform Build Notes<br>
1149
Eclipse Platform Build Notes<br>
48
Java development tools core</h1>
1150
Java development tools core</h1>
49
Eclipse SDK 3.8.0 - %date% - 3.8.0 M2
1151
Eclipse SDK 3.8.0 - September 6, 2011
50
<br>Project org.eclipse.jdt.core v_C08
1152
<br>Project org.eclipse.jdt.core v_C08
51
(<a href="http://dev.eclipse.org/viewcvs/index.cgi/org.eclipse.jdt.core/?only_with_tag=v_C08">cvs</a>).
1153
(<a href="http://dev.eclipse.org/viewcvs/index.cgi/org.eclipse.jdt.core/?only_with_tag=v_C08">cvs</a>).
52
<h2>What's new in this drop</h2>
1154
<h2>What's new in this drop</h2>
53
1155
54
<h3>Problem Reports Fixed</h3>
1156
<h3>Problem Reports Fixed</h3>
55
<a href="https://bugs.eclipse.org/bugs/show_bug.cgi?id=24804">24804</a>
1157
<a href="https://bugs.eclipse.org/bugs/show_bug.cgi?id=356325">356325</a>
1158
[select] Open declaration on a constructor of a local class with type parameters doesn't work
1159
<br><a href="https://bugs.eclipse.org/bugs/show_bug.cgi?id=24804">24804</a>
56
Organize imports wipes comments between statements [code manipulation]
1160
Organize imports wipes comments between statements [code manipulation]
57
<br><a href="https://bugs.eclipse.org/bugs/show_bug.cgi?id=356363">356363</a>
1161
<br><a href="https://bugs.eclipse.org/bugs/show_bug.cgi?id=356363">356363</a>
58
Many links to java.sun.com are broken
1162
Many links to java.sun.com are broken
Lines 143-149 Link Here
143
 * Returns the binding key of the declaring type of the element represented by this binding key. If the binding key
1247
 * Returns the binding key of the declaring type of the element represented by this binding key. If the binding key
144
 * does not represent a member or if the member doesn't have a declaring type, returns <code>null</code>.
1248
 * does not represent a member or if the member doesn't have a declaring type, returns <code>null</code>.
145
 * 
1249
 * 
146
 * <p>
147
 * Note that only binding keys for references to methods and fields
1250
 * Note that only binding keys for references to methods and fields
148
 * are fully supported. The binding keys for declarations will not have type parameters.
1251
 * are fully supported. The binding keys for declarations will not have type parameters.
149
 * 
1252
 * 
Lines 208-214 Link Here
208
<li>Added a new API in CompletionProposal to tell whether it diamond operator can be used (see bug <a href="https://bugs.eclipse.org/bugs/show_bug.cgi?id=351444">351444</a> for details):
1311
<li>Added a new API in CompletionProposal to tell whether it diamond operator can be used (see bug <a href="https://bugs.eclipse.org/bugs/show_bug.cgi?id=351444">351444</a> for details):
209
<pre>
1312
<pre>
210
/** 
1313
/** 
211
 * Returns whether it is safe to use the '<>' (diamond) operator in place of explicitly specifying
1314
 * Returns whether it is safe to use the '&lt;&gt;' (diamond) operator in place of explicitly specifying
212
 * type arguments for this proposal. 
1315
 * type arguments for this proposal. 
213
 * 
1316
 * 
214
 * This is only relevant for source level 1.7 or greater.
1317
 * This is only relevant for source level 1.7 or greater.
Lines 227-233 Link Here
227
	/**
1330
	/**
228
	 * Compiler option ID: Reporting redundant specification of type arguments in class instance creation expressions.
1331
	 * Compiler option ID: Reporting redundant specification of type arguments in class instance creation expressions.
229
	 * When enabled, the compiler will issue an error or a warning if type arguments are used in a class instance creation,
1332
	 * When enabled, the compiler will issue an error or a warning if type arguments are used in a class instance creation,
230
	 * when the '<>' operator can be used instead.
1333
	 * when the '&lt;&gt;' operator can be used instead.
231
	 *
1334
	 *
232
	 * This option only has an effect if the compiler compliance is 1.7 or greater.
1335
	 * This option only has an effect if the compiler compliance is 1.7 or greater.
233
	 * 
1336
	 * 
(-)a/org.eclipse.jdt.core/codeassist/org/eclipse/jdt/internal/codeassist/CompletionEngine.java (+1 lines)
Lines 1502-1507 Link Here
1502
					this.lookupEnvironment,
1502
					this.lookupEnvironment,
1503
					scope,
1503
					scope,
1504
					astNode,
1504
					astNode,
1505
					astNodeParent,
1505
					this.owner,
1506
					this.owner,
1506
					this.parser);
1507
					this.parser);
1507
		}
1508
		}
(-)a/org.eclipse.jdt.core/codeassist/org/eclipse/jdt/internal/codeassist/InternalCompletionContext.java (-1 / +90 lines)
Lines 1-5 Link Here
1
/*******************************************************************************
1
/*******************************************************************************
2
 * Copyright (c) 2005, 2008 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 24-31 Link Here
24
import org.eclipse.jdt.internal.codeassist.complete.CompletionParser;
24
import org.eclipse.jdt.internal.codeassist.complete.CompletionParser;
25
import org.eclipse.jdt.internal.compiler.ast.ASTNode;
25
import org.eclipse.jdt.internal.compiler.ast.ASTNode;
26
import org.eclipse.jdt.internal.compiler.ast.CompilationUnitDeclaration;
26
import org.eclipse.jdt.internal.compiler.ast.CompilationUnitDeclaration;
27
import org.eclipse.jdt.internal.compiler.lookup.FieldBinding;
28
import org.eclipse.jdt.internal.compiler.lookup.LocalVariableBinding;
27
import org.eclipse.jdt.internal.compiler.lookup.LookupEnvironment;
29
import org.eclipse.jdt.internal.compiler.lookup.LookupEnvironment;
30
import org.eclipse.jdt.internal.compiler.lookup.MethodBinding;
28
import org.eclipse.jdt.internal.compiler.lookup.Scope;
31
import org.eclipse.jdt.internal.compiler.lookup.Scope;
32
import org.eclipse.jdt.internal.compiler.util.ObjectVector;
29
33
30
34
31
/**
35
/**
Lines 65-70 Link Here
65
			LookupEnvironment lookupEnvironment,
69
			LookupEnvironment lookupEnvironment,
66
			Scope scope,
70
			Scope scope,
67
			ASTNode astNode,
71
			ASTNode astNode,
72
			ASTNode astNodeParent,
68
			WorkingCopyOwner owner,
73
			WorkingCopyOwner owner,
69
			CompletionParser parser) {
74
			CompletionParser parser) {
70
		this.isExtended = true;
75
		this.isExtended = true;
Lines 76-81 Link Here
76
					lookupEnvironment,
81
					lookupEnvironment,
77
					scope,
82
					scope,
78
					astNode,
83
					astNode,
84
					astNodeParent,
79
					owner,
85
					owner,
80
					parser);
86
					parser);
81
	}
87
	}
Lines 368-371 Link Here
368
	public boolean isInJavadocText() {
374
	public boolean isInJavadocText() {
369
		return (this.javadoc & CompletionOnJavadoc.TEXT) != 0;
375
		return (this.javadoc & CompletionOnJavadoc.TEXT) != 0;
370
	}
376
	}
377
	
378
	/**
379
	 * Return the completion node associated with the current completion.
380
	 *
381
	 * @return completion AST node, or null if the extendedContext is null.
382
	 * @exception UnsupportedOperationException if the context is not an extended context
383
	 *
384
	 * @see #isExtended()
385
	 */
386
	public ASTNode getCompletionNode() {
387
		if (!this.isExtended) throw new UnsupportedOperationException("Operation only supported in extended context"); //$NON-NLS-1$
388
	
389
		if (this.extendedContext == null) return null;
390
	
391
		return this.extendedContext.getCompletionNode();
392
	}
393
	
394
	/**
395
	 * Return the parent AST node of the completion node associated with the current completion.
396
	 *
397
	 * @return completion parent AST node, or null if the extendedContext is null.
398
	 * @exception UnsupportedOperationException if the context is not an extended context
399
	 *
400
	 * @see #isExtended()
401
	 */
402
	public ASTNode getCompletionNodeParent() {
403
		if (!this.isExtended) throw new UnsupportedOperationException("Operation only supported in extended context"); //$NON-NLS-1$
404
	
405
		if (this.extendedContext == null) return null;
406
	
407
		return this.extendedContext.getCompletionNodeParent();
408
	}
409
	
410
	/**
411
	 * Return the bindings of all visible local variables in the current completion context.
412
	 *
413
	 * @return bindings of all visible local variables, or null if the extendedContext is null. Returned bindings are instances of
414
	 * {@link LocalVariableBinding}
415
	 * @exception UnsupportedOperationException if the context is not an extended context
416
	 *
417
	 * @see #isExtended()
418
	 */
419
	public ObjectVector getVisibleLocalVariables() {
420
		if (!this.isExtended) throw new UnsupportedOperationException("Operation only supported in extended context"); //$NON-NLS-1$
421
	
422
		if (this.extendedContext == null) return null;
423
	
424
		return this.extendedContext.getVisibleLocalVariables();
425
	}
426
	
427
	/**
428
	 * Return the bindings of all visible fields in the current completion context.
429
	 *
430
	 * @return bindings of all visible fields, or null if the extendedContext is null. Returned bindings are instances of
431
	 * {@link FieldBinding}
432
	 * @exception UnsupportedOperationException if the context is not an extended context
433
	 *
434
	 * @see #isExtended()
435
	 */
436
	public ObjectVector getVisibleFields() {
437
		if (!this.isExtended) throw new UnsupportedOperationException("Operation only supported in extended context"); //$NON-NLS-1$
438
	
439
		if (this.extendedContext == null) return null;
440
	
441
		return this.extendedContext.getVisibleFields();
442
	}
443
	
444
	/**
445
	 * Return the bindings of all visible methods in the current completion context.
446
	 *
447
	 * @return bindings of all visible methods, or null if the extendedContext is null. Returned bindings are instances of
448
	 * {@link MethodBinding}
449
	 * @exception UnsupportedOperationException if the context is not an extended context
450
	 *
451
	 * @see #isExtended()
452
	 */
453
	public ObjectVector getVisibleMethods() {
454
		if (!this.isExtended) throw new UnsupportedOperationException("Operation only supported in extended context"); //$NON-NLS-1$
455
	
456
		if (this.extendedContext == null) return null;
457
	
458
		return this.extendedContext.getVisibleMethods();
459
	}
371
}
460
}
(-)a/org.eclipse.jdt.core/codeassist/org/eclipse/jdt/internal/codeassist/InternalExtendedCompletionContext.java (+39 lines)
Lines 76-81 Link Here
76
	private LookupEnvironment lookupEnvironment;
76
	private LookupEnvironment lookupEnvironment;
77
	private Scope assistScope;
77
	private Scope assistScope;
78
	private ASTNode assistNode;
78
	private ASTNode assistNode;
79
	private ASTNode assistNodeParent;
79
	private WorkingCopyOwner owner;
80
	private WorkingCopyOwner owner;
80
81
81
	private CompletionParser parser;
82
	private CompletionParser parser;
Lines 98-103 Link Here
98
			LookupEnvironment lookupEnvironment,
99
			LookupEnvironment lookupEnvironment,
99
			Scope assistScope,
100
			Scope assistScope,
100
			ASTNode assistNode,
101
			ASTNode assistNode,
102
			ASTNode assistNodeParent,
101
			WorkingCopyOwner owner,
103
			WorkingCopyOwner owner,
102
			CompletionParser parser) {
104
			CompletionParser parser) {
103
		this.completionContext = completionContext;
105
		this.completionContext = completionContext;
Lines 106-111 Link Here
106
		this.lookupEnvironment = lookupEnvironment;
108
		this.lookupEnvironment = lookupEnvironment;
107
		this.assistScope = assistScope;
109
		this.assistScope = assistScope;
108
		this.assistNode = assistNode;
110
		this.assistNode = assistNode;
111
		this.assistNodeParent = assistNodeParent;
109
		this.owner = owner;
112
		this.owner = owner;
110
		this.parser = parser;
113
		this.parser = parser;
111
	}
114
	}
Lines 929-932 Link Here
929
		}
932
		}
930
		return false;
933
		return false;
931
	}
934
	}
935
	
936
	/**
937
	 * @see InternalCompletionContext#getCompletionNode()
938
	 */
939
	public ASTNode getCompletionNode() {
940
		return this.assistNode;
941
	}
942
	
943
	/**
944
	 * @see InternalCompletionContext#getCompletionNodeParent()
945
	 */
946
	public ASTNode getCompletionNodeParent() {
947
		// TODO Auto-generated method stub
948
		return this.assistNodeParent;
949
	}
950
	
951
	public ObjectVector getVisibleLocalVariables() {
952
		if (!this.hasComputedVisibleElementBindings) {
953
			computeVisibleElementBindings();
954
		}
955
		return this.visibleLocalVariables;
956
	}
957
	
958
	public ObjectVector getVisibleFields() {
959
		if (!this.hasComputedVisibleElementBindings) {
960
			computeVisibleElementBindings();
961
		}
962
		return this.visibleFields;
963
	}
964
	
965
	public ObjectVector getVisibleMethods() {
966
		if (!this.hasComputedVisibleElementBindings) {
967
			computeVisibleElementBindings();
968
		}
969
		return this.visibleMethods;
970
	}
932
}
971
}
(-)a/org.eclipse.jdt.core/codeassist/org/eclipse/jdt/internal/codeassist/SelectionEngine.java (-4 / +4 lines)
Lines 531-543 Link Here
531
							}
531
							}
532
						}
532
						}
533
533
534
						if ((c1 = ScannerHelper.getNumericValue(source[pos++])) > 15
534
						if ((c1 = ScannerHelper.getHexadecimalValue(source[pos++])) > 15
535
							|| c1 < 0
535
							|| c1 < 0
536
							|| (c2 = ScannerHelper.getNumericValue(source[pos++])) > 15
536
							|| (c2 = ScannerHelper.getHexadecimalValue(source[pos++])) > 15
537
							|| c2 < 0
537
							|| c2 < 0
538
							|| (c3 = ScannerHelper.getNumericValue(source[pos++])) > 15
538
							|| (c3 = ScannerHelper.getHexadecimalValue(source[pos++])) > 15
539
							|| c3 < 0
539
							|| c3 < 0
540
							|| (c4 = ScannerHelper.getNumericValue(source[pos++])) > 15
540
							|| (c4 = ScannerHelper.getHexadecimalValue(source[pos++])) > 15
541
							|| c4 < 0) {
541
							|| c4 < 0) {
542
							return false;
542
							return false;
543
						} else {
543
						} else {
(-)a/org.eclipse.jdt.core/codeassist/org/eclipse/jdt/internal/codeassist/complete/CompletionParser.java (-2 / +6 lines)
Lines 1-5 Link Here
1
/*******************************************************************************
1
/*******************************************************************************
2
 * Copyright (c) 2000, 2011 IBM Corporation and others.
2
 * Copyright (c) 2000, 2012 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 1167-1173 Link Here
1167
							if (prevKind == K_BETWEEN_NEW_AND_LEFT_BRACKET) {
1167
							if (prevKind == K_BETWEEN_NEW_AND_LEFT_BRACKET) {
1168
								
1168
								
1169
								AllocationExpression exp;
1169
								AllocationExpression exp;
1170
								if (this.expressionPtr > -1 && this.expressionStack[this.expressionPtr] instanceof AllocationExpression) {
1170
								if (this.expressionPtr > -1 && this.expressionStack[this.expressionPtr] instanceof AllocationExpression 
1171
										&& this.invocationType == QUALIFIED_ALLOCATION) { // https://bugs.eclipse.org/bugs/show_bug.cgi?id=361963
1171
									exp = new QualifiedAllocationExpression();
1172
									exp = new QualifiedAllocationExpression();
1172
									exp.type = ref;
1173
									exp.type = ref;
1173
									((QualifiedAllocationExpression)exp).enclosingInstance = this.expressionStack[this.expressionPtr];
1174
									((QualifiedAllocationExpression)exp).enclosingInstance = this.expressionStack[this.expressionPtr];
Lines 2627-2632 Link Here
2627
				arg.annotations = new Annotation[length],
2628
				arg.annotations = new Annotation[length],
2628
				0,
2629
				0,
2629
				length);
2630
				length);
2631
			RecoveredType currentRecoveryType = this.currentRecoveryType();
2632
			if (currentRecoveryType != null)
2633
				currentRecoveryType.annotationsConsumed(arg.annotations);
2630
		}
2634
		}
2631
2635
2632
		arg.isCatchArgument = topKnownElementKind(COMPLETION_OR_ASSIST_PARSER) == K_BETWEEN_CATCH_AND_RIGHT_PAREN;
2636
		arg.isCatchArgument = topKnownElementKind(COMPLETION_OR_ASSIST_PARSER) == K_BETWEEN_CATCH_AND_RIGHT_PAREN;
(-)a/org.eclipse.jdt.core/codeassist/org/eclipse/jdt/internal/codeassist/complete/CompletionScanner.java (-12 / +12 lines)
Lines 552-564 Link Here
552
									while (this.source[this.currentPosition] == 'u') {
552
									while (this.source[this.currentPosition] == 'u') {
553
										this.currentPosition++;
553
										this.currentPosition++;
554
									}
554
									}
555
									if ((c1 = ScannerHelper.getNumericValue(this.source[this.currentPosition++])) > 15
555
									if ((c1 = ScannerHelper.getHexadecimalValue(this.source[this.currentPosition++])) > 15
556
										|| c1 < 0
556
										|| c1 < 0
557
										|| (c2 = ScannerHelper.getNumericValue(this.source[this.currentPosition++])) > 15
557
										|| (c2 = ScannerHelper.getHexadecimalValue(this.source[this.currentPosition++])) > 15
558
										|| c2 < 0
558
										|| c2 < 0
559
										|| (c3 = ScannerHelper.getNumericValue(this.source[this.currentPosition++])) > 15
559
										|| (c3 = ScannerHelper.getHexadecimalValue(this.source[this.currentPosition++])) > 15
560
										|| c3 < 0
560
										|| c3 < 0
561
										|| (c4 = ScannerHelper.getNumericValue(this.source[this.currentPosition++])) > 15
561
										|| (c4 = ScannerHelper.getHexadecimalValue(this.source[this.currentPosition++])) > 15
562
										|| c4 < 0) {
562
										|| c4 < 0) {
563
										throw new InvalidInputException(INVALID_UNICODE_ESCAPE);
563
										throw new InvalidInputException(INVALID_UNICODE_ESCAPE);
564
									} else {
564
									} else {
Lines 585-597 Link Here
585
										while (this.source[this.currentPosition] == 'u') {
585
										while (this.source[this.currentPosition] == 'u') {
586
											this.currentPosition++;
586
											this.currentPosition++;
587
										}
587
										}
588
										if ((c1 = ScannerHelper.getNumericValue(this.source[this.currentPosition++])) > 15
588
										if ((c1 = ScannerHelper.getHexadecimalValue(this.source[this.currentPosition++])) > 15
589
											|| c1 < 0
589
											|| c1 < 0
590
											|| (c2 = ScannerHelper.getNumericValue(this.source[this.currentPosition++])) > 15
590
											|| (c2 = ScannerHelper.getHexadecimalValue(this.source[this.currentPosition++])) > 15
591
											|| c2 < 0
591
											|| c2 < 0
592
											|| (c3 = ScannerHelper.getNumericValue(this.source[this.currentPosition++])) > 15
592
											|| (c3 = ScannerHelper.getHexadecimalValue(this.source[this.currentPosition++])) > 15
593
											|| c3 < 0
593
											|| c3 < 0
594
											|| (c4 = ScannerHelper.getNumericValue(this.source[this.currentPosition++])) > 15
594
											|| (c4 = ScannerHelper.getHexadecimalValue(this.source[this.currentPosition++])) > 15
595
											|| c4 < 0) {
595
											|| c4 < 0) {
596
											throw new InvalidInputException(INVALID_UNICODE_ESCAPE);
596
											throw new InvalidInputException(INVALID_UNICODE_ESCAPE);
597
										} else {
597
										} else {
Lines 623-635 Link Here
623
										}
623
										}
624
										//-------------unicode traitement ------------
624
										//-------------unicode traitement ------------
625
										int c1 = 0, c2 = 0, c3 = 0, c4 = 0;
625
										int c1 = 0, c2 = 0, c3 = 0, c4 = 0;
626
										if ((c1 = ScannerHelper.getNumericValue(this.source[index++])) > 15
626
										if ((c1 = ScannerHelper.getHexadecimalValue(this.source[index++])) > 15
627
											|| c1 < 0
627
											|| c1 < 0
628
											|| (c2 = ScannerHelper.getNumericValue(this.source[index++])) > 15
628
											|| (c2 = ScannerHelper.getHexadecimalValue(this.source[index++])) > 15
629
											|| c2 < 0
629
											|| c2 < 0
630
											|| (c3 = ScannerHelper.getNumericValue(this.source[index++])) > 15
630
											|| (c3 = ScannerHelper.getHexadecimalValue(this.source[index++])) > 15
631
											|| c3 < 0
631
											|| c3 < 0
632
											|| (c4 = ScannerHelper.getNumericValue(this.source[index++])) > 15
632
											|| (c4 = ScannerHelper.getHexadecimalValue(this.source[index++])) > 15
633
											|| c4 < 0) {
633
											|| c4 < 0) {
634
											this.currentPosition = index;
634
											this.currentPosition = index;
635
											throw new InvalidInputException(INVALID_UNICODE_ESCAPE);
635
											throw new InvalidInputException(INVALID_UNICODE_ESCAPE);
(-)a/org.eclipse.jdt.core/codeassist/org/eclipse/jdt/internal/codeassist/select/SelectionParser.java (+3 lines)
Lines 634-639 Link Here
634
				arg.annotations = new Annotation[length],
634
				arg.annotations = new Annotation[length],
635
				0,
635
				0,
636
				length);
636
				length);
637
			RecoveredType currentRecoveryType = this.currentRecoveryType();
638
			if (currentRecoveryType != null)
639
				currentRecoveryType.annotationsConsumed(arg.annotations);
637
		}
640
		}
638
641
639
		pushOnAstStack(arg);
642
		pushOnAstStack(arg);
(-)a/org.eclipse.jdt.core/compiler/org/eclipse/jdt/core/compiler/IProblem.java (-2 / +82 lines)
Lines 1-5 Link Here
1
/*******************************************************************************
1
/*******************************************************************************
2
 * Copyright (c) 2000, 2011 IBM Corporation and others.
2
 * Copyright (c) 2000, 2012 IBM Corporation and others.
3
 * All rights reserved. This program and the accompanying materials
3
 * All rights reserved. This program and the accompanying materials
4
 * are made available under the terms of the Eclipse Public License v1.0
4
 * are made available under the terms of the Eclipse Public License v1.0
5
 * which accompanies this distribution, and is available at
5
 * which accompanies this distribution, and is available at
Lines 116-122 Link Here
116
 *		Benjamin Muskalla - added the following constants
116
 *		Benjamin Muskalla - added the following constants
117
 *									MissingSynchronizedModifierInInheritedMethod
117
 *									MissingSynchronizedModifierInInheritedMethod
118
 *		Stephan Herrmann  - added the following constants
118
 *		Stephan Herrmann  - added the following constants
119
 *									UnusedObjectAllocation									
119
 *									UnusedObjectAllocation
120
 *									PotentiallyUnclosedCloseable
121
 *									PotentiallyUnclosedCloseableAtExit
122
 *									UnclosedCloseable
123
 *									UnclosedCloseableAtExit
124
 *									ExplicitlyClosedAutoCloseable
125
 * 								    RequiredNonNullButProvidedNull
126
 * 									RequiredNonNullButProvidedPotentialNull
127
 * 									RequiredNonNullButProvidedUnknown
128
 * 									NullAnnotationNameMustBeQualified
129
 * 									IllegalReturnNullityRedefinition
130
 * 									IllegalRedefinitionToNonNullParameter
131
 * 									IllegalDefinitionToNonNullParameter
132
 * 									ParameterLackingNonNullAnnotation
133
 * 									ParameterLackingNullableAnnotation
134
 * 									PotentialNullMessageSendReference
135
 * 									RedundantNullCheckOnNonNullMessageSend
136
 * 									CannotImplementIncompatibleNullness
137
 * 									RedundantNullAnnotation
138
 *									RedundantNullDefaultAnnotation
139
 *									RedundantNullDefaultAnnotationPackage
140
 *									RedundantNullDefaultAnnotationType
141
 *									RedundantNullDefaultAnnotationMethod
142
 *									ContradictoryNullAnnotations
120
 *******************************************************************************/
143
 *******************************************************************************/
121
package org.eclipse.jdt.core.compiler;
144
package org.eclipse.jdt.core.compiler;
122
145
Lines 1337-1342 Link Here
1337
	int SafeVarargsOnNonFinalInstanceMethod = MethodRelated + 805;
1360
	int SafeVarargsOnNonFinalInstanceMethod = MethodRelated + 805;
1338
	/** @since 3.7.1 */
1361
	/** @since 3.7.1 */
1339
	int PotentialHeapPollutionFromVararg = MethodRelated + 806;
1362
	int PotentialHeapPollutionFromVararg = MethodRelated + 806;
1363
	/** @since 3.8 */
1364
	int VarargsElementTypeNotVisible = MethodRelated + 807;
1365
	/** @since 3.8 */
1366
	int VarargsElementTypeNotVisibleForConstructor = ConstructorRelated + 808;
1340
	/**
1367
	/**
1341
	 * Javadoc Generic
1368
	 * Javadoc Generic
1342
	 */
1369
	 */
Lines 1394-1399 Link Here
1394
	int DiamondNotBelow17 =  TypeRelated + 883;
1421
	int DiamondNotBelow17 =  TypeRelated + 883;
1395
	/** @since 3.7.1 */
1422
	/** @since 3.7.1 */
1396
	int RedundantSpecificationOfTypeArguments = TypeRelated + 884;
1423
	int RedundantSpecificationOfTypeArguments = TypeRelated + 884;
1424
	/** @since 3.8 */
1425
	int PotentiallyUnclosedCloseable = Internal + 885;
1426
	/** @since 3.8 */
1427
	int PotentiallyUnclosedCloseableAtExit = Internal + 886;
1428
	/** @since 3.8 */
1429
	int UnclosedCloseable = Internal + 887;
1430
	/** @since 3.8 */
1431
	int UnclosedCloseableAtExit = Internal + 888;
1432
	/** @since 3.8 */
1433
	int ExplicitlyClosedAutoCloseable = Internal + 889;
1434
	/** @since 3.8 */
1435
	int SwitchOnEnumNotBelow15 = TypeRelated + 890;	// https://bugs.eclipse.org/bugs/show_bug.cgi?id=360317
1436
	/**
1437
	 * Errors/warnings from annotation based null analysis
1438
	 */
1439
	/** @since 3.8 */
1440
	int RequiredNonNullButProvidedNull = TypeRelated + 910;
1441
	/** @since 3.8 */
1442
	int RequiredNonNullButProvidedPotentialNull = TypeRelated + 911;
1443
	/** @since 3.8 */
1444
	int RequiredNonNullButProvidedUnknown = TypeRelated + 912;
1445
	// removed during 3.8 M6: ImportRelated + 913 
1446
	/** @since 3.8 */
1447
	int IllegalReturnNullityRedefinition = MethodRelated + 914;
1448
	/** @since 3.8 */
1449
	int IllegalRedefinitionToNonNullParameter = MethodRelated + 915;
1450
	/** @since 3.8 */
1451
	int IllegalDefinitionToNonNullParameter = MethodRelated + 916;
1452
	/** @since 3.8 */
1453
	int ParameterLackingNonNullAnnotation = MethodRelated + 917;
1454
	/** @since 3.8 */
1455
	int ParameterLackingNullableAnnotation = MethodRelated + 918;
1456
	/** @since 3.8 */
1457
	int PotentialNullMessageSendReference = Internal + 919;
1458
	/** @since 3.8 */
1459
	int RedundantNullCheckOnNonNullMessageSend = Internal + 920;
1460
	/** @since 3.8 */
1461
	int CannotImplementIncompatibleNullness = Internal + 921;
1462
	/** @since 3.8 */
1463
	int RedundantNullAnnotation = MethodRelated + 922;
1464
	/** @since 3.8 */
1465
	int IllegalAnnotationForBaseType = TypeRelated + 923;
1466
	/** @since 3.8 */
1467
	int RedundantNullDefaultAnnotation = Internal + 925;
1468
	/** @since 3.8 */
1469
	int RedundantNullDefaultAnnotationPackage = Internal + 926;
1470
	/** @since 3.8 */
1471
	int RedundantNullDefaultAnnotationType = Internal + 927;
1472
	/** @since 3.8 */
1473
	int RedundantNullDefaultAnnotationMethod = Internal + 928;
1474
	/** @since 3.8 */
1475
	int ContradictoryNullAnnotations = Internal + 929;
1476
1397
	/**
1477
	/**
1398
	 * External problems -- These are problems defined by other plugins
1478
	 * External problems -- These are problems defined by other plugins
1399
	 */
1479
	 */
(-)a/org.eclipse.jdt.core/compiler/org/eclipse/jdt/internal/compiler/Compiler.java (-3 / +10 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 337868 - [compiler][model] incomplete support for package-info.java when using SearchableEnvironment
10
 *     Stephan Herrmann - contributions for 
11
 *     							bug 337868 - [compiler][model] incomplete support for package-info.java when using SearchableEnvironment
12
 *     							bug 186342 - [compiler][null] Using annotations for null checking
11
 *******************************************************************************/
13
 *******************************************************************************/
12
package org.eclipse.jdt.internal.compiler;
14
package org.eclipse.jdt.internal.compiler;
13
15
Lines 695-700 Link Here
695
697
696
		// Switch the current policy and compilation result for this unit to the requested one.
698
		// Switch the current policy and compilation result for this unit to the requested one.
697
		for (int i = 0; i < maxUnits; i++) {
699
		for (int i = 0; i < maxUnits; i++) {
700
			CompilationResult unitResult = null;
698
			try {
701
			try {
699
				if (this.options.verbose) {
702
				if (this.options.verbose) {
700
					this.out.println(
703
					this.out.println(
Lines 707-714 Link Here
707
				}
710
				}
708
				// diet parsing for large collection of units
711
				// diet parsing for large collection of units
709
				CompilationUnitDeclaration parsedUnit;
712
				CompilationUnitDeclaration parsedUnit;
710
				CompilationResult unitResult =
713
				unitResult = new CompilationResult(sourceUnits[i], i, maxUnits, this.options.maxProblemsPerUnit);
711
					new CompilationResult(sourceUnits[i], i, maxUnits, this.options.maxProblemsPerUnit);
712
				long parseStart = System.currentTimeMillis();
714
				long parseStart = System.currentTimeMillis();
713
				if (this.totalUnits < this.parseThreshold) {
715
				if (this.totalUnits < this.parseThreshold) {
714
					parsedUnit = this.parser.parse(sourceUnits[i], unitResult);
716
					parsedUnit = this.parser.parse(sourceUnits[i], unitResult);
Lines 727-732 Link Here
727
				}
729
				}
728
				//} catch (AbortCompilationUnit e) {
730
				//} catch (AbortCompilationUnit e) {
729
				//	requestor.acceptResult(unitResult.tagAsAccepted());
731
				//	requestor.acceptResult(unitResult.tagAsAccepted());
732
			} catch (AbortCompilation a) {
733
				// best effort to find a way for reporting this problem:
734
				if (a.compilationResult == null)
735
					a.compilationResult = unitResult;
736
				throw a;
730
			} finally {
737
			} finally {
731
				sourceUnits[i] = null; // no longer hold onto the unit
738
				sourceUnits[i] = null; // no longer hold onto the unit
732
			}
739
			}
(-)a/org.eclipse.jdt.core/compiler/org/eclipse/jdt/internal/compiler/ast/ASTNode.java (-3 / +9 lines)
Lines 1-5 Link Here
1
/*******************************************************************************
1
/*******************************************************************************
2
 * Copyright (c) 2000, 2011 IBM Corporation and others.
2
 * Copyright (c) 2000, 2012 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 9-15 Link Here
9
 *     IBM Corporation - initial API and implementation
9
 *     IBM Corporation - initial API and implementation
10
 *     Matt McCutchen - partial fix for https://bugs.eclipse.org/bugs/show_bug.cgi?id=122995
10
 *     Matt McCutchen - partial fix for https://bugs.eclipse.org/bugs/show_bug.cgi?id=122995
11
 *     Karen Moore - fix for https://bugs.eclipse.org/bugs/show_bug.cgi?id=207411
11
 *     Karen Moore - fix for https://bugs.eclipse.org/bugs/show_bug.cgi?id=207411
12
 *     Stephan Herrmann <stephan@cs.tu-berlin.de> - Contribution for bug 185682 - Increment/decrement operators mark local variables as read
12
 *     Stephan Herrmann <stephan@cs.tu-berlin.de> - Contributions for 
13
 *     							bug 185682 - Increment/decrement operators mark local variables as read
14
 *     							bug 186342 - [compiler][null] Using annotations for null checking
15
 *								bug 365519 - editorial cleanup after bug 186342 and bug 365387
13
 *******************************************************************************/
16
 *******************************************************************************/
14
package org.eclipse.jdt.internal.compiler.ast;
17
package org.eclipse.jdt.internal.compiler.ast;
15
18
Lines 253-258 Link Here
253
256
254
	// this is only used for method invocation as the expression inside an expression statement
257
	// this is only used for method invocation as the expression inside an expression statement
255
	public static final int InsideExpressionStatement = Bit5;
258
	public static final int InsideExpressionStatement = Bit5;
259
260
	// for annotation reference, signal if annotation was created from a default:
261
	public static final int IsSynthetic = ASTNode.Bit7;
256
262
257
	public ASTNode() {
263
	public ASTNode() {
258
264
Lines 601-607 Link Here
601
					local.tagBits |= (TagBits.AnnotationResolved | TagBits.DeprecatedAnnotationResolved);
607
					local.tagBits |= (TagBits.AnnotationResolved | TagBits.DeprecatedAnnotationResolved);
602
					if (length > 0) {
608
					if (length > 0) {
603
						annotations = new AnnotationBinding[length];
609
						annotations = new AnnotationBinding[length];
604
						local.setAnnotations(annotations);
610
						local.setAnnotations(annotations, scope);
605
					}
611
					}
606
					break;
612
					break;
607
				default :
613
				default :
(-)a/org.eclipse.jdt.core/compiler/org/eclipse/jdt/internal/compiler/ast/AbstractMethodDeclaration.java (-14 / +72 lines)
Lines 1-5 Link Here
1
/*******************************************************************************
1
/*******************************************************************************
2
 * Copyright (c) 2000, 2011 IBM Corporation and others.
2
 * Copyright (c) 2000, 2012 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-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 - Contributions for
11
 *								bug 186342 - [compiler][null] Using annotations for null checking
12
 *								bug 367203 - [compiler][null] detect assigning null to nonnull argument
13
 *								bug 365519 - editorial cleanup after bug 186342 and bug 365387
14
 *								bug 365531 - [compiler][null] investigate alternative strategy for internally encoding nullness defaults
10
 *******************************************************************************/
15
 *******************************************************************************/
11
package org.eclipse.jdt.internal.compiler.ast;
16
package org.eclipse.jdt.internal.compiler.ast;
12
17
13
import org.eclipse.jdt.core.compiler.*;
18
import org.eclipse.jdt.core.compiler.*;
14
import org.eclipse.jdt.internal.compiler.*;
19
import org.eclipse.jdt.internal.compiler.*;
15
import org.eclipse.jdt.internal.compiler.flow.FlowInfo;
20
import org.eclipse.jdt.internal.compiler.flow.FlowInfo;
16
import org.eclipse.jdt.internal.compiler.flow.InitializationFlowContext;
17
import org.eclipse.jdt.internal.compiler.impl.*;
21
import org.eclipse.jdt.internal.compiler.impl.*;
18
import org.eclipse.jdt.internal.compiler.classfmt.ClassFileConstants;
22
import org.eclipse.jdt.internal.compiler.classfmt.ClassFileConstants;
19
import org.eclipse.jdt.internal.compiler.codegen.*;
23
import org.eclipse.jdt.internal.compiler.codegen.*;
Lines 69-75 Link Here
69
		}
73
		}
70
	}
74
	}
71
75
72
	public abstract void analyseCode(ClassScope classScope, InitializationFlowContext initializationContext, FlowInfo info);
76
	/**
77
	 * When a method is accessed via SourceTypeBinding.resolveTypesFor(MethodBinding)
78
	 * we create the argument binding and resolve annotations in order to compute null annotation tagbits.
79
	 */
80
	public void createArgumentBindings() {
81
		if (this.arguments != null && this.binding != null) {
82
			for (int i = 0, length = this.arguments.length; i < length; i++) {
83
				Argument argument = this.arguments[i];
84
				argument.createBinding(this.scope, this.binding.parameters[i]);
85
				// createBinding() has resolved annotations, now transfer nullness info from the argument to the method:
86
				if ((argument.binding.tagBits & (TagBits.AnnotationNonNull|TagBits.AnnotationNullable)) != 0) {
87
					if (this.binding.parameterNonNullness == null)
88
						this.binding.parameterNonNullness = new Boolean[this.arguments.length];
89
					this.binding.parameterNonNullness[i] = Boolean.valueOf((argument.binding.tagBits & TagBits.AnnotationNonNull) != 0);
90
				}
91
			}
92
		}
93
	}
73
94
74
	/**
95
	/**
75
	 * Bind and add argument's binding into the scope of the method
96
	 * Bind and add argument's binding into the scope of the method
Lines 147-152 Link Here
147
		}
168
		}
148
	}
169
	}
149
170
171
	/**
172
	 * Feed null information from argument annotations into the analysis and mark arguments as assigned.
173
	 */
174
	void analyseArguments(FlowInfo flowInfo) {
175
		if (this.arguments != null) {
176
			for (int i = 0, count = this.arguments.length; i < count; i++) {
177
				if (this.binding.parameterNonNullness != null) {
178
					// leverage null-info from parameter annotations:
179
					Boolean nonNullNess = this.binding.parameterNonNullness[i];
180
					if (nonNullNess != null) {
181
						if (nonNullNess.booleanValue())
182
							flowInfo.markAsDefinitelyNonNull(this.arguments[i].binding);
183
						else
184
							flowInfo.markPotentiallyNullBit(this.arguments[i].binding);
185
					}
186
				}
187
				// tag parameters as being set:
188
				flowInfo.markAsDefinitelyAssigned(this.arguments[i].binding);
189
			}
190
		}
191
	}
192
150
	public CompilationResult compilationResult() {
193
	public CompilationResult compilationResult() {
151
194
152
		return this.compilationResult;
195
		return this.compilationResult;
Lines 185-201 Link Here
185
				// a fatal error was detected during code generation, need to restart code gen if possible
228
				// a fatal error was detected during code generation, need to restart code gen if possible
186
				if (e.compilationResult == CodeStream.RESTART_IN_WIDE_MODE) {
229
				if (e.compilationResult == CodeStream.RESTART_IN_WIDE_MODE) {
187
					// a branch target required a goto_w, restart code gen in wide mode.
230
					// a branch target required a goto_w, restart code gen in wide mode.
188
					if (!restart) {
231
					classFile.contentsOffset = problemResetPC;
189
						classFile.contentsOffset = problemResetPC;
232
					classFile.methodCount--;
190
						classFile.methodCount--;
233
					classFile.codeStream.resetInWideMode(); // request wide mode
191
						classFile.codeStream.resetInWideMode(); // request wide mode
234
					restart = true;
192
						restart = true;
193
					} else {
194
						// after restarting in wide mode, code generation failed again
195
						// report a problem
196
						restart = false;
197
						abort = true;
198
					}
199
				} else if (e.compilationResult == CodeStream.RESTART_CODE_GEN_FOR_UNUSED_LOCALS_MODE) {
235
				} else if (e.compilationResult == CodeStream.RESTART_CODE_GEN_FOR_UNUSED_LOCALS_MODE) {
200
					classFile.contentsOffset = problemResetPC;
236
					classFile.contentsOffset = problemResetPC;
201
					classFile.methodCount--;
237
					classFile.methodCount--;
Lines 282-287 Link Here
282
				this.scope.problemReporter().noMoreAvailableSpaceForArgument(this.scope.locals[i], this.scope.locals[i].declaration);
318
				this.scope.problemReporter().noMoreAvailableSpaceForArgument(this.scope.locals[i], this.scope.locals[i].declaration);
283
			}
319
			}
284
		}
320
		}
321
	}
322
323
	public CompilationUnitDeclaration getCompilationUnitDeclaration() {
324
		if (this.scope != null) {
325
			return this.scope.compilationUnitScope().referenceContext;
326
		}
327
		return null;
285
	}
328
	}
286
329
287
	public boolean hasErrors() {
330
	public boolean hasErrors() {
Lines 419-424 Link Here
419
			bindThrownExceptions();
462
			bindThrownExceptions();
420
			resolveJavadoc();
463
			resolveJavadoc();
421
			resolveAnnotations(this.scope, this.annotations, this.binding);
464
			resolveAnnotations(this.scope, this.annotations, this.binding);
465
			validateNullAnnotations();
422
			resolveStatements();
466
			resolveStatements();
423
			// check @Deprecated annotation presence
467
			// check @Deprecated annotation presence
424
			if (this.binding != null
468
			if (this.binding != null
Lines 482-485 Link Here
482
	public TypeParameter[] typeParameters() {
526
	public TypeParameter[] typeParameters() {
483
	    return null;
527
	    return null;
484
	}
528
	}
529
530
	void validateNullAnnotations() {
531
		// null annotations on parameters?
532
		if (this.binding != null && this.binding.parameterNonNullness != null) {
533
			int length = this.binding.parameters.length;
534
			for (int i=0; i<length; i++) {
535
				if (this.binding.parameterNonNullness[i] != null) {
536
					long nullAnnotationTagBit =  this.binding.parameterNonNullness[i].booleanValue()
537
							? TagBits.AnnotationNonNull : TagBits.AnnotationNullable;
538
					this.scope.validateNullAnnotation(nullAnnotationTagBit, this.arguments[i].type, this.arguments[i].annotations);
539
				}
540
			}
541
		}
542
	}
485
}
543
}
(-)a/org.eclipse.jdt.core/compiler/org/eclipse/jdt/internal/compiler/ast/AllocationExpression.java (-2 / +24 lines)
Lines 1-5 Link Here
1
/*******************************************************************************
1
/*******************************************************************************
2
 * Copyright (c) 2000, 2011 IBM Corporation and others.
2
 * Copyright (c) 2000, 2012 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-15 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 - 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
14
 * 							bug 186342 - [compiler][null] Using annotations for null checking
15
 *							bug 358903 - Filter practically unimportant resource leak warnings
16
 *							bug 368546 - [compiler][resource] Avoid remaining false positives found when compiling the Eclipse SDK
17
 *							bug 370639 - [compiler][resource] restore the default for resource leak warnings
13
 *******************************************************************************/
18
 *******************************************************************************/
14
package org.eclipse.jdt.internal.compiler.ast;
19
package org.eclipse.jdt.internal.compiler.ast;
15
20
Lines 35-56 Link Here
35
	protected TypeBinding typeExpected;	  // for <> inference
40
	protected TypeBinding typeExpected;	  // for <> inference
36
	public boolean inferredReturnType;
41
	public boolean inferredReturnType;
37
42
43
	public FakedTrackingVariable closeTracker;	// when allocation a Closeable store a pre-liminary tracking variable here
44
38
public FlowInfo analyseCode(BlockScope currentScope, FlowContext flowContext, FlowInfo flowInfo) {
45
public FlowInfo analyseCode(BlockScope currentScope, FlowContext flowContext, FlowInfo flowInfo) {
39
	// check captured variables are initialized in current context (26134)
46
	// check captured variables are initialized in current context (26134)
40
	checkCapturedLocalInitializationIfNecessary((ReferenceBinding)this.binding.declaringClass.erasure(), currentScope, flowInfo);
47
	checkCapturedLocalInitializationIfNecessary((ReferenceBinding)this.binding.declaringClass.erasure(), currentScope, flowInfo);
41
48
42
	// process arguments
49
	// process arguments
43
	if (this.arguments != null) {
50
	if (this.arguments != null) {
51
		boolean analyseResources = currentScope.compilerOptions().analyseResourceLeaks;
52
		boolean hasResourceWrapperType = analyseResources 
53
				&& this.resolvedType instanceof ReferenceBinding 
54
				&& ((ReferenceBinding)this.resolvedType).hasTypeBit(TypeIds.BitWrapperCloseable);
44
		for (int i = 0, count = this.arguments.length; i < count; i++) {
55
		for (int i = 0, count = this.arguments.length; i < count; i++) {
45
			flowInfo =
56
			flowInfo =
46
				this.arguments[i]
57
				this.arguments[i]
47
					.analyseCode(currentScope, flowContext, flowInfo)
58
					.analyseCode(currentScope, flowContext, flowInfo)
48
					.unconditionalInits();
59
					.unconditionalInits();
60
			// if argument is an AutoCloseable insert info that it *may* be closed (by the target method, i.e.)
61
			if (analyseResources && !hasResourceWrapperType) { // allocation of wrapped closeables is analyzed specially
62
				flowInfo = FakedTrackingVariable.markPassedToOutside(currentScope, this.arguments[i], flowInfo, false);
63
			}
49
			if ((this.arguments[i].implicitConversion & TypeIds.UNBOXING) != 0) {
64
			if ((this.arguments[i].implicitConversion & TypeIds.UNBOXING) != 0) {
50
				this.arguments[i].checkNPE(currentScope, flowContext, flowInfo);
65
				this.arguments[i].checkNPE(currentScope, flowContext, flowInfo);
51
			}
66
			}
52
		}
67
		}
68
		analyseArguments(currentScope, flowContext, flowInfo, this.binding, this.arguments);
53
	}
69
	}
70
54
	// record some dependency information for exception types
71
	// record some dependency information for exception types
55
	ReferenceBinding[] thrownExceptions;
72
	ReferenceBinding[] thrownExceptions;
56
	if (((thrownExceptions = this.binding.thrownExceptions).length) != 0) {
73
	if (((thrownExceptions = this.binding.thrownExceptions).length) != 0) {
Lines 65-70 Link Here
65
			flowInfo.unconditionalCopy(),
82
			flowInfo.unconditionalCopy(),
66
			currentScope);
83
			currentScope);
67
	}
84
	}
85
86
	// after having analysed exceptions above start tracking newly allocated resource:
87
	if (FakedTrackingVariable.isAnyCloseable(this.resolvedType) && currentScope.compilerOptions().analyseResourceLeaks)
88
		FakedTrackingVariable.analyseCloseableAllocation(currentScope, flowInfo, this);
89
68
	if (this.binding.declaringClass.isMemberType() && !this.binding.declaringClass.isStatic()) {
90
	if (this.binding.declaringClass.isMemberType() && !this.binding.declaringClass.isStatic()) {
69
		// allocating a non-static member type without an enclosing instance of parent type
91
		// allocating a non-static member type without an enclosing instance of parent type
70
		// https://bugs.eclipse.org/bugs/show_bug.cgi?id=335845
92
		// https://bugs.eclipse.org/bugs/show_bug.cgi?id=335845
(-)a/org.eclipse.jdt.core/compiler/org/eclipse/jdt/internal/compiler/ast/Annotation.java (-5 / +28 lines)
Lines 1-5 Link Here
1
/*******************************************************************************
1
/*******************************************************************************
2
 * Copyright (c) 2000, 2011 IBM Corporation and others.
2
 * Copyright (c) 2000, 2012 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 - Contributions for
11
 *								bug 186342 - [compiler][null] Using annotations for null checking
12
 *								bug 365662 - [compiler][null] warn on contradictory and redundant null annotations
10
 *******************************************************************************/
13
 *******************************************************************************/
11
package org.eclipse.jdt.internal.compiler.ast;
14
package org.eclipse.jdt.internal.compiler.ast;
12
15
Lines 24-29 Link Here
24
public abstract class Annotation extends Expression {
27
public abstract class Annotation extends Expression {
25
28
26
	final static MemberValuePair[] NoValuePairs = new MemberValuePair[0];
29
	final static MemberValuePair[] NoValuePairs = new MemberValuePair[0];
30
	private static final long TAGBITS_NULLABLE_OR_NONNULL = TagBits.AnnotationNullable|TagBits.AnnotationNonNull;
31
27
	public int declarationSourceEnd;
32
	public int declarationSourceEnd;
28
	public Binding recipient;
33
	public Binding recipient;
29
34
Lines 167-177 Link Here
167
			case TypeIds.T_JavaLangInvokeMethodHandlePolymorphicSignature :
172
			case TypeIds.T_JavaLangInvokeMethodHandlePolymorphicSignature :
168
				tagBits |= TagBits.AnnotationPolymorphicSignature;
173
				tagBits |= TagBits.AnnotationPolymorphicSignature;
169
				break;
174
				break;
170
			case TypeIds.T_JavaxAnnotationPostConstruct :
175
			case TypeIds.T_ConfiguredAnnotationNullable :
171
				tagBits |= TagBits.AnnotationPostConstruct;
176
				tagBits |= TagBits.AnnotationNullable;
172
				break;
177
				break;
173
			case TypeIds.T_JavaxAnnotationPreDestroy :
178
			case TypeIds.T_ConfiguredAnnotationNonNull :
174
				tagBits |= TagBits.AnnotationPreDestroy;
179
				tagBits |= TagBits.AnnotationNonNull;
180
				break;
181
			case TypeIds.T_ConfiguredAnnotationNonNullByDefault :
182
				if (valueAttribute != null 
183
					&& valueAttribute.value instanceof FalseLiteral) 
184
				{
185
					// parameter 'false' means: this annotation cancels any defaults
186
					tagBits |= TagBits.AnnotationNullUnspecifiedByDefault;
187
					break;
188
				}
189
				tagBits |= TagBits.AnnotationNonNullByDefault;
175
				break;
190
				break;
176
		}
191
		}
177
		return tagBits;
192
		return tagBits;
Lines 376-381 Link Here
376
							AbstractMethodDeclaration methodDeclaration = sourceType.scope.referenceContext.declarationOf(sourceMethod);
391
							AbstractMethodDeclaration methodDeclaration = sourceType.scope.referenceContext.declarationOf(sourceMethod);
377
							recordSuppressWarnings(scope, methodDeclaration.declarationSourceStart, methodDeclaration.declarationSourceEnd, scope.compilerOptions().suppressWarnings);
392
							recordSuppressWarnings(scope, methodDeclaration.declarationSourceStart, methodDeclaration.declarationSourceEnd, scope.compilerOptions().suppressWarnings);
378
						}
393
						}
394
						if ((sourceMethod.tagBits & TAGBITS_NULLABLE_OR_NONNULL) == TAGBITS_NULLABLE_OR_NONNULL) {
395
							scope.problemReporter().contradictoryNullAnnotations(this);
396
							sourceMethod.tagBits &= ~TAGBITS_NULLABLE_OR_NONNULL; // avoid secondary problems
397
						}
379
						break;
398
						break;
380
					case Binding.FIELD :
399
					case Binding.FIELD :
381
						FieldBinding sourceField = (FieldBinding) this.recipient;
400
						FieldBinding sourceField = (FieldBinding) this.recipient;
Lines 393-398 Link Here
393
							 LocalDeclaration localDeclaration = variable.declaration;
412
							 LocalDeclaration localDeclaration = variable.declaration;
394
							recordSuppressWarnings(scope, localDeclaration.declarationSourceStart, localDeclaration.declarationSourceEnd, scope.compilerOptions().suppressWarnings);
413
							recordSuppressWarnings(scope, localDeclaration.declarationSourceStart, localDeclaration.declarationSourceEnd, scope.compilerOptions().suppressWarnings);
395
						}
414
						}
415
						if ((variable.tagBits & TAGBITS_NULLABLE_OR_NONNULL) == TAGBITS_NULLABLE_OR_NONNULL) {
416
							scope.problemReporter().contradictoryNullAnnotations(this);
417
							variable.tagBits &= ~TAGBITS_NULLABLE_OR_NONNULL; // avoid secondary problems
418
						}
396
						break;
419
						break;
397
				}
420
				}
398
			}
421
			}
(-)a/org.eclipse.jdt.core/compiler/org/eclipse/jdt/internal/compiler/ast/Argument.java (-16 / +22 lines)
Lines 4-12 Link Here
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
6
 * http://www.eclipse.org/legal/epl-v10.html
6
 * http://www.eclipse.org/legal/epl-v10.html
7
 * 
7
 *
8
 * Contributors:
8
 * Contributors:
9
 *     IBM Corporation - initial API and implementation
9
 *     IBM Corporation - initial API and implementation
10
 *     Stephan Herrmann - Contributions for
11
 *								bug 186342 - [compiler][null] Using annotations for null checking
12
 *								bug 365519 - editorial cleanup after bug 186342 and bug 365387
10
 *******************************************************************************/
13
 *******************************************************************************/
11
package org.eclipse.jdt.internal.compiler.ast;
14
package org.eclipse.jdt.internal.compiler.ast;
12
15
Lines 30-36 Link Here
30
		this.bits |= (IsLocalDeclarationReachable | IsArgument);
33
		this.bits |= (IsLocalDeclarationReachable | IsArgument);
31
	}
34
	}
32
35
36
	public void createBinding(MethodScope scope, TypeBinding typeBinding) {
37
		if (this.binding == null) {
38
			// for default constructors and fake implementation of abstract methods 
39
			this.binding = new LocalVariableBinding(this, typeBinding, this.modifiers, true /*isArgument*/);
40
		} else if (!this.binding.type.isValidBinding()) {
41
			AbstractMethodDeclaration methodDecl = scope.referenceMethod();
42
			if (methodDecl != null) {
43
				MethodBinding methodBinding = methodDecl.binding;
44
				if (methodBinding != null) {
45
					methodBinding.tagBits |= TagBits.HasUnresolvedArguments;
46
				}
47
			}
48
		}
49
		resolveAnnotations(scope, this.annotations, this.binding);
50
		this.binding.declaration = this;
51
	}
52
33
	public void bind(MethodScope scope, TypeBinding typeBinding, boolean used) {
53
	public void bind(MethodScope scope, TypeBinding typeBinding, boolean used) {
54
		createBinding(scope, typeBinding); // basically a no-op if createBinding() was called before
34
55
35
		// record the resolved type into the type reference
56
		// record the resolved type into the type reference
36
		Binding existingVariable = scope.getBinding(this.name, Binding.VARIABLE, this, false /*do not resolve hidden field*/);
57
		Binding existingVariable = scope.getBinding(this.name, Binding.VARIABLE, this, false /*do not resolve hidden field*/);
Lines 52-73 Link Here
52
				scope.problemReporter().localVariableHiding(this, existingVariable, isSpecialArgument);
73
				scope.problemReporter().localVariableHiding(this, existingVariable, isSpecialArgument);
53
			}
74
			}
54
		}
75
		}
55
56
		if (this.binding == null) {
57
			this.binding = new LocalVariableBinding(this, typeBinding, this.modifiers, true);
58
		} else if (!this.binding.type.isValidBinding()) {
59
			AbstractMethodDeclaration methodDecl = scope.referenceMethod();
60
			if (methodDecl != null) {
61
				MethodBinding methodBinding = methodDecl.binding;
62
				if (methodBinding != null) {
63
					methodBinding.tagBits |= TagBits.HasUnresolvedArguments;
64
				}
65
			}
66
		}
67
		scope.addLocalVariable(this.binding);
76
		scope.addLocalVariable(this.binding);
68
		resolveAnnotations(scope, this.annotations, this.binding);
69
		//true stand for argument instead of just local
70
		this.binding.declaration = this;
71
		this.binding.useFlag = used ? LocalVariableBinding.USED : LocalVariableBinding.UNUSED;
77
		this.binding.useFlag = used ? LocalVariableBinding.USED : LocalVariableBinding.UNUSED;
72
	}
78
	}
73
79
(-)a/org.eclipse.jdt.core/compiler/org/eclipse/jdt/internal/compiler/ast/ArrayInitializer.java (-1 / +9 lines)
Lines 1-5 Link Here
1
/*******************************************************************************
1
/*******************************************************************************
2
 * Copyright (c) 2000, 2009 IBM Corporation and others.
2
 * Copyright (c) 2000, 2012 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 - Contributions for 
11
 *								bug 368546 - [compiler][resource] Avoid remaining false positives found when compiling the Eclipse SDK
12
 *								bug 370639 - [compiler][resource] restore the default for resource leak warnings
10
 *******************************************************************************/
13
 *******************************************************************************/
11
package org.eclipse.jdt.internal.compiler.ast;
14
package org.eclipse.jdt.internal.compiler.ast;
12
15
Lines 32-39 Link Here
32
	public FlowInfo analyseCode(BlockScope currentScope, FlowContext flowContext, FlowInfo flowInfo) {
35
	public FlowInfo analyseCode(BlockScope currentScope, FlowContext flowContext, FlowInfo flowInfo) {
33
36
34
		if (this.expressions != null) {
37
		if (this.expressions != null) {
38
			boolean analyseResources = currentScope.compilerOptions().analyseResourceLeaks;
35
			for (int i = 0, max = this.expressions.length; i < max; i++) {
39
			for (int i = 0, max = this.expressions.length; i < max; i++) {
36
				flowInfo = this.expressions[i].analyseCode(currentScope, flowContext, flowInfo).unconditionalInits();
40
				flowInfo = this.expressions[i].analyseCode(currentScope, flowContext, flowInfo).unconditionalInits();
41
42
				if (analyseResources && FakedTrackingVariable.isAnyCloseable(this.expressions[i].resolvedType)) {
43
					flowInfo = FakedTrackingVariable.markPassedToOutside(currentScope, this.expressions[i], flowInfo, false);
44
				}
37
			}
45
			}
38
		}
46
		}
39
		return flowInfo;
47
		return flowInfo;
(-)a/org.eclipse.jdt.core/compiler/org/eclipse/jdt/internal/compiler/ast/ArrayReference.java (-1 / +1 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
(-)a/org.eclipse.jdt.core/compiler/org/eclipse/jdt/internal/compiler/ast/Assignment.java (-4 / +27 lines)
Lines 1-17 Link Here
1
/*******************************************************************************
1
/*******************************************************************************
2
 * Copyright (c) 2000, 2011 IBM Corporation and others.
2
 * Copyright (c) 2000, 2012 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
6
 * http://www.eclipse.org/legal/epl-v10.html
6
 * http://www.eclipse.org/legal/epl-v10.html
7
 * 
7
 *
8
 * Contributors:
8
 * Contributors:
9
 *     IBM Corporation - initial API and implementation
9
 *     IBM Corporation - initial API and implementation
10
 *     Genady Beriozkin - added support for reporting assignment with no effect
10
 *     Genady Beriozkin - added support for reporting assignment with no effect
11
 *     Stephan Herrmann <stephan@cs.tu-berlin.de> - Contributions for 
11
 *     Stephan Herrmann <stephan@cs.tu-berlin.de> - Contributions for
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
16
 *							bug 186342 - [compiler][null] Using annotations for null checking
17
 *							bug 358903 - Filter practically unimportant resource leak warnings
18
 *							bug 370639 - [compiler][resource] restore the default for resource leak warnings
15
 *******************************************************************************/
19
 *******************************************************************************/
16
package org.eclipse.jdt.internal.compiler.ast;
20
package org.eclipse.jdt.internal.compiler.ast;
17
21
Lines 44-52 Link Here
44
	if ((this.expression.implicitConversion & TypeIds.UNBOXING) != 0) {
48
	if ((this.expression.implicitConversion & TypeIds.UNBOXING) != 0) {
45
		this.expression.checkNPE(currentScope, flowContext, flowInfo);
49
		this.expression.checkNPE(currentScope, flowContext, flowInfo);
46
	}
50
	}
51
	
52
	FlowInfo preInitInfo = null;
53
	boolean shouldAnalyseResource = local != null
54
			&& flowInfo.reachMode() == FlowInfo.REACHABLE
55
			&& currentScope.compilerOptions().analyseResourceLeaks
56
			&& (FakedTrackingVariable.isAnyCloseable(this.expression.resolvedType)
57
					|| this.expression.resolvedType == TypeBinding.NULL);
58
	if (shouldAnalyseResource) {
59
		preInitInfo = flowInfo.unconditionalCopy();
60
		// analysis of resource leaks needs additional context while analyzing the RHS:
61
		FakedTrackingVariable.preConnectTrackerAcrossAssignment(this, local, this.expression);
62
	}
63
	
47
	flowInfo = ((Reference) this.lhs)
64
	flowInfo = ((Reference) this.lhs)
48
		.analyseAssignment(currentScope, flowContext, flowInfo, this, false)
65
		.analyseAssignment(currentScope, flowContext, flowInfo, this, false)
49
		.unconditionalInits();
66
		.unconditionalInits();
67
68
	if (shouldAnalyseResource)
69
		FakedTrackingVariable.handleResourceAssignment(currentScope, preInitInfo, flowInfo, this, this.expression, local);
70
	else
71
		FakedTrackingVariable.cleanUpAfterAssignment(currentScope, this.lhs.bits, this.expression);
72
50
	int nullStatus = this.expression.nullStatus(flowInfo);
73
	int nullStatus = this.expression.nullStatus(flowInfo);
51
	if (local != null && (local.type.tagBits & TagBits.IsBaseType) == 0) {
74
	if (local != null && (local.type.tagBits & TagBits.IsBaseType) == 0) {
52
		if (nullStatus == FlowInfo.NULL) {
75
		if (nullStatus == FlowInfo.NULL) {
Lines 54-60 Link Here
54
				FlowContext.CAN_ONLY_NULL | FlowContext.IN_ASSIGNMENT, flowInfo);
77
				FlowContext.CAN_ONLY_NULL | FlowContext.IN_ASSIGNMENT, flowInfo);
55
		}
78
		}
56
	}
79
	}
57
	nullStatus = checkAgainstNullAnnotation(currentScope, local, nullStatus);
80
	nullStatus = checkAssignmentAgainstNullAnnotation(currentScope, flowContext, local, nullStatus, this.expression);
58
	if (local != null && (local.type.tagBits & TagBits.IsBaseType) == 0) {
81
	if (local != null && (local.type.tagBits & TagBits.IsBaseType) == 0) {
59
		flowInfo.markNullStatus(local, nullStatus);
82
		flowInfo.markNullStatus(local, nullStatus);
60
		if (flowContext.initsOnFinally != null)
83
		if (flowContext.initsOnFinally != null)
(-)a/org.eclipse.jdt.core/compiler/org/eclipse/jdt/internal/compiler/ast/Block.java (-2 / +7 lines)
Lines 1-5 Link Here
1
/*******************************************************************************
1
/*******************************************************************************
2
 * Copyright (c) 2000, 2009 IBM Corporation and others.
2
 * Copyright (c) 2000, 2012 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 - Contributions for
11
 *								bug 349326 - [1.7] new warning for missing try-with-resources
12
 *								bug 368546 - [compiler][resource] Avoid remaining false positives found when compiling the Eclipse SDK
10
 *******************************************************************************/
13
 *******************************************************************************/
11
package org.eclipse.jdt.internal.compiler.ast;
14
package org.eclipse.jdt.internal.compiler.ast;
12
15
Lines 32-41 Link Here
32
	int complaintLevel = (flowInfo.reachMode() & FlowInfo.UNREACHABLE) != 0 ? Statement.COMPLAINED_FAKE_REACHABLE : Statement.NOT_COMPLAINED;
35
	int complaintLevel = (flowInfo.reachMode() & FlowInfo.UNREACHABLE) != 0 ? Statement.COMPLAINED_FAKE_REACHABLE : Statement.NOT_COMPLAINED;
33
	for (int i = 0, max = this.statements.length; i < max; i++) {
36
	for (int i = 0, max = this.statements.length; i < max; i++) {
34
		Statement stat = this.statements[i];
37
		Statement stat = this.statements[i];
35
		if ((complaintLevel = stat.complainIfUnreachable(flowInfo, this.scope, complaintLevel)) < Statement.COMPLAINED_UNREACHABLE) {
38
		if ((complaintLevel = stat.complainIfUnreachable(flowInfo, this.scope, complaintLevel, true)) < Statement.COMPLAINED_UNREACHABLE) {
36
			flowInfo = stat.analyseCode(this.scope, flowContext, flowInfo);
39
			flowInfo = stat.analyseCode(this.scope, flowContext, flowInfo);
37
		}
40
		}
38
	}
41
	}
42
	if (this.explicitDeclarations > 0) // if block has its own scope analyze tracking vars now:
43
		this.scope.checkUnclosedCloseables(flowInfo, flowContext, null, null);
39
	return flowInfo;
44
	return flowInfo;
40
}
45
}
41
/**
46
/**
(-)a/org.eclipse.jdt.core/compiler/org/eclipse/jdt/internal/compiler/ast/BreakStatement.java (-2 / +2 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 72-78 Link Here
72
			targetContext.recordBreakFrom(flowInfo);
72
			targetContext.recordBreakFrom(flowInfo);
73
			break;
73
			break;
74
		}
74
		}
75
	} while ((traversedContext = traversedContext.parent) != null);
75
	} while ((traversedContext = traversedContext.getLocalParent()) != null);
76
76
77
	// resize subroutines
77
	// resize subroutines
78
	if (subCount != this.subroutines.length) {
78
	if (subCount != this.subroutines.length) {
(-)a/org.eclipse.jdt.core/compiler/org/eclipse/jdt/internal/compiler/ast/Clinit.java (-11 / +6 lines)
Lines 1-5 Link Here
1
/*******************************************************************************
1
/*******************************************************************************
2
 * Copyright (c) 2000, 2011 IBM Corporation and others.
2
 * Copyright (c) 2000, 2012 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 118-133 Link Here
118
				// cases.
118
				// cases.
119
				if (e.compilationResult == CodeStream.RESTART_IN_WIDE_MODE) {
119
				if (e.compilationResult == CodeStream.RESTART_IN_WIDE_MODE) {
120
					// a branch target required a goto_w, restart code gen in wide mode.
120
					// a branch target required a goto_w, restart code gen in wide mode.
121
					if (!restart) {
121
					classFile.contentsOffset = clinitOffset;
122
						classFile.contentsOffset = clinitOffset;
122
					classFile.methodCount--;
123
						classFile.methodCount--;
123
					classFile.codeStream.resetInWideMode(); // request wide mode
124
						classFile.codeStream.resetInWideMode(); // request wide mode
124
					// restart method generation
125
						// restart method generation
125
					restart = true;
126
						restart = true;
127
					} else {
128
						classFile.contentsOffset = clinitOffset;
129
						classFile.methodCount--;
130
					}
131
				} else if (e.compilationResult == CodeStream.RESTART_CODE_GEN_FOR_UNUSED_LOCALS_MODE) {
126
				} else if (e.compilationResult == CodeStream.RESTART_CODE_GEN_FOR_UNUSED_LOCALS_MODE) {
132
					classFile.contentsOffset = clinitOffset;
127
					classFile.contentsOffset = clinitOffset;
133
					classFile.methodCount--;
128
					classFile.methodCount--;
(-)a/org.eclipse.jdt.core/compiler/org/eclipse/jdt/internal/compiler/ast/CompilationUnitDeclaration.java (-1 / +23 lines)
Lines 1-5 Link Here
1
/*******************************************************************************
1
/*******************************************************************************
2
 * Copyright (c) 2000, 2011 IBM Corporation and others.
2
 * Copyright (c) 2000, 2012 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 364-369 Link Here
364
	}
364
	}
365
}
365
}
366
366
367
public CompilationUnitDeclaration getCompilationUnitDeclaration() {
368
	return this;
369
}
370
367
public char[] getFileName() {
371
public char[] getFileName() {
368
	return this.compilationResult.getFileName();
372
	return this.compilationResult.getFileName();
369
}
373
}
Lines 394-399 Link Here
394
	return CharOperation.equals(getMainTypeName(), TypeConstants.PACKAGE_INFO_NAME);
398
	return CharOperation.equals(getMainTypeName(), TypeConstants.PACKAGE_INFO_NAME);
395
}
399
}
396
400
401
public boolean isSuppressed(CategorizedProblem problem) {
402
	if (this.suppressWarningsCount == 0) return false;
403
	int irritant = ProblemReporter.getIrritant(problem.getID());
404
	if (irritant == 0) return false;
405
	int start = problem.getSourceStart();
406
	int end = problem.getSourceEnd();
407
	nextSuppress: for (int iSuppress = 0, suppressCount = this.suppressWarningsCount; iSuppress < suppressCount; iSuppress++) {
408
		long position = this.suppressWarningScopePositions[iSuppress];
409
		int startSuppress = (int) (position >>> 32);
410
		int endSuppress = (int) position;
411
		if (start < startSuppress) continue nextSuppress;
412
		if (end > endSuppress) continue nextSuppress;
413
		if (this.suppressWarningIrritants[iSuppress].isSet(irritant))
414
			return true;
415
	}
416
	return false;
417
}
418
397
public boolean hasErrors() {
419
public boolean hasErrors() {
398
	return this.ignoreFurtherInvestigation;
420
	return this.ignoreFurtherInvestigation;
399
}
421
}
(-)a/org.eclipse.jdt.core/compiler/org/eclipse/jdt/internal/compiler/ast/ConditionalExpression.java (-2 / +3 lines)
Lines 12-17 Link Here
12
 *     						bug 292478 - Report potentially null across variable assignment
12
 *     						bug 292478 - Report potentially null across variable assignment
13
 * 							bug 324178 - [null] ConditionalExpression.nullStatus(..) doesn't take into account the analysis of condition itself
13
 * 							bug 324178 - [null] ConditionalExpression.nullStatus(..) doesn't take into account the analysis of condition itself
14
 * 							bug 354554 - [null] conditional with redundant condition yields weak error message
14
 * 							bug 354554 - [null] conditional with redundant condition yields weak error message
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 65-71 Link Here
65
				trueFlowInfo.setReachMode(FlowInfo.UNREACHABLE_OR_DEAD);
66
				trueFlowInfo.setReachMode(FlowInfo.UNREACHABLE_OR_DEAD);
66
			}
67
			}
67
			if (!isKnowDeadCodePattern(this.condition) || currentScope.compilerOptions().reportDeadCodeInTrivialIfStatement) {
68
			if (!isKnowDeadCodePattern(this.condition) || currentScope.compilerOptions().reportDeadCodeInTrivialIfStatement) {
68
				this.valueIfTrue.complainIfUnreachable(trueFlowInfo, currentScope, initialComplaintLevel);
69
				this.valueIfTrue.complainIfUnreachable(trueFlowInfo, currentScope, initialComplaintLevel, false);
69
			}
70
			}
70
		}
71
		}
71
		this.trueInitStateIndex = currentScope.methodScope().recordInitializationStates(trueFlowInfo);
72
		this.trueInitStateIndex = currentScope.methodScope().recordInitializationStates(trueFlowInfo);
Lines 78-84 Link Here
78
				falseFlowInfo.setReachMode(FlowInfo.UNREACHABLE_OR_DEAD);
79
				falseFlowInfo.setReachMode(FlowInfo.UNREACHABLE_OR_DEAD);
79
			}
80
			}
80
			if (!isKnowDeadCodePattern(this.condition) || currentScope.compilerOptions().reportDeadCodeInTrivialIfStatement) {
81
			if (!isKnowDeadCodePattern(this.condition) || currentScope.compilerOptions().reportDeadCodeInTrivialIfStatement) {
81
				this.valueIfFalse.complainIfUnreachable(falseFlowInfo, currentScope, initialComplaintLevel);
82
				this.valueIfFalse.complainIfUnreachable(falseFlowInfo, currentScope, initialComplaintLevel, true);
82
			}
83
			}
83
		}
84
		}
84
		this.falseInitStateIndex = currentScope.methodScope().recordInitializationStates(falseFlowInfo);
85
		this.falseInitStateIndex = currentScope.methodScope().recordInitializationStates(falseFlowInfo);
(-)a/org.eclipse.jdt.core/compiler/org/eclipse/jdt/internal/compiler/ast/ConstructorDeclaration.java (-28 / +17 lines)
Lines 1-5 Link Here
1
/*******************************************************************************
1
/*******************************************************************************
2
 * Copyright (c) 2000, 2011 IBM Corporation and others.
2
 * Copyright (c) 2000, 2012 IBM Corporation and others.
3
 * All rights reserved. This program and the accompanying materials
3
 * All rights reserved. This program and the accompanying materials
4
 * are made available under the terms of the Eclipse Public License v1.0
4
 * are made available under the terms of the Eclipse Public License v1.0
5
 * which accompanies this distribution, and is available at
5
 * which accompanies this distribution, and is available at
Lines 7-13 Link Here
7
 *
7
 *
8
 * Contributors:
8
 * Contributors:
9
 *     IBM Corporation - initial API and implementation
9
 *     IBM Corporation - initial API and implementation
10
 *     Stephan Herrmann - Contribution for Bug 343713 - [compiler] bogus line number in constructor of inner class in 1.5 compliance
10
 *     Stephan Herrmann - Contributions for
11
 *     							bug 343713 - [compiler] bogus line number in constructor of inner class in 1.5 compliance
12
 *     							bug 349326 - [1.7] new warning for missing try-with-resources
13
 *								bug 186342 - [compiler][null] Using annotations for null checking
14
 *								bug 361407 - Resource leak warning when resource is assigned to a field outside of constructor
15
 *								bug 368546 - [compiler][resource] Avoid remaining false positives found when compiling the Eclipse SDK
11
 *******************************************************************************/
16
 *******************************************************************************/
12
package org.eclipse.jdt.internal.compiler.ast;
17
package org.eclipse.jdt.internal.compiler.ast;
13
18
Lines 32-49 Link Here
32
public ConstructorDeclaration(CompilationResult compilationResult){
37
public ConstructorDeclaration(CompilationResult compilationResult){
33
	super(compilationResult);
38
	super(compilationResult);
34
}
39
}
35
36
/**
37
 * @see org.eclipse.jdt.internal.compiler.ast.AbstractMethodDeclaration#analyseCode(org.eclipse.jdt.internal.compiler.lookup.ClassScope, org.eclipse.jdt.internal.compiler.flow.InitializationFlowContext, org.eclipse.jdt.internal.compiler.flow.FlowInfo)
38
 * @deprecated use instead {@link #analyseCode(ClassScope, InitializationFlowContext, FlowInfo, int)}
39
 */
40
public void analyseCode(ClassScope classScope, InitializationFlowContext initializerFlowContext, FlowInfo flowInfo) {
41
	analyseCode(classScope, initializerFlowContext, flowInfo, FlowInfo.REACHABLE);
42
}
43
44
/**
40
/**
45
 * The flowInfo corresponds to non-static field initialization infos. It may be unreachable (155423), but still the explicit constructor call must be
41
 * The flowInfo corresponds to non-static field initialization infos. It may be unreachable (155423), but still the explicit constructor call must be
46
 * analysed as reachable, since it will be generated in the end.
42
 * analyzed as reachable, since it will be generated in the end.
47
 */
43
 */
48
public void analyseCode(ClassScope classScope, InitializationFlowContext initializerFlowContext, FlowInfo flowInfo, int initialReachMode) {
44
public void analyseCode(ClassScope classScope, InitializationFlowContext initializerFlowContext, FlowInfo flowInfo, int initialReachMode) {
49
	if (this.ignoreFurtherInvestigation)
45
	if (this.ignoreFurtherInvestigation)
Lines 120-131 Link Here
120
			}
116
			}
121
		}
117
		}
122
118
123
		// tag parameters as being set
119
		// nullity and mark as assigned
124
		if (this.arguments != null) {
120
		analyseArguments(flowInfo);
125
			for (int i = 0, count = this.arguments.length; i < count; i++) {
126
				flowInfo.markAsDefinitelyAssigned(this.arguments[i].binding);
127
			}
128
		}
129
121
130
		// propagate to constructor call
122
		// propagate to constructor call
131
		if (this.constructorCall != null) {
123
		if (this.constructorCall != null) {
Lines 151-157 Link Here
151
			int complaintLevel = (nonStaticFieldInfoReachMode & FlowInfo.UNREACHABLE) == 0 ? Statement.NOT_COMPLAINED : Statement.COMPLAINED_FAKE_REACHABLE;
143
			int complaintLevel = (nonStaticFieldInfoReachMode & FlowInfo.UNREACHABLE) == 0 ? Statement.NOT_COMPLAINED : Statement.COMPLAINED_FAKE_REACHABLE;
152
			for (int i = 0, count = this.statements.length; i < count; i++) {
144
			for (int i = 0, count = this.statements.length; i < count; i++) {
153
				Statement stat = this.statements[i];
145
				Statement stat = this.statements[i];
154
				if ((complaintLevel = stat.complainIfUnreachable(flowInfo, this.scope, complaintLevel)) < Statement.COMPLAINED_UNREACHABLE) {
146
				if ((complaintLevel = stat.complainIfUnreachable(flowInfo, this.scope, complaintLevel, true)) < Statement.COMPLAINED_UNREACHABLE) {
155
					flowInfo = stat.analyseCode(this.scope, constructorContext, flowInfo);
147
					flowInfo = stat.analyseCode(this.scope, constructorContext, flowInfo);
156
				}
148
				}
157
			}
149
			}
Lines 186-191 Link Here
186
		constructorContext.complainIfUnusedExceptionHandlers(this);
178
		constructorContext.complainIfUnusedExceptionHandlers(this);
187
		// check unused parameters
179
		// check unused parameters
188
		this.scope.checkUnusedParameters(this.binding);
180
		this.scope.checkUnusedParameters(this.binding);
181
		this.scope.checkUnclosedCloseables(flowInfo, null, null/*don't report against a specific location*/, null);
189
	} catch (AbortMethod e) {
182
	} catch (AbortMethod e) {
190
		this.ignoreFurtherInvestigation = true;
183
		this.ignoreFurtherInvestigation = true;
191
	}
184
	}
Lines 220-234 Link Here
220
		} catch (AbortMethod e) {
213
		} catch (AbortMethod e) {
221
			if (e.compilationResult == CodeStream.RESTART_IN_WIDE_MODE) {
214
			if (e.compilationResult == CodeStream.RESTART_IN_WIDE_MODE) {
222
				// a branch target required a goto_w, restart code gen in wide mode.
215
				// a branch target required a goto_w, restart code gen in wide mode.
223
				if (!restart) {
216
				classFile.contentsOffset = problemResetPC;
224
					classFile.contentsOffset = problemResetPC;
217
				classFile.methodCount--;
225
					classFile.methodCount--;
218
				classFile.codeStream.resetInWideMode(); // request wide mode
226
					classFile.codeStream.resetInWideMode(); // request wide mode
219
				restart = true;
227
					restart = true;
228
				} else {
229
					restart = false;
230
					abort = true;
231
				}
232
			} else if (e.compilationResult == CodeStream.RESTART_CODE_GEN_FOR_UNUSED_LOCALS_MODE) {
220
			} else if (e.compilationResult == CodeStream.RESTART_CODE_GEN_FOR_UNUSED_LOCALS_MODE) {
233
				classFile.contentsOffset = problemResetPC;
221
				classFile.contentsOffset = problemResetPC;
234
				classFile.methodCount--;
222
				classFile.methodCount--;
Lines 416-421 Link Here
416
404
417
	ConstructorDeclaration targetConstructor =
405
	ConstructorDeclaration targetConstructor =
418
		((ConstructorDeclaration)this.scope.referenceType().declarationOf(this.constructorCall.binding.original()));
406
		((ConstructorDeclaration)this.scope.referenceType().declarationOf(this.constructorCall.binding.original()));
407
	if (targetConstructor == null) return false; // https://bugs.eclipse.org/bugs/show_bug.cgi?id=358762
419
	if (this == targetConstructor) return true; // direct case
408
	if (this == targetConstructor) return true; // direct case
420
409
421
	if (visited == null) { // lazy allocation
410
	if (visited == null) { // lazy allocation
(-)a/org.eclipse.jdt.core/compiler/org/eclipse/jdt/internal/compiler/ast/ContinueStatement.java (-2 / +2 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 75-81 Link Here
75
			targetContext.recordContinueFrom(flowContext, flowInfo);
75
			targetContext.recordContinueFrom(flowContext, flowInfo);
76
			break;
76
			break;
77
		}
77
		}
78
	} while ((traversedContext = traversedContext.parent) != null);
78
	} while ((traversedContext = traversedContext.getLocalParent()) != null);
79
79
80
	// resize subroutines
80
	// resize subroutines
81
	if (subCount != this.subroutines.length) {
81
	if (subCount != this.subroutines.length) {
(-)a/org.eclipse.jdt.core/compiler/org/eclipse/jdt/internal/compiler/ast/DoStatement.java (-2 / +6 lines)
Lines 1-5 Link Here
1
/*******************************************************************************
1
/*******************************************************************************
2
 * Copyright (c) 2000, 2011 IBM Corporation and others.
2
 * Copyright (c) 2000, 2012 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 101-107 Link Here
101
			(this.action == null
101
			(this.action == null
102
				? actionInfo
102
				? actionInfo
103
				: (actionInfo.mergedWith(loopingContext.initsOnContinue))).copy());
103
				: (actionInfo.mergedWith(loopingContext.initsOnContinue))).copy());
104
	this.preConditionInitStateIndex = currentScope.methodScope().recordInitializationStates(actionInfo);
104
	/* https://bugs.eclipse.org/bugs/show_bug.cgi?id=367023, we reach the condition at the bottom via two arcs, 
105
	   one by free fall and another by continuing... Merge initializations propagated through the two pathways,
106
	   cf, while and for loops.
107
	*/
108
	this.preConditionInitStateIndex = currentScope.methodScope().recordInitializationStates(actionInfo.mergedWith(loopingContext.initsOnContinue));
105
	if (!isConditionOptimizedFalse && this.continueLabel != null) {
109
	if (!isConditionOptimizedFalse && this.continueLabel != null) {
106
		loopingContext.complainOnDeferredFinalChecks(currentScope, condInfo);
110
		loopingContext.complainOnDeferredFinalChecks(currentScope, condInfo);
107
		condLoopContext.complainOnDeferredFinalChecks(currentScope, condInfo);
111
		condLoopContext.complainOnDeferredFinalChecks(currentScope, condInfo);
(-)a/org.eclipse.jdt.core/compiler/org/eclipse/jdt/internal/compiler/ast/EmptyStatement.java (-3 / +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 29-40 Link Here
29
	}
30
	}
30
31
31
	// Report an error if necessary
32
	// Report an error if necessary
32
	public int complainIfUnreachable(FlowInfo flowInfo, BlockScope scope, int complaintLevel) {
33
	public int complainIfUnreachable(FlowInfo flowInfo, BlockScope scope, int complaintLevel, boolean endOfBlock) {
33
		// before 1.4, empty statements are tolerated anywhere
34
		// before 1.4, empty statements are tolerated anywhere
34
		if (scope.compilerOptions().complianceLevel < ClassFileConstants.JDK1_4) {
35
		if (scope.compilerOptions().complianceLevel < ClassFileConstants.JDK1_4) {
35
			return complaintLevel;
36
			return complaintLevel;
36
		}
37
		}
37
		return super.complainIfUnreachable(flowInfo, scope, complaintLevel);
38
		return super.complainIfUnreachable(flowInfo, scope, complaintLevel, endOfBlock);
38
	}
39
	}
39
40
40
	public void generateCode(BlockScope currentScope, CodeStream codeStream){
41
	public void generateCode(BlockScope currentScope, CodeStream codeStream){
(-)a/org.eclipse.jdt.core/compiler/org/eclipse/jdt/internal/compiler/ast/EqualExpression.java (-3 / +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-12 Link Here
7
 *
7
 *
8
 * Contributors:
8
 * Contributors:
9
 *     IBM Corporation - initial API and implementation
9
 *     IBM Corporation - initial API and implementation
10
 *     Stephan Herrmann - Contribution for bug 186342 - [compiler][null] Using annotations for null checking
10
 *******************************************************************************/
11
 *******************************************************************************/
11
package org.eclipse.jdt.internal.compiler.ast;
12
package org.eclipse.jdt.internal.compiler.ast;
12
13
Lines 23-36 Link Here
23
		super(left,right,operator);
24
		super(left,right,operator);
24
	}
25
	}
25
	private void checkNullComparison(BlockScope scope, FlowContext flowContext, FlowInfo flowInfo, FlowInfo initsWhenTrue, FlowInfo initsWhenFalse) {
26
	private void checkNullComparison(BlockScope scope, FlowContext flowContext, FlowInfo flowInfo, FlowInfo initsWhenTrue, FlowInfo initsWhenFalse) {
27
		int rightStatus = this.right.nullStatus(flowInfo);
28
		int leftStatus = this.left.nullStatus(flowInfo);
29
		// check if either is a method annotated @NonNull and compared to null:
30
		if (leftStatus == FlowInfo.NON_NULL && rightStatus == FlowInfo.NULL) {
31
			if (this.left instanceof MessageSend) { 
32
				scope.problemReporter().messageSendRedundantCheckOnNonNull(((MessageSend) this.left).binding, this.left);
33
			}
34
			// TODO: handle all kinds of expressions (cf. also https://bugs.eclipse.org/364326)
35
		} else if (leftStatus == FlowInfo.NULL && rightStatus == FlowInfo.NON_NULL) {
36
			if (this.right instanceof MessageSend) {
37
				scope.problemReporter().messageSendRedundantCheckOnNonNull(((MessageSend) this.right).binding, this.right);
38
			}
39
			// TODO: handle all kinds of expressions (cf. also https://bugs.eclipse.org/364326)
40
		}
26
41
27
		LocalVariableBinding local = this.left.localVariableBinding();
42
		LocalVariableBinding local = this.left.localVariableBinding();
28
		if (local != null && (local.type.tagBits & TagBits.IsBaseType) == 0) {
43
		if (local != null && (local.type.tagBits & TagBits.IsBaseType) == 0) {
29
			checkVariableComparison(scope, flowContext, flowInfo, initsWhenTrue, initsWhenFalse, local, this.right.nullStatus(flowInfo), this.left);
44
			checkVariableComparison(scope, flowContext, flowInfo, initsWhenTrue, initsWhenFalse, local, rightStatus, this.left);
30
		}
45
		}
31
		local = this.right.localVariableBinding();
46
		local = this.right.localVariableBinding();
32
		if (local != null && (local.type.tagBits & TagBits.IsBaseType) == 0) {
47
		if (local != null && (local.type.tagBits & TagBits.IsBaseType) == 0) {
33
			checkVariableComparison(scope, flowContext, flowInfo, initsWhenTrue, initsWhenFalse, local, this.left.nullStatus(flowInfo), this.right);
48
			checkVariableComparison(scope, flowContext, flowInfo, initsWhenTrue, initsWhenFalse, local, leftStatus, this.right);
34
		}
49
		}
35
	}
50
	}
36
	private void checkVariableComparison(BlockScope scope, FlowContext flowContext, FlowInfo flowInfo, FlowInfo initsWhenTrue, FlowInfo initsWhenFalse, LocalVariableBinding local, int nullStatus, Expression reference) {
51
	private void checkVariableComparison(BlockScope scope, FlowContext flowContext, FlowInfo flowInfo, FlowInfo initsWhenTrue, FlowInfo initsWhenFalse, LocalVariableBinding local, int nullStatus, Expression reference) {
(-)a/org.eclipse.jdt.core/compiler/org/eclipse/jdt/internal/compiler/ast/ExplicitConstructorCall.java (-2 / +12 lines)
Lines 1-5 Link Here
1
/*******************************************************************************
1
/*******************************************************************************
2
 * Copyright (c) 2000, 2011 IBM Corporation and others.
2
 * Copyright (c) 2000, 2012 IBM Corporation and others.
3
 * All rights reserved. This program and the accompanying materials
3
 * All rights reserved. This program and the accompanying materials
4
 * are made available under the terms of the Eclipse Public License v1.0
4
 * are made available under the terms of the Eclipse Public License v1.0
5
 * which accompanies this distribution, and is available at
5
 * which accompanies this distribution, and is available at
Lines 7-13 Link Here
7
 *
7
 *
8
 * Contributors:
8
 * Contributors:
9
 *     IBM Corporation - initial API and implementation
9
 *     IBM Corporation - initial API and implementation
10
 *     Stephan Herrmann - Contribution for bug 319201 - [null] no warning when unboxing SingleNameReference causes NPE
10
 *     Stephan Herrmann - Contributions for
11
 *								bug 319201 - [null] no warning when unboxing SingleNameReference causes NPE
12
 *								bug 186342 - [compiler][null] Using annotations for null checking
13
 *								bug 361407 - Resource leak warning when resource is assigned to a field outside of constructor
14
 *								bug 370639 - [compiler][resource] restore the default for resource leak warnings
11
 *******************************************************************************/
15
 *******************************************************************************/
12
package org.eclipse.jdt.internal.compiler.ast;
16
package org.eclipse.jdt.internal.compiler.ast;
13
17
Lines 72-86 Link Here
72
			}
76
			}
73
			// process arguments
77
			// process arguments
74
			if (this.arguments != null) {
78
			if (this.arguments != null) {
79
				boolean analyseResources = currentScope.compilerOptions().analyseResourceLeaks;
75
				for (int i = 0, max = this.arguments.length; i < max; i++) {
80
				for (int i = 0, max = this.arguments.length; i < max; i++) {
76
					flowInfo =
81
					flowInfo =
77
						this.arguments[i]
82
						this.arguments[i]
78
							.analyseCode(currentScope, flowContext, flowInfo)
83
							.analyseCode(currentScope, flowContext, flowInfo)
79
							.unconditionalInits();
84
							.unconditionalInits();
85
					if (analyseResources) {
86
						// if argument is an AutoCloseable insert info that it *may* be closed (by the target constructor, i.e.)
87
						flowInfo = FakedTrackingVariable.markPassedToOutside(currentScope, this.arguments[i], flowInfo, false);
88
					}
80
					if ((this.arguments[i].implicitConversion & TypeIds.UNBOXING) != 0) {
89
					if ((this.arguments[i].implicitConversion & TypeIds.UNBOXING) != 0) {
81
						this.arguments[i].checkNPE(currentScope, flowContext, flowInfo);
90
						this.arguments[i].checkNPE(currentScope, flowContext, flowInfo);
82
					}
91
					}
83
				}
92
				}
93
				analyseArguments(currentScope, flowContext, flowInfo, this.binding, this.arguments);
84
			}
94
			}
85
95
86
			ReferenceBinding[] thrownExceptions;
96
			ReferenceBinding[] thrownExceptions;
(-)a/org.eclipse.jdt.core/compiler/org/eclipse/jdt/internal/compiler/ast/FakedTrackingVariable.java (+791 lines)
Added Link Here
1
/*******************************************************************************
2
 * Copyright (c) 2011, 2012 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 java.util.HashMap;
14
import java.util.Iterator;
15
import java.util.Map;
16
import java.util.Map.Entry;
17
import java.util.Set;
18
19
import org.eclipse.jdt.internal.compiler.codegen.CodeStream;
20
import org.eclipse.jdt.internal.compiler.flow.FlowContext;
21
import org.eclipse.jdt.internal.compiler.flow.FlowInfo;
22
import org.eclipse.jdt.internal.compiler.impl.Constant;
23
import org.eclipse.jdt.internal.compiler.lookup.Binding;
24
import org.eclipse.jdt.internal.compiler.lookup.BlockScope;
25
import org.eclipse.jdt.internal.compiler.lookup.LocalVariableBinding;
26
import org.eclipse.jdt.internal.compiler.lookup.MethodScope;
27
import org.eclipse.jdt.internal.compiler.lookup.ReferenceBinding;
28
import org.eclipse.jdt.internal.compiler.lookup.Scope;
29
import org.eclipse.jdt.internal.compiler.lookup.TypeBinding;
30
import org.eclipse.jdt.internal.compiler.lookup.TypeConstants;
31
import org.eclipse.jdt.internal.compiler.lookup.TypeIds;
32
import org.eclipse.jdt.internal.compiler.problem.ProblemReporter;
33
34
/**
35
 * A faked local variable declaration used for keeping track of data flows of a
36
 * special variable. Certain events will be recorded by changing the null info
37
 * for this variable.
38
 * 
39
 * See bug 349326 - [1.7] new warning for missing try-with-resources
40
 */
41
public class FakedTrackingVariable extends LocalDeclaration {
42
43
	// a call to close() was seen at least on one path:
44
	private static final int CLOSE_SEEN = 1;
45
	// the resource is shared with outside code either by
46
	// - passing as an arg in a method call or
47
	// - obtaining this from a method call or array reference
48
	// Interpret that we may or may not be responsible for closing
49
	private static final int SHARED_WITH_OUTSIDE = 2;
50
	// the resource is likely owned by outside code (owner has responsibility to close): 
51
	// - obtained as argument of the current method, or via a field read
52
	// - stored into a field
53
	// - returned as the result of this method 
54
	private static final int OWNED_BY_OUTSIDE = 4;
55
	// If close() is invoked from a nested method (inside a local type) report remaining problems only as potential:
56
	private static final int CLOSED_IN_NESTED_METHOD = 8;
57
	// explicit closing has been reported already against this resource:
58
	private static final int REPORTED_EXPLICIT_CLOSE = 16;
59
	// a location independent potential problem has been reported against this resource:
60
	private static final int REPORTED_POTENTIAL_LEAK = 32;
61
	// a location independent definitive problem has been reported against this resource:
62
	private static final int REPORTED_DEFINITIVE_LEAK = 64;
63
64
	/**
65
	 * Bitset of {@link #CLOSE_SEEN}, {@link #SHARED_WITH_OUTSIDE}, {@link #OWNED_BY_OUTSIDE}, {@link #CLOSED_IN_NESTED_METHOD}, {@link #REPORTED_EXPLICIT_CLOSE}, {@link #REPORTED_POTENTIAL_LEAK} and {@link #REPORTED_DEFINITIVE_LEAK}.
66
	 */
67
	private int globalClosingState = 0;
68
69
	public LocalVariableBinding originalBinding; // the real local being tracked, can be null for preliminary track vars for allocation expressions
70
	
71
	public FakedTrackingVariable innerTracker; // chained tracking variable of a chained (wrapped) resource
72
	public FakedTrackingVariable outerTracker; // inverse of 'innerTracker'
73
74
	MethodScope methodScope; // designates the method declaring this variable
75
76
	private HashMap recordedLocations; // initially null, ASTNode -> Integer
77
78
	// temporary storage while analyzing "res = new Res();":
79
	private ASTNode currentAssignment; // temporarily store the assignment as the location for error reporting
80
81
	public FakedTrackingVariable(LocalVariableBinding original, ASTNode location) {
82
		super(original.name, location.sourceStart, location.sourceEnd);
83
		this.type = new SingleTypeReference(
84
				TypeConstants.OBJECT,
85
				((long)this.sourceStart <<32)+this.sourceEnd);
86
		this.methodScope = original.declaringScope.methodScope();
87
		this.originalBinding = original;
88
		resolve(original.declaringScope);
89
	}
90
91
	/* Create an unassigned tracking variable while analyzing an allocation expression: */
92
	private FakedTrackingVariable(BlockScope scope, ASTNode location) {
93
		super("<unassigned Closeable value>".toCharArray(), location.sourceStart, location.sourceEnd); //$NON-NLS-1$
94
		this.type = new SingleTypeReference(
95
				TypeConstants.OBJECT,
96
				((long)this.sourceStart <<32)+this.sourceEnd);
97
		this.methodScope = scope.methodScope();
98
		this.originalBinding = null;
99
		resolve(scope);
100
	}
101
	
102
	public void generateCode(BlockScope currentScope, CodeStream codeStream)
103
	{ /* NOP - this variable is completely dummy, ie. for analysis only. */ }
104
105
	public void resolve (BlockScope scope) {
106
		// only need the binding, which is used as reference in FlowInfo methods.
107
		this.binding = new LocalVariableBinding(
108
				this.name,
109
				scope.getJavaLangObject(),  // dummy, just needs to be a reference type
110
				0,
111
				false);
112
		this.binding.closeTracker = this;
113
		this.binding.declaringScope = scope;
114
		this.binding.setConstant(Constant.NotAConstant);
115
		this.binding.useFlag = LocalVariableBinding.USED;
116
		// use a free slot without assigning it:
117
		this.binding.id = scope.registerTrackingVariable(this);
118
	}
119
120
	/**
121
	 * If expression resolves to a value of type AutoCloseable answer the variable that tracks closing of that local.
122
	 * Covers two cases:
123
	 * <ul>
124
	 * <li>value is a local variable reference, create tracking variable it if needed.
125
	 * <li>value is an allocation expression, return a preliminary tracking variable if set.
126
	 * </ul>
127
	 * @param expression
128
	 * @return a new {@link FakedTrackingVariable} or null.
129
	 */
130
	public static FakedTrackingVariable getCloseTrackingVariable(Expression expression) {
131
		while (true) {
132
			if (expression instanceof CastExpression)
133
				expression = ((CastExpression) expression).expression;
134
			else if (expression instanceof Assignment)
135
				expression = ((Assignment) expression).expression;
136
			else
137
				break;
138
		}
139
		if (expression instanceof SingleNameReference) {
140
			SingleNameReference name = (SingleNameReference) expression;
141
			if (name.binding instanceof LocalVariableBinding) {
142
				LocalVariableBinding local = (LocalVariableBinding)name.binding;
143
				if (local.closeTracker != null)
144
					return local.closeTracker;
145
				if (!isAnyCloseable(expression.resolvedType))
146
					return null;
147
				// tracking var doesn't yet exist. This happens in finally block
148
				// which is analyzed before the corresponding try block
149
				Statement location = local.declaration;
150
				local.closeTracker = new FakedTrackingVariable(local, location);
151
				if (local.isParameter()) {
152
					local.closeTracker.globalClosingState |= OWNED_BY_OUTSIDE;
153
					// status of this tracker is now UNKNOWN
154
				}
155
				return local.closeTracker;
156
			}
157
		} else if (expression instanceof AllocationExpression) {
158
			// return any preliminary tracking variable from analyseCloseableAllocation 
159
			return ((AllocationExpression) expression).closeTracker;
160
		}		
161
		return null;
162
	}
163
164
	/**
165
	 * Before analyzing an assignment of this shape: <code>singleName = new Allocation()</code>
166
	 * connect any tracking variable of the LHS with the allocation on the RHS.
167
	 * Also the assignment is temporarily stored in the tracking variable in case we need to
168
	 * report errors because the assignment leaves the old LHS value unclosed.
169
	 * In this case the assignment should be used as the error location.
170
	 * 
171
	 * @param location the assignment/local declaration being analyzed
172
	 * @param local the local variable being assigned to
173
	 * @param rhs the rhs of the assignment resp. the initialization of the local variable declaration.
174
	 * 		<strong>Precondition:</strong> client has already checked that the resolved type of this expression is either a closeable type or NULL.
175
	 */
176
	public static void preConnectTrackerAcrossAssignment(ASTNode location, LocalVariableBinding local, Expression rhs) {
177
		FakedTrackingVariable closeTracker = null;
178
		if (rhs instanceof AllocationExpression) {
179
			closeTracker = local.closeTracker;
180
			if (closeTracker == null) {
181
				if (rhs.resolvedType != TypeBinding.NULL) { // not NULL means valid closeable as per method precondition
182
					closeTracker = new FakedTrackingVariable(local, location);
183
					if (local.isParameter()) {
184
						closeTracker.globalClosingState |= OWNED_BY_OUTSIDE;
185
					}
186
				}					
187
			}
188
			if (closeTracker != null) {
189
				closeTracker.currentAssignment = location;
190
				AllocationExpression allocation = (AllocationExpression)rhs;
191
				allocation.closeTracker = closeTracker;
192
				if (allocation.arguments != null && allocation.arguments.length > 0) {
193
					// also push into nested allocations, see https://bugs.eclipse.org/368709
194
					preConnectTrackerAcrossAssignment(location, local, allocation.arguments[0]);
195
				}
196
			}
197
		}
198
	}
199
200
	/** 
201
	 * Compute/assign a tracking variable for a freshly allocated closeable value, using information from our white lists.
202
	 * See  Bug 358903 - Filter practically unimportant resource leak warnings 
203
	 */
204
	public static void analyseCloseableAllocation(BlockScope scope, FlowInfo flowInfo, AllocationExpression allocation) {
205
		// client has checked that the resolvedType is an AutoCloseable, hence the following cast is safe:
206
		if (((ReferenceBinding)allocation.resolvedType).hasTypeBit(TypeIds.BitResourceFreeCloseable)) {
207
			// remove unnecessary attempts (closeable is not relevant)
208
			if (allocation.closeTracker != null) {
209
				scope.removeTrackingVar(allocation.closeTracker);
210
				allocation.closeTracker = null;
211
			}
212
		} else if (((ReferenceBinding)allocation.resolvedType).hasTypeBit(TypeIds.BitWrapperCloseable)) {
213
			boolean isWrapper = true;
214
			if (allocation.arguments != null &&  allocation.arguments.length > 0) {
215
				// find the wrapped resource represented by its tracking var:
216
				FakedTrackingVariable innerTracker = findCloseTracker(scope, flowInfo, allocation.arguments[0]);
217
				if (innerTracker != null) {
218
					FakedTrackingVariable currentInner = innerTracker;
219
					do {
220
						if (currentInner == allocation.closeTracker)
221
							return; // self wrap (res = new Res(res)) -> neither change (here) nor remove (below)
222
						// also check for indirect cycles, see https://bugs.eclipse.org/368709
223
						currentInner = currentInner.innerTracker;
224
					} while (currentInner != null);
225
					int newStatus = FlowInfo.NULL;
226
					if (allocation.closeTracker == null) {
227
						allocation.closeTracker = new FakedTrackingVariable(scope, allocation); // no local available, closeable is unassigned
228
					} else {
229
						if (scope.finallyInfo != null) {
230
							// inject results from analysing a finally block onto the newly connected wrapper
231
							int finallyStatus = scope.finallyInfo.nullStatus(allocation.closeTracker.binding);
232
							if (finallyStatus != FlowInfo.UNKNOWN)
233
								newStatus = finallyStatus;
234
						}
235
					}
236
					allocation.closeTracker.innerTracker = innerTracker;
237
					innerTracker.outerTracker = allocation.closeTracker;
238
					flowInfo.markNullStatus(allocation.closeTracker.binding, newStatus);
239
					if (newStatus != FlowInfo.NULL) {
240
						// propagate results from a finally block also into nested resources:
241
						FakedTrackingVariable currentTracker = innerTracker;
242
						while (currentTracker != null) {
243
							flowInfo.markNullStatus(currentTracker.binding, newStatus);
244
							currentTracker.globalClosingState |= allocation.closeTracker.globalClosingState;
245
							currentTracker = currentTracker.innerTracker;
246
						}
247
					}
248
					return; // keep chaining wrapper (by avoiding to fall through to removeTrackingVar below)
249
				} else {
250
					if (!isAnyCloseable(allocation.arguments[0].resolvedType)) {
251
						isWrapper = false; // argument is not closeable
252
					}
253
				}
254
			} else {
255
				isWrapper = false; // no argument
256
			}
257
			// successful wrapper detection has exited above, let's see why that failed
258
			if (isWrapper) {
259
				// remove unnecessary attempts (wrapper has no relevant inner)
260
				if (allocation.closeTracker != null) {
261
					scope.removeTrackingVar(allocation.closeTracker);
262
					allocation.closeTracker = null;
263
				}
264
			} else {
265
				// allocation does not provide a resource as the first argument -> don't treat as a wrapper
266
				handleRegularResource(scope, flowInfo, allocation);
267
			}
268
		} else { // regular resource
269
			handleRegularResource(scope, flowInfo, allocation);
270
		}
271
	}
272
273
	private static void handleRegularResource(BlockScope scope, FlowInfo flowInfo, AllocationExpression allocation) {
274
		FakedTrackingVariable presetTracker = allocation.closeTracker;
275
		if (presetTracker != null && presetTracker.originalBinding != null) {
276
			// the current assignment forgets a previous resource in the LHS, may cause a leak
277
			// report now because handleResourceAssignment can't distinguish this from a self-wrap situation
278
			int closeStatus = flowInfo.nullStatus(presetTracker.binding);
279
			if (closeStatus != FlowInfo.NON_NULL		// old resource was not closed
280
					&& closeStatus != FlowInfo.UNKNOWN	// old resource had some flow information
281
					&& !flowInfo.isDefinitelyNull(presetTracker.originalBinding)		// old resource was not null
282
					&& !(presetTracker.currentAssignment instanceof LocalDeclaration))	// forgetting old val in local decl is syntactically impossible
283
				allocation.closeTracker.recordErrorLocation(presetTracker.currentAssignment, closeStatus);
284
		} else {
285
			allocation.closeTracker = new FakedTrackingVariable(scope, allocation); // no local available, closeable is unassigned
286
		}
287
		flowInfo.markAsDefinitelyNull(allocation.closeTracker.binding);
288
	}
289
290
	/** Find an existing tracking variable for the argument of an allocation for a resource wrapper. */
291
	private static FakedTrackingVariable findCloseTracker(BlockScope scope, FlowInfo flowInfo, Expression arg)
292
	{
293
		while (arg instanceof Assignment) {
294
			Assignment assign = (Assignment)arg;
295
			LocalVariableBinding innerLocal = assign.localVariableBinding();
296
			if (innerLocal != null) {
297
				// nested assignment has already been processed
298
				return innerLocal.closeTracker;
299
			} else {
300
				arg = assign.expression; // unwrap assignment and fall through
301
			}
302
		}
303
		if (arg instanceof SingleNameReference) {
304
			// is allocation arg a reference to an existing closeable?
305
			LocalVariableBinding local = arg.localVariableBinding();
306
			if (local != null) {
307
				return local.closeTracker;
308
			}
309
		} else if (arg instanceof AllocationExpression) {
310
			// nested allocation
311
			return ((AllocationExpression)arg).closeTracker;
312
		}
313
		return null; // not a tracked expression
314
	}
315
316
	/** 
317
	 * Check if the rhs of an assignment or local declaration is an (Auto)Closeable.
318
	 * If so create or re-use a tracking variable, and wire and initialize everything.
319
	 * @param scope scope containing the assignment
320
	 * @param upstreamInfo info without analysis of the rhs, use this to determine the status of a resource being disconnected
321
	 * @param flowInfo info with analysis of the rhs, use this for recording resource status because this will be passed downstream
322
	 * @param location where to report warnigs/errors against
323
	 * @param rhs the right hand side of the assignment, this expression is to be analyzed.
324
	 *			The caller has already checked that the rhs is either of a closeable type or null.
325
	 * @param local the local variable into which the rhs is being assigned
326
	 */
327
	public static void handleResourceAssignment(BlockScope scope, FlowInfo upstreamInfo, FlowInfo flowInfo, ASTNode location, Expression rhs, LocalVariableBinding local)
328
	{
329
		// does the LHS (local) already have a tracker, indicating we may leak a resource by the assignment?
330
		FakedTrackingVariable previousTracker = null;
331
		FakedTrackingVariable disconnectedTracker = null;
332
		if (local.closeTracker != null) {
333
			// assigning to a variable already holding an AutoCloseable, has it been closed before?
334
			previousTracker = local.closeTracker;
335
			int nullStatus = upstreamInfo.nullStatus(local);
336
			if (nullStatus != FlowInfo.NULL && nullStatus != FlowInfo.UNKNOWN) // only if previous value may be relevant
337
				disconnectedTracker = previousTracker; // report error below, unless we have a self-wrap assignment
338
		}
339
340
		rhsAnalyis:
341
		if (rhs.resolvedType != TypeBinding.NULL) {
342
			// new value is AutoCloseable, start tracking, possibly re-using existing tracker var:
343
			FakedTrackingVariable rhsTrackVar = getCloseTrackingVariable(rhs);
344
			if (rhsTrackVar != null) {								// 1. if RHS has a tracking variable...
345
				if (local.closeTracker == null) {
346
					// null shouldn't occur but let's play safe:
347
					if (rhsTrackVar.originalBinding != null)
348
						local.closeTracker = rhsTrackVar;			//		a.: let fresh LHS share it
349
					if (rhsTrackVar.currentAssignment == location) {
350
						// pre-set tracker from lhs - passed from outside?
351
						// now it's a fresh resource
352
						rhsTrackVar.globalClosingState &= ~(SHARED_WITH_OUTSIDE|OWNED_BY_OUTSIDE);
353
					}
354
				} else {
355
					if (rhs instanceof AllocationExpression) {
356
						if (rhsTrackVar == disconnectedTracker)
357
							return;									// 		b.: self wrapper: res = new Wrap(res); -> done!
358
						if (local.closeTracker == rhsTrackVar 
359
								&& ((rhsTrackVar.globalClosingState & OWNED_BY_OUTSIDE) != 0)) {
360
																	// 		c.: assigning a fresh resource (pre-connected alloc) 
361
																	//			to a local previously holding an alien resource -> start over
362
							local.closeTracker = new FakedTrackingVariable(local, location);
363
							flowInfo.markAsDefinitelyNull(local.closeTracker.binding);
364
							// still check disconnectedTracker below
365
							break rhsAnalyis;
366
						}
367
					}
368
					local.closeTracker = rhsTrackVar;				//		d.: conflicting LHS and RHS, proceed with recordErrorLocation below
369
				}
370
				// keep close-status of RHS unchanged across this assignment
371
			} else if (previousTracker != null) {					// 2. re-use tracking variable from the LHS?
372
				// re-assigning from a fresh value, mark as not-closed again:
373
				if ((previousTracker.globalClosingState & (SHARED_WITH_OUTSIDE|OWNED_BY_OUTSIDE)) == 0)
374
					flowInfo.markAsDefinitelyNull(previousTracker.binding);
375
				local.closeTracker = analyseCloseableExpression(flowInfo, local, location, rhs, previousTracker);
376
			} else {												// 3. no re-use, create a fresh tracking variable:
377
				rhsTrackVar = analyseCloseableExpression(flowInfo, local, location, rhs, null);
378
				if (rhsTrackVar != null) {
379
					local.closeTracker = rhsTrackVar;
380
					// a fresh resource, mark as not-closed:
381
					if ((rhsTrackVar.globalClosingState & (SHARED_WITH_OUTSIDE|OWNED_BY_OUTSIDE)) == 0)
382
						flowInfo.markAsDefinitelyNull(rhsTrackVar.binding);
383
// TODO(stephan): this might be useful, but I could not find a test case for it: 
384
//					if (flowContext.initsOnFinally != null)
385
//						flowContext.initsOnFinally.markAsDefinitelyNonNull(trackerBinding);
386
				}
387
			}
388
		}
389
390
		if (disconnectedTracker != null) {
391
			if (disconnectedTracker.innerTracker != null && disconnectedTracker.innerTracker.binding.declaringScope == scope) {
392
				// discard tracker for the wrapper but keep the inner:
393
				disconnectedTracker.innerTracker.outerTracker = null;
394
				scope.pruneWrapperTrackingVar(disconnectedTracker);
395
			} else {
396
				int upstreamStatus = upstreamInfo.nullStatus(disconnectedTracker.binding);
397
				if (upstreamStatus != FlowInfo.NON_NULL)
398
					disconnectedTracker.recordErrorLocation(location, upstreamStatus);
399
			}
400
		}
401
	}
402
	/**
403
	 * Analyze structure of a closeable expression, matching (chained) resources against our white lists.
404
	 * @param flowInfo where to record close status
405
	 * @param local local variable to which the closeable is being assigned
406
	 * @param location where to flag errors/warnings against
407
	 * @param expression expression to be analyzed
408
	 * @param previousTracker when analyzing a re-assignment we may already have a tracking variable for local,
409
	 *  		which we should then re-use
410
	 * @return a tracking variable associated with local or null if no need to track
411
	 */
412
	private static FakedTrackingVariable analyseCloseableExpression(FlowInfo flowInfo, LocalVariableBinding local, 
413
									ASTNode location, Expression expression, FakedTrackingVariable previousTracker) 
414
	{
415
		// unwrap uninteresting nodes:
416
		while (true) {
417
			if (expression instanceof Assignment)
418
				expression = ((Assignment)expression).expression;
419
			else if (expression instanceof CastExpression)
420
				expression = ((CastExpression) expression).expression;
421
			else
422
				break;
423
		}
424
425
		// analyze by node type:
426
		if (expression instanceof AllocationExpression) {
427
			// allocation expressions already have their tracking variables analyzed by analyseCloseableAllocation(..)
428
			FakedTrackingVariable tracker = ((AllocationExpression) expression).closeTracker;
429
			if (tracker != null && tracker.originalBinding == null) {
430
				// tracker without original binding (unassigned closeable) shouldn't reach here but let's play safe
431
				return null;
432
			}
433
			return tracker;
434
		} else if (expression instanceof MessageSend 
435
				|| expression instanceof ArrayReference) 
436
		{
437
			// we *might* be responsible for the resource obtained
438
			FakedTrackingVariable tracker = new FakedTrackingVariable(local, location);
439
			tracker.globalClosingState |= SHARED_WITH_OUTSIDE;
440
			flowInfo.markPotentiallyNullBit(tracker.binding); // shed some doubt
441
			return tracker;
442
		} else if (
443
				(expression.bits & RestrictiveFlagMASK) == Binding.FIELD
444
				||((expression instanceof QualifiedNameReference)
445
						&& ((QualifiedNameReference) expression).isFieldAccess()))
446
		{
447
			// responsibility for this resource probably lies at a higher level
448
			FakedTrackingVariable tracker = new FakedTrackingVariable(local, location);
449
			tracker.globalClosingState |= OWNED_BY_OUTSIDE;
450
			// leave state as UNKNOWN, the bit OWNED_BY_OUTSIDE will prevent spurious warnings
451
			return tracker;			
452
		}
453
454
		if (expression.resolvedType instanceof ReferenceBinding) {
455
			ReferenceBinding resourceType = (ReferenceBinding) expression.resolvedType;
456
			if (resourceType.hasTypeBit(TypeIds.BitResourceFreeCloseable)) {
457
				// (a) resource-free closeable: -> null
458
				return null;
459
			}
460
		}
461
		if (local.closeTracker != null)
462
			// (c): inner has already been analyzed: -> re-use track var
463
			return local.closeTracker;
464
		FakedTrackingVariable newTracker = new FakedTrackingVariable(local, location);
465
		LocalVariableBinding rhsLocal = expression.localVariableBinding();
466
		if (rhsLocal != null && rhsLocal.isParameter()) {
467
			newTracker.globalClosingState |= OWNED_BY_OUTSIDE;
468
		}
469
		return newTracker;
470
	}
471
472
	public static void cleanUpAfterAssignment(BlockScope currentScope, int lhsBits, Expression expression) {
473
		// remove all remaining track vars with no original binding
474
475
		// unwrap uninteresting nodes:
476
		while (true) {
477
			if (expression instanceof Assignment)
478
				expression = ((Assignment)expression).expression;
479
			else if (expression instanceof CastExpression)
480
				expression = ((CastExpression) expression).expression;
481
			else
482
				break;
483
		}
484
		if (expression instanceof AllocationExpression) {
485
			FakedTrackingVariable tracker = ((AllocationExpression) expression).closeTracker;
486
			if (tracker != null && tracker.originalBinding == null) {
487
				currentScope.removeTrackingVar(tracker);
488
				((AllocationExpression) expression).closeTracker = null;
489
			}
490
		} else {
491
			// assignment passing a local into a field?
492
			LocalVariableBinding local = expression.localVariableBinding();
493
			if (local != null && local.closeTracker != null && ((lhsBits & Binding.FIELD) != 0))
494
				currentScope.removeTrackingVar(local.closeTracker); // TODO: may want to use local.closeTracker.markPassedToOutside(..,true)
495
		}
496
	}
497
498
	/** Answer wither the given type binding is a subtype of java.lang.AutoCloseable. */
499
	public static boolean isAnyCloseable(TypeBinding typeBinding) {
500
		return typeBinding instanceof ReferenceBinding
501
			&& ((ReferenceBinding)typeBinding).hasTypeBit(TypeIds.BitAutoCloseable|TypeIds.BitCloseable);
502
	}
503
504
	public int findMostSpecificStatus(FlowInfo flowInfo, BlockScope currentScope, BlockScope locationScope) {
505
		int status = FlowInfo.UNKNOWN;
506
		FakedTrackingVariable currentTracker = this;
507
		// loop as to consider wrappers (per white list) encapsulating an inner resource.
508
		while (currentTracker != null) {
509
			LocalVariableBinding currentVar = currentTracker.binding;
510
			int currentStatus = getNullStatusAggressively(currentVar, flowInfo);
511
			if (locationScope != null) // only check at method exit points
512
				currentStatus = mergeCloseStatus(locationScope, currentStatus, currentVar, currentScope);
513
			if (currentStatus == FlowInfo.NON_NULL) {
514
				status = currentStatus;
515
				break; // closed -> stop searching
516
			} else if (status == FlowInfo.NULL || status == FlowInfo.UNKNOWN) {
517
				status = currentStatus; // improved although not yet safe -> keep searching for better
518
			}
519
			currentTracker = currentTracker.innerTracker;
520
		}
521
		return status;
522
	}
523
524
	/**
525
	 * Get the null status looking even into unreachable flows
526
	 * @param local
527
	 * @param flowInfo
528
	 * @return one of the constants FlowInfo.{NULL,POTENTIALLY_NULL,POTENTIALLY_NON_NULL,NON_NULL}.
529
	 */
530
	private int getNullStatusAggressively(LocalVariableBinding local, FlowInfo flowInfo) {
531
		int reachMode = flowInfo.reachMode();
532
		int status = 0;
533
		try {
534
			// unreachable flowInfo is too shy in reporting null-issues, temporarily forget reachability:
535
			if (reachMode != FlowInfo.REACHABLE)
536
				flowInfo.tagBits &= ~FlowInfo.UNREACHABLE;
537
			status = flowInfo.nullStatus(local);
538
		} finally {
539
			// reset
540
			flowInfo.tagBits |= reachMode;
541
		}
542
		// at this point some combinations are not useful so flatten to a single bit:
543
		if ((status & FlowInfo.NULL) != 0) {
544
			if ((status & (FlowInfo.NON_NULL | FlowInfo.POTENTIALLY_NON_NULL)) != 0)
545
				return FlowInfo.POTENTIALLY_NULL; 	// null + doubt = pot null
546
			return FlowInfo.NULL;
547
		} else if ((status & FlowInfo.NON_NULL) != 0) {
548
			if ((status & FlowInfo.POTENTIALLY_NULL) != 0)
549
				return FlowInfo.POTENTIALLY_NULL;	// non-null + doubt = pot null
550
			return FlowInfo.NON_NULL;
551
		} else if ((status & FlowInfo.POTENTIALLY_NULL) != 0)
552
			return FlowInfo.POTENTIALLY_NULL;
553
		return status;
554
	}
555
556
	public int mergeCloseStatus(BlockScope currentScope, int status, LocalVariableBinding local, BlockScope outerScope) {
557
		// get the most suitable null status representing whether resource 'binding' has been closed
558
		// start at 'currentScope' and potentially travel out until 'outerScope'
559
		// at each scope consult any recorded 'finallyInfo'.
560
		if (status != FlowInfo.NON_NULL) {
561
			if (currentScope.finallyInfo != null) {
562
				int finallyStatus = currentScope.finallyInfo.nullStatus(local);
563
				if (finallyStatus == FlowInfo.NON_NULL)
564
					return finallyStatus;
565
				if (finallyStatus != FlowInfo.NULL) // neither is NON_NULL, but not both are NULL => call it POTENTIALLY_NULL
566
					status = FlowInfo.POTENTIALLY_NULL;
567
			}
568
			if (currentScope != outerScope && currentScope.parent instanceof BlockScope)
569
				return mergeCloseStatus(((BlockScope) currentScope.parent), status, local, outerScope);
570
		}
571
		return status;
572
	}
573
574
	/** Mark that this resource is closed locally. */
575
	public void markClose(FlowInfo flowInfo, FlowContext flowContext) {
576
		FakedTrackingVariable current = this;
577
		do {
578
			flowInfo.markAsDefinitelyNonNull(current.binding);
579
			current.globalClosingState |= CLOSE_SEEN;
580
//TODO(stephan): this might be useful, but I could not find a test case for it: 
581
			if (flowContext.initsOnFinally != null)
582
				flowContext.initsOnFinally.markAsDefinitelyNonNull(this.binding);
583
			current = current.innerTracker;
584
		} while (current != null);
585
	}
586
587
	/** Mark that this resource is closed from a nested method (inside a local class). */
588
	public void markClosedInNestedMethod() {
589
		this.globalClosingState |= CLOSED_IN_NESTED_METHOD;
590
	}
591
592
	/** 
593
	 * Mark that this resource is passed to some outside code
594
	 * (as argument to a method/ctor call or as a return value from the current method), 
595
	 * and thus should be considered as potentially closed.
596
	 * @param owned should the resource be considered owned by some outside?
597
	 */
598
	public static FlowInfo markPassedToOutside(BlockScope scope, Expression expression, FlowInfo flowInfo, boolean owned) {	
599
		
600
		FakedTrackingVariable trackVar = getCloseTrackingVariable(expression);
601
		if (trackVar != null) {
602
			// insert info that the tracked resource *may* be closed (by the target method, i.e.)
603
			FlowInfo infoResourceIsClosed = owned ? flowInfo : flowInfo.copy();
604
			int flag = owned ? OWNED_BY_OUTSIDE : SHARED_WITH_OUTSIDE;
605
			do {
606
				trackVar.globalClosingState |= flag;
607
				if (scope.methodScope() != trackVar.methodScope)
608
					trackVar.globalClosingState |= CLOSED_IN_NESTED_METHOD;
609
				infoResourceIsClosed.markAsDefinitelyNonNull(trackVar.binding);
610
			} while ((trackVar = trackVar.innerTracker) != null);
611
			if (owned) {
612
				return infoResourceIsClosed; // don't let downstream signal any problems on this flow
613
			} else {
614
				return FlowInfo.conditional(flowInfo, infoResourceIsClosed); // only report potential problems on this flow
615
			}
616
		}
617
		return flowInfo;
618
	}
619
620
	/** 
621
	 * Pick tracking variables from 'varsOfScope' to establish a proper order of processing:
622
	 * As much as possible pick wrapper resources before their inner resources.
623
	 * Also consider cases of wrappers and their inners being declared at different scopes.
624
	 */
625
	public static FakedTrackingVariable pickVarForReporting(Set varsOfScope, BlockScope scope, boolean atExit) {
626
		if (varsOfScope.isEmpty()) return null;
627
		FakedTrackingVariable trackingVar = (FakedTrackingVariable) varsOfScope.iterator().next();
628
		while (trackingVar.outerTracker != null) {
629
			// resource is wrapped, is wrapper defined in this scope?
630
			if (varsOfScope.contains(trackingVar.outerTracker)) {
631
				// resource from same scope, travel up the wrapper chain
632
				trackingVar = trackingVar.outerTracker;
633
			} else if (atExit) {
634
				// at an exit point we report against inner despite a wrapper that may/may not be closed later
635
				break;
636
			} else {
637
				BlockScope outerTrackerScope = trackingVar.outerTracker.binding.declaringScope;
638
				if (outerTrackerScope == scope) {
639
					// outerTracker is from same scope and already processed -> pick trackingVar now
640
					break;
641
				} else {
642
					// outer resource is from other (outer?) scope
643
					Scope currentScope = scope;
644
					while ((currentScope = currentScope.parent) instanceof BlockScope) {
645
						if (outerTrackerScope == currentScope) {
646
							// at end of block pass responsibility for inner resource to outer scope holding a wrapper
647
							varsOfScope.remove(trackingVar); // drop this one
648
							// pick a next candidate:
649
							return pickVarForReporting(varsOfScope, scope, atExit);
650
						}
651
					}
652
					break; // not parent owned -> pick this var
653
				}
654
			}
655
		}
656
		varsOfScope.remove(trackingVar);
657
		return trackingVar;
658
	}
659
660
	/**
661
	 * Answer true if we know for sure that no resource is bound to this variable
662
	 * at the point of 'flowInfo'. 
663
	 */
664
	public boolean hasDefinitelyNoResource(FlowInfo flowInfo) {
665
		if (this.originalBinding == null) return false; // shouldn't happen but keep quiet.
666
		if (flowInfo.isDefinitelyNull(this.originalBinding)) {
667
			return true;
668
		}
669
		if (!(flowInfo.isDefinitelyAssigned(this.originalBinding) 
670
				|| flowInfo.isPotentiallyAssigned(this.originalBinding))) {
671
			return true;
672
		}
673
		return false;
674
	}
675
676
	public boolean isClosedInFinallyOfEnclosing(BlockScope scope) {
677
		BlockScope currentScope = scope;
678
		while (true) {			
679
			if (currentScope.finallyInfo != null
680
					&& currentScope.finallyInfo.isDefinitelyNonNull(this.binding)) {
681
				return true; // closed in enclosing finally
682
			}
683
			if (!(currentScope.parent instanceof BlockScope)) {
684
				return false;
685
			}
686
			currentScope = (BlockScope) currentScope.parent;
687
		} 
688
	}
689
	/** 
690
	 * If current is the same as 'returnedResource' or a wrapper thereof,
691
	 * mark as reported and return true, otherwise false.
692
	 */
693
	public boolean isResourceBeingReturned(FakedTrackingVariable returnedResource) {
694
		FakedTrackingVariable current = this;
695
		do {
696
			if (current == returnedResource) {
697
				this.globalClosingState |= REPORTED_DEFINITIVE_LEAK;
698
				return true;
699
			}
700
			current = current.innerTracker;
701
		} while (current != null);
702
		return false;
703
	}
704
705
	public void recordErrorLocation(ASTNode location, int nullStatus) {
706
		if ((this.globalClosingState & OWNED_BY_OUTSIDE) != 0) {
707
			return;
708
		}
709
		if (this.recordedLocations == null)
710
			this.recordedLocations = new HashMap();
711
		this.recordedLocations.put(location, new Integer(nullStatus));
712
	}
713
714
	public boolean reportRecordedErrors(Scope scope, int mergedStatus) {
715
		FakedTrackingVariable current = this;
716
		while (current.globalClosingState == 0) {
717
			current = current.innerTracker;
718
			if (current == null) {
719
				// no relevant state found -> report:
720
				reportError(scope.problemReporter(), null, mergedStatus);
721
				return true;
722
			}
723
		}
724
		boolean hasReported = false;
725
		if (this.recordedLocations != null) {
726
			Iterator locations = this.recordedLocations.entrySet().iterator();
727
			int reportFlags = 0;
728
			while (locations.hasNext()) {
729
				Map.Entry entry = (Entry) locations.next();
730
				reportFlags |= reportError(scope.problemReporter(), (ASTNode)entry.getKey(), ((Integer)entry.getValue()).intValue());
731
				hasReported = true;
732
			}
733
			if (reportFlags != 0) {
734
				// after all locations have been reported, mark as reported to prevent duplicate report via an outer wrapper
735
				current = this;
736
				do {
737
					current.globalClosingState |= reportFlags;
738
				} while ((current = current.innerTracker) != null);
739
			}
740
		}
741
		return hasReported;
742
	}
743
	
744
	public int reportError(ProblemReporter problemReporter, ASTNode location, int nullStatus) {
745
		if ((this.globalClosingState & OWNED_BY_OUTSIDE) != 0) {
746
			return 0; // TODO: should we still propagate some flags??
747
		}
748
		// which degree of problem?
749
		boolean isPotentialProblem = false;
750
		if (nullStatus == FlowInfo.NULL) {
751
			if ((this.globalClosingState & CLOSED_IN_NESTED_METHOD) != 0)
752
				isPotentialProblem = true;
753
		} else if ((nullStatus & (FlowInfo.POTENTIALLY_NULL|FlowInfo.POTENTIALLY_NON_NULL)) != 0) {
754
			isPotentialProblem = true;
755
		}
756
		// report:
757
		if (isPotentialProblem) {
758
			if ((this.globalClosingState & (REPORTED_POTENTIAL_LEAK|REPORTED_DEFINITIVE_LEAK)) != 0)
759
				return 0;
760
			problemReporter.potentiallyUnclosedCloseable(this, location);	
761
		} else {
762
			if ((this.globalClosingState & (REPORTED_DEFINITIVE_LEAK)) != 0)
763
				return 0;
764
			problemReporter.unclosedCloseable(this, location);			
765
		}
766
		// propagate flag to inners:
767
		int reportFlag = isPotentialProblem ? REPORTED_POTENTIAL_LEAK : REPORTED_DEFINITIVE_LEAK;
768
		if (location == null) { // if location != null flags will be set after the loop over locations 
769
			FakedTrackingVariable current = this;
770
			do {
771
				current.globalClosingState |= reportFlag;
772
			} while ((current = current.innerTracker) != null);
773
		}
774
		return reportFlag;
775
	}
776
777
	public void reportExplicitClosing(ProblemReporter problemReporter) {
778
		if ((this.globalClosingState & (OWNED_BY_OUTSIDE|REPORTED_EXPLICIT_CLOSE)) == 0) { // can't use t-w-r for OWNED_BY_OUTSIDE
779
			this.globalClosingState |= REPORTED_EXPLICIT_CLOSE;
780
			problemReporter.explicitlyClosedAutoCloseable(this);
781
		}
782
	}
783
784
	public void resetReportingBits() {
785
		FakedTrackingVariable current = this;
786
		do {
787
			current.globalClosingState &= ~(REPORTED_POTENTIAL_LEAK|REPORTED_DEFINITIVE_LEAK);
788
			current = current.innerTracker;
789
		} while (current != null);
790
	}
791
}
(-)a/org.eclipse.jdt.core/compiler/org/eclipse/jdt/internal/compiler/ast/FieldDeclaration.java (+6 lines)
Lines 123-128 Link Here
123
	return (this.modifiers & ClassFileConstants.AccStatic) != 0;
123
	return (this.modifiers & ClassFileConstants.AccStatic) != 0;
124
}
124
}
125
125
126
public boolean isFinal() {
127
	if (this.binding != null)
128
		return this.binding.isFinal();
129
	return (this.modifiers & ClassFileConstants.AccFinal) != 0;
130
}
131
126
public StringBuffer printStatement(int indent, StringBuffer output) {
132
public StringBuffer printStatement(int indent, StringBuffer output) {
127
	if (this.javadoc != null) {
133
	if (this.javadoc != null) {
128
		this.javadoc.print(indent, output);
134
		this.javadoc.print(indent, output);
(-)a/org.eclipse.jdt.core/compiler/org/eclipse/jdt/internal/compiler/ast/ForStatement.java (-2 / +15 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 138-144 Link Here
138
						actionInfo.setReachMode(FlowInfo.UNREACHABLE_OR_DEAD);
140
						actionInfo.setReachMode(FlowInfo.UNREACHABLE_OR_DEAD);
139
					}
141
					}
140
				}
142
				}
141
			if (this.action.complainIfUnreachable(actionInfo, this.scope, initialComplaintLevel) < Statement.COMPLAINED_UNREACHABLE) {
143
			if (this.action.complainIfUnreachable(actionInfo, this.scope, initialComplaintLevel, true) < Statement.COMPLAINED_UNREACHABLE) {
142
				actionInfo = this.action.analyseCode(this.scope, loopingContext, actionInfo).unconditionalInits();
144
				actionInfo = this.action.analyseCode(this.scope, loopingContext, actionInfo).unconditionalInits();
143
			}
145
			}
144
146
Lines 215-220 Link Here
215
				exitBranch,
217
				exitBranch,
216
				isConditionOptimizedFalse,
218
				isConditionOptimizedFalse,
217
				!isConditionTrue /*for(;;){}while(true); unreachable(); */);
219
				!isConditionTrue /*for(;;){}while(true); unreachable(); */);
220
		// Variables initialized only for the purpose of the for loop can be removed for further flow info
221
		// https://bugs.eclipse.org/bugs/show_bug.cgi?id=359495
222
		if (this.initializations != null) {
223
			for (int i = 0; i < this.initializations.length; i++) {
224
				Statement init = this.initializations[i];
225
				if (init instanceof LocalDeclaration) {
226
					LocalVariableBinding binding = ((LocalDeclaration) init).binding;
227
					mergedInfo.resetAssignmentInfo(binding);
228
				}
229
			}
230
		}
218
		this.mergedInitStateIndex = currentScope.methodScope().recordInitializationStates(mergedInfo);
231
		this.mergedInitStateIndex = currentScope.methodScope().recordInitializationStates(mergedInfo);
219
		return mergedInfo;
232
		return mergedInfo;
220
	}
233
	}
(-)a/org.eclipse.jdt.core/compiler/org/eclipse/jdt/internal/compiler/ast/ForeachStatement.java (-6 / +21 lines)
Lines 1-5 Link Here
1
/*******************************************************************************
1
/*******************************************************************************
2
 * Copyright (c) 2000, 2011 IBM Corporation and others.
2
 * Copyright (c) 2000, 2012 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
11
 *								bug 349326 - [1.7] new warning for missing try-with-resources
12
 *								bug 370930 - NonNull annotation not considered for enhanced for loops
10
 *******************************************************************************/
13
 *******************************************************************************/
11
package org.eclipse.jdt.internal.compiler.ast;
14
package org.eclipse.jdt.internal.compiler.ast;
12
15
Lines 25-30 Link Here
25
import org.eclipse.jdt.internal.compiler.lookup.LocalVariableBinding;
28
import org.eclipse.jdt.internal.compiler.lookup.LocalVariableBinding;
26
import org.eclipse.jdt.internal.compiler.lookup.ParameterizedTypeBinding;
29
import org.eclipse.jdt.internal.compiler.lookup.ParameterizedTypeBinding;
27
import org.eclipse.jdt.internal.compiler.lookup.ReferenceBinding;
30
import org.eclipse.jdt.internal.compiler.lookup.ReferenceBinding;
31
import org.eclipse.jdt.internal.compiler.lookup.TagBits;
28
import org.eclipse.jdt.internal.compiler.lookup.TypeBinding;
32
import org.eclipse.jdt.internal.compiler.lookup.TypeBinding;
29
33
30
public class ForeachStatement extends Statement {
34
public class ForeachStatement extends Statement {
Lines 82-90 Link Here
82
		this.collection.checkNPE(currentScope, flowContext, flowInfo);
86
		this.collection.checkNPE(currentScope, flowContext, flowInfo);
83
		flowInfo = this.elementVariable.analyseCode(this.scope, flowContext, flowInfo);		
87
		flowInfo = this.elementVariable.analyseCode(this.scope, flowContext, flowInfo);		
84
		FlowInfo condInfo = this.collection.analyseCode(this.scope, flowContext, flowInfo.copy());
88
		FlowInfo condInfo = this.collection.analyseCode(this.scope, flowContext, flowInfo.copy());
89
		LocalVariableBinding elementVarBinding = this.elementVariable.binding;
85
90
86
		// element variable will be assigned when iterating
91
		// element variable will be assigned when iterating
87
		condInfo.markAsDefinitelyAssigned(this.elementVariable.binding);
92
		condInfo.markAsDefinitelyAssigned(elementVarBinding);
88
93
89
		this.postCollectionInitStateIndex = currentScope.methodScope().recordInitializationStates(condInfo);
94
		this.postCollectionInitStateIndex = currentScope.methodScope().recordInitializationStates(condInfo);
90
95
Lines 94-111 Link Here
94
				this.continueLabel, this.scope);
99
				this.continueLabel, this.scope);
95
		UnconditionalFlowInfo actionInfo =
100
		UnconditionalFlowInfo actionInfo =
96
			condInfo.nullInfoLessUnconditionalCopy();
101
			condInfo.nullInfoLessUnconditionalCopy();
97
		actionInfo.markAsDefinitelyUnknown(this.elementVariable.binding);
102
		actionInfo.markAsDefinitelyUnknown(elementVarBinding);
103
		if (currentScope.compilerOptions().isAnnotationBasedNullAnalysisEnabled) {
104
			// this currently produces an unavoidable warning against all @NonNull element vars:
105
			int nullStatus = this.elementVariable.checkAssignmentAgainstNullAnnotation(currentScope, flowContext, 
106
															elementVarBinding, FlowInfo.UNKNOWN, this.collection);
107
			// TODO (stephan): 	once we have JSR 308 fetch nullStatus from the collection element type
108
			//              	and feed the result into the above check (instead of FlowInfo.UNKNOWN)
109
			if ((elementVarBinding.type.tagBits & TagBits.IsBaseType) == 0) {
110
				actionInfo.markNullStatus(elementVarBinding, nullStatus);
111
			}
112
		}
98
		FlowInfo exitBranch;
113
		FlowInfo exitBranch;
99
		if (!(this.action == null || (this.action.isEmptyBlock()
114
		if (!(this.action == null || (this.action.isEmptyBlock()
100
				&& currentScope.compilerOptions().complianceLevel <= ClassFileConstants.JDK1_3))) {
115
				&& currentScope.compilerOptions().complianceLevel <= ClassFileConstants.JDK1_3))) {
101
116
102
			if (this.action.complainIfUnreachable(actionInfo, this.scope, initialComplaintLevel) < Statement.COMPLAINED_UNREACHABLE) {
117
			if (this.action.complainIfUnreachable(actionInfo, this.scope, initialComplaintLevel, true) < Statement.COMPLAINED_UNREACHABLE) {
103
				actionInfo = this.action.analyseCode(this.scope, loopingContext, actionInfo).unconditionalCopy();
118
				actionInfo = this.action.analyseCode(this.scope, loopingContext, actionInfo).unconditionalCopy();
104
			}
119
			}
105
120
106
			// code generation can be optimized when no need to continue in the loop
121
			// code generation can be optimized when no need to continue in the loop
107
			exitBranch = flowInfo.unconditionalCopy().
122
			exitBranch = flowInfo.unconditionalCopy().
108
			addInitializationsFrom(condInfo.initsWhenFalse());
123
					addNullInfoFrom(condInfo.initsWhenFalse());
109
			// TODO (maxime) no need to test when false: can optimize (same for action being unreachable above)
124
			// TODO (maxime) no need to test when false: can optimize (same for action being unreachable above)
110
			if ((actionInfo.tagBits & loopingContext.initsOnContinue.tagBits &
125
			if ((actionInfo.tagBits & loopingContext.initsOnContinue.tagBits &
111
					FlowInfo.UNREACHABLE_OR_DEAD) != 0) {
126
					FlowInfo.UNREACHABLE_OR_DEAD) != 0) {
Lines 128-134 Link Here
128
		switch(this.kind) {
143
		switch(this.kind) {
129
			case ARRAY :
144
			case ARRAY :
130
				if (!hasEmptyAction
145
				if (!hasEmptyAction
131
						|| this.elementVariable.binding.resolvedPosition != -1) {
146
						|| elementVarBinding.resolvedPosition != -1) {
132
					this.collectionVariable.useFlag = LocalVariableBinding.USED;
147
					this.collectionVariable.useFlag = LocalVariableBinding.USED;
133
					if (this.continueLabel != null) {
148
					if (this.continueLabel != null) {
134
						this.indexVariable.useFlag = LocalVariableBinding.USED;
149
						this.indexVariable.useFlag = LocalVariableBinding.USED;
(-)a/org.eclipse.jdt.core/compiler/org/eclipse/jdt/internal/compiler/ast/IfStatement.java (-6 / +12 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 84-95 Link Here
84
		// No need if the whole if-else construct itself lies in unreachable code
86
		// No need if the whole if-else construct itself lies in unreachable code
85
		this.bits |= ASTNode.IsElseStatementUnreachable;
87
		this.bits |= ASTNode.IsElseStatementUnreachable;
86
	}
88
	}
89
	boolean reportDeadCodeForKnownPattern = !isKnowDeadCodePattern(this.condition) || currentScope.compilerOptions().reportDeadCodeInTrivialIfStatement;
87
	if (this.thenStatement != null) {
90
	if (this.thenStatement != null) {
88
		// Save info for code gen
91
		// Save info for code gen
89
		this.thenInitStateIndex = currentScope.methodScope().recordInitializationStates(thenFlowInfo);
92
		this.thenInitStateIndex = currentScope.methodScope().recordInitializationStates(thenFlowInfo);
90
		if (isConditionOptimizedFalse || ((this.bits & ASTNode.IsThenStatementUnreachable) != 0)) {
93
		if (isConditionOptimizedFalse || ((this.bits & ASTNode.IsThenStatementUnreachable) != 0)) {
91
			if (!isKnowDeadCodePattern(this.condition) || currentScope.compilerOptions().reportDeadCodeInTrivialIfStatement) {
94
			if (reportDeadCodeForKnownPattern) {
92
				this.thenStatement.complainIfUnreachable(thenFlowInfo, currentScope, initialComplaintLevel);
95
				this.thenStatement.complainIfUnreachable(thenFlowInfo, currentScope, initialComplaintLevel, false);
93
			} else {
96
			} else {
94
				// its a known coding pattern which should be tolerated by dead code analysis
97
				// its a known coding pattern which should be tolerated by dead code analysis
95
				// according to isKnowDeadCodePattern()
98
				// according to isKnowDeadCodePattern()
Lines 114-121 Link Here
114
		// Save info for code gen
117
		// Save info for code gen
115
		this.elseInitStateIndex = currentScope.methodScope().recordInitializationStates(elseFlowInfo);
118
		this.elseInitStateIndex = currentScope.methodScope().recordInitializationStates(elseFlowInfo);
116
		if (isConditionOptimizedTrue || ((this.bits & ASTNode.IsElseStatementUnreachable) != 0)) {
119
		if (isConditionOptimizedTrue || ((this.bits & ASTNode.IsElseStatementUnreachable) != 0)) {
117
			if (!isKnowDeadCodePattern(this.condition) || currentScope.compilerOptions().reportDeadCodeInTrivialIfStatement) {
120
			if (reportDeadCodeForKnownPattern) {
118
				this.elseStatement.complainIfUnreachable(elseFlowInfo, currentScope, initialComplaintLevel);
121
				this.elseStatement.complainIfUnreachable(elseFlowInfo, currentScope, initialComplaintLevel, false);
119
			} else {
122
			} else {
120
				// its a known coding pattern which should be tolerated by dead code analysis
123
				// its a known coding pattern which should be tolerated by dead code analysis
121
				// according to isKnowDeadCodePattern()
124
				// according to isKnowDeadCodePattern()
Lines 124-129 Link Here
124
		}
127
		}
125
		elseFlowInfo = this.elseStatement.analyseCode(currentScope, flowContext, elseFlowInfo);
128
		elseFlowInfo = this.elseStatement.analyseCode(currentScope, flowContext, elseFlowInfo);
126
	}
129
	}
130
	// process AutoCloseable resources closed in only one branch:
131
	currentScope.correlateTrackingVarsIfElse(thenFlowInfo, elseFlowInfo);
127
	// merge THEN & ELSE initializations
132
	// merge THEN & ELSE initializations
128
	FlowInfo mergedInfo = FlowInfo.mergedOptimizedBranchesIfElse(
133
	FlowInfo mergedInfo = FlowInfo.mergedOptimizedBranchesIfElse(
129
		thenFlowInfo,
134
		thenFlowInfo,
Lines 132-138 Link Here
132
		isConditionOptimizedFalse,
137
		isConditionOptimizedFalse,
133
		true /*if(true){ return; }  fake-reachable(); */,
138
		true /*if(true){ return; }  fake-reachable(); */,
134
		flowInfo,
139
		flowInfo,
135
		this);
140
		this,
141
		reportDeadCodeForKnownPattern);
136
	this.mergedInitStateIndex = currentScope.methodScope().recordInitializationStates(mergedInfo);
142
	this.mergedInitStateIndex = currentScope.methodScope().recordInitializationStates(mergedInfo);
137
	return mergedInfo;
143
	return mergedInfo;
138
}
144
}
(-)a/org.eclipse.jdt.core/compiler/org/eclipse/jdt/internal/compiler/ast/LocalDeclaration.java (-10 / +31 lines)
Lines 1-5 Link Here
1
/*******************************************************************************
1
/*******************************************************************************
2
 * Copyright (c) 2000, 2011 IBM Corporation and others.
2
 * Copyright (c) 2000, 2012 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-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 <stephan@cs.tu-berlin.de> - Contributions for 
10
 *     Stephan Herrmann <stephan@cs.tu-berlin.de> - Contributions for
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
15
 *							bug 186342 - [compiler][null] Using annotations for null checking
16
 *							bug 358903 - Filter practically unimportant resource leak warnings
17
 *							bug 370639 - [compiler][resource] restore the default for resource leak warnings
14
 *******************************************************************************/
18
 *******************************************************************************/
15
package org.eclipse.jdt.internal.compiler.ast;
19
package org.eclipse.jdt.internal.compiler.ast;
16
20
Lines 72-81 Link Here
72
		this.initialization.checkNPE(currentScope, flowContext, flowInfo);
76
		this.initialization.checkNPE(currentScope, flowContext, flowInfo);
73
	}
77
	}
74
	
78
	
79
	FlowInfo preInitInfo = null;
80
	boolean shouldAnalyseResource = this.binding != null 
81
			&& flowInfo.reachMode() == FlowInfo.REACHABLE
82
			&& FakedTrackingVariable.isAnyCloseable(this.initialization.resolvedType)
83
			&& currentScope.compilerOptions().analyseResourceLeaks;
84
	if (shouldAnalyseResource) {
85
		preInitInfo = flowInfo.unconditionalCopy();
86
		// analysis of resource leaks needs additional context while analyzing the RHS:
87
		FakedTrackingVariable.preConnectTrackerAcrossAssignment(this, this.binding, this.initialization);
88
	}
89
75
	flowInfo =
90
	flowInfo =
76
		this.initialization
91
		this.initialization
77
			.analyseCode(currentScope, flowContext, flowInfo)
92
			.analyseCode(currentScope, flowContext, flowInfo)
78
			.unconditionalInits();
93
			.unconditionalInits();
94
95
	if (shouldAnalyseResource)
96
		FakedTrackingVariable.handleResourceAssignment(currentScope, preInitInfo, flowInfo, this, this.initialization, this.binding);
97
	else
98
		FakedTrackingVariable.cleanUpAfterAssignment(currentScope, Binding.LOCAL, this.initialization);
99
79
	int nullStatus = this.initialization.nullStatus(flowInfo);
100
	int nullStatus = this.initialization.nullStatus(flowInfo);
80
	if (!flowInfo.isDefinitelyAssigned(this.binding)){// for local variable debug attributes
101
	if (!flowInfo.isDefinitelyAssigned(this.binding)){// for local variable debug attributes
81
		this.bits |= FirstAssignmentToLocal;
102
		this.bits |= FirstAssignmentToLocal;
Lines 83-89 Link Here
83
		this.bits &= ~FirstAssignmentToLocal;  // int i = (i = 0);
104
		this.bits &= ~FirstAssignmentToLocal;  // int i = (i = 0);
84
	}
105
	}
85
	flowInfo.markAsDefinitelyAssigned(this.binding);
106
	flowInfo.markAsDefinitelyAssigned(this.binding);
86
	nullStatus = checkAgainstNullAnnotation(currentScope, this.binding, nullStatus);		
107
	nullStatus = checkAssignmentAgainstNullAnnotation(currentScope, flowContext, this.binding, nullStatus, this.initialization);
87
	if ((this.binding.type.tagBits & TagBits.IsBaseType) == 0) {
108
	if ((this.binding.type.tagBits & TagBits.IsBaseType) == 0) {
88
		flowInfo.markNullStatus(this.binding, nullStatus);
109
		flowInfo.markNullStatus(this.binding, nullStatus);
89
		// no need to inform enclosing try block since its locals won't get
110
		// no need to inform enclosing try block since its locals won't get
Lines 133-141 Link Here
133
			this.initialization.generateCode(currentScope, codeStream, true);
154
			this.initialization.generateCode(currentScope, codeStream, true);
134
			// 26903, need extra cast to store null in array local var
155
			// 26903, need extra cast to store null in array local var
135
			if (this.binding.type.isArrayType()
156
			if (this.binding.type.isArrayType()
136
				&& (this.initialization.resolvedType == TypeBinding.NULL	// arrayLoc = null
157
				&& ((this.initialization instanceof CastExpression)	// arrayLoc = (type[])null
137
					|| ((this.initialization instanceof CastExpression)	// arrayLoc = (type[])null
158
						&& (((CastExpression)this.initialization).innermostCastedExpression().resolvedType == TypeBinding.NULL))){
138
						&& (((CastExpression)this.initialization).innermostCastedExpression().resolvedType == TypeBinding.NULL)))){
139
				codeStream.checkcast(this.binding.type);
159
				codeStream.checkcast(this.binding.type);
140
			}
160
			}
141
			codeStream.store(this.binding, false);
161
			codeStream.store(this.binding, false);
Lines 185-191 Link Here
185
		if ((this.modifiers & ClassFileConstants.AccFinal)!= 0 && this.initialization == null) {
205
		if ((this.modifiers & ClassFileConstants.AccFinal)!= 0 && this.initialization == null) {
186
			this.modifiers |= ExtraCompilerModifiers.AccBlankFinal;
206
			this.modifiers |= ExtraCompilerModifiers.AccBlankFinal;
187
		}
207
		}
188
		this.binding = new LocalVariableBinding(this, variableType, this.modifiers, false);
208
		this.binding = new LocalVariableBinding(this, variableType, this.modifiers, false /*isArgument*/);
189
		scope.addLocalVariable(this.binding);
209
		scope.addLocalVariable(this.binding);
190
		this.binding.setConstant(Constant.NotAConstant);
210
		this.binding.setConstant(Constant.NotAConstant);
191
		// allow to recursivelly target the binding....
211
		// allow to recursivelly target the binding....
Lines 249-254 Link Here
249
		}
269
		}
250
		// only resolve annotation at the end, for constant to be positioned before (96991)
270
		// only resolve annotation at the end, for constant to be positioned before (96991)
251
		resolveAnnotations(scope, this.annotations, this.binding);
271
		resolveAnnotations(scope, this.annotations, this.binding);
272
		scope.validateNullAnnotation(this.binding.tagBits, this.type, this.annotations);
252
	}
273
	}
253
274
254
	public void traverse(ASTVisitor visitor, BlockScope scope) {
275
	public void traverse(ASTVisitor visitor, BlockScope scope) {
(-)a/org.eclipse.jdt.core/compiler/org/eclipse/jdt/internal/compiler/ast/MemberValuePair.java (-1 / +4 lines)
Lines 1-5 Link Here
1
/*******************************************************************************
1
/*******************************************************************************
2
 * Copyright (c) 2000, 2010 IBM Corporation and others.
2
 * Copyright (c) 2000, 2012 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 - Contributions for
11
 *								bug 186342 - [compiler][null] Using annotations for null checking
12
 *								bug 365519 - editorial cleanup after bug 186342 and bug 365387
10
 *******************************************************************************/
13
 *******************************************************************************/
11
package org.eclipse.jdt.internal.compiler.ast;
14
package org.eclipse.jdt.internal.compiler.ast;
12
15
(-)a/org.eclipse.jdt.core/compiler/org/eclipse/jdt/internal/compiler/ast/MessageSend.java (-3 / +39 lines)
Lines 1-5 Link Here
1
/*******************************************************************************
1
/*******************************************************************************
2
 * Copyright (c) 2000, 2011 IBM Corporation and others.
2
 * Copyright (c) 2000, 2012 IBM Corporation and others.
3
 * All rights reserved. This program and the accompanying materials
3
 * All rights reserved. This program and the accompanying materials
4
 * are made available under the terms of the Eclipse Public License v1.0
4
 * are made available under the terms of the Eclipse Public License v1.0
5
 * which accompanies this distribution, and is available at
5
 * which accompanies this distribution, and is available at
Lines 8-14 Link Here
8
 * Contributors:
8
 * Contributors:
9
 *     IBM Corporation - initial API and implementation
9
 *     IBM Corporation - initial API and implementation
10
 *     Nick Teryaev - fix for bug (https://bugs.eclipse.org/bugs/show_bug.cgi?id=40752)
10
 *     Nick Teryaev - fix for bug (https://bugs.eclipse.org/bugs/show_bug.cgi?id=40752)
11
 *     Stephan Herrmann - Contribution for bug 319201 - [null] no warning when unboxing SingleNameReference causes NPE
11
 *     Stephan Herrmann - Contributions for
12
 *								bug 319201 - [null] no warning when unboxing SingleNameReference causes NPE
13
 *								bug 349326 - [1.7] new warning for missing try-with-resources
14
 *								bug 186342 - [compiler][null] Using annotations for null checking
15
 *								bug 358903 - Filter practically unimportant resource leak warnings
16
 *								bug 370639 - [compiler][resource] restore the default for resource leak warnings
12
 *******************************************************************************/
17
 *******************************************************************************/
13
package org.eclipse.jdt.internal.compiler.ast;
18
package org.eclipse.jdt.internal.compiler.ast;
14
19
Lines 38-43 Link Here
38
import org.eclipse.jdt.internal.compiler.lookup.SourceTypeBinding;
43
import org.eclipse.jdt.internal.compiler.lookup.SourceTypeBinding;
39
import org.eclipse.jdt.internal.compiler.lookup.TagBits;
44
import org.eclipse.jdt.internal.compiler.lookup.TagBits;
40
import org.eclipse.jdt.internal.compiler.lookup.TypeBinding;
45
import org.eclipse.jdt.internal.compiler.lookup.TypeBinding;
46
import org.eclipse.jdt.internal.compiler.lookup.TypeConstants;
41
import org.eclipse.jdt.internal.compiler.lookup.TypeIds;
47
import org.eclipse.jdt.internal.compiler.lookup.TypeIds;
42
import org.eclipse.jdt.internal.compiler.problem.ProblemSeverities;
48
import org.eclipse.jdt.internal.compiler.problem.ProblemSeverities;
43
49
Lines 60-65 Link Here
60
public FlowInfo analyseCode(BlockScope currentScope, FlowContext flowContext, FlowInfo flowInfo) {
66
public FlowInfo analyseCode(BlockScope currentScope, FlowContext flowContext, FlowInfo flowInfo) {
61
	boolean nonStatic = !this.binding.isStatic();
67
	boolean nonStatic = !this.binding.isStatic();
62
	flowInfo = this.receiver.analyseCode(currentScope, flowContext, flowInfo, nonStatic).unconditionalInits();
68
	flowInfo = this.receiver.analyseCode(currentScope, flowContext, flowInfo, nonStatic).unconditionalInits();
69
	// recording the closing of AutoCloseable resources:
70
	boolean analyseResources = currentScope.compilerOptions().analyseResourceLeaks;
71
	if (analyseResources && CharOperation.equals(TypeConstants.CLOSE, this.selector)) 
72
	{
73
		FakedTrackingVariable trackingVariable = FakedTrackingVariable.getCloseTrackingVariable(this.receiver);
74
		if (trackingVariable != null) { // null happens if receiver is not a local variable or not an AutoCloseable
75
			if (trackingVariable.methodScope == currentScope.methodScope()) {
76
				trackingVariable.markClose(flowInfo, flowContext);
77
			} else {
78
				trackingVariable.markClosedInNestedMethod();
79
			}
80
		}
81
	}
63
	if (nonStatic) {
82
	if (nonStatic) {
64
		this.receiver.checkNPE(currentScope, flowContext, flowInfo);
83
		this.receiver.checkNPE(currentScope, flowContext, flowInfo);
65
		// https://bugs.eclipse.org/bugs/show_bug.cgi?id=318682
84
		// https://bugs.eclipse.org/bugs/show_bug.cgi?id=318682
Lines 81-87 Link Here
81
				this.arguments[i].checkNPE(currentScope, flowContext, flowInfo);
100
				this.arguments[i].checkNPE(currentScope, flowContext, flowInfo);
82
			}
101
			}
83
			flowInfo = this.arguments[i].analyseCode(currentScope, flowContext, flowInfo).unconditionalInits();
102
			flowInfo = this.arguments[i].analyseCode(currentScope, flowContext, flowInfo).unconditionalInits();
103
			if (analyseResources) {
104
				// if argument is an AutoCloseable insert info that it *may* be closed (by the target method, i.e.)
105
				flowInfo = FakedTrackingVariable.markPassedToOutside(currentScope, this.arguments[i], flowInfo, false);
106
			}
84
		}
107
		}
108
		analyseArguments(currentScope, flowContext, flowInfo, this.binding, this.arguments);
85
	}
109
	}
86
	ReferenceBinding[] thrownExceptions;
110
	ReferenceBinding[] thrownExceptions;
87
	if ((thrownExceptions = this.binding.thrownExceptions) != Binding.NO_EXCEPTIONS) {
111
	if ((thrownExceptions = this.binding.thrownExceptions) != Binding.NO_EXCEPTIONS) {
Lines 97-102 Link Here
97
	}
121
	}
98
	manageSyntheticAccessIfNecessary(currentScope, flowInfo);
122
	manageSyntheticAccessIfNecessary(currentScope, flowInfo);
99
	return flowInfo;
123
	return flowInfo;
124
}
125
public void checkNPE(BlockScope scope, FlowContext flowContext, FlowInfo flowInfo) {
126
	super.checkNPE(scope, flowContext, flowInfo);
127
	if ((nullStatus(flowInfo) & FlowInfo.POTENTIALLY_NULL) != 0)
128
		scope.problemReporter().messageSendPotentialNullReference(this.binding, this);
100
}
129
}
101
/**
130
/**
102
 * @see org.eclipse.jdt.internal.compiler.ast.Expression#computeConversion(org.eclipse.jdt.internal.compiler.lookup.Scope, org.eclipse.jdt.internal.compiler.lookup.TypeBinding, org.eclipse.jdt.internal.compiler.lookup.TypeBinding)
131
 * @see org.eclipse.jdt.internal.compiler.ast.Expression#computeConversion(org.eclipse.jdt.internal.compiler.lookup.Scope, org.eclipse.jdt.internal.compiler.lookup.TypeBinding, org.eclipse.jdt.internal.compiler.lookup.TypeBinding)
Lines 251-259 Link Here
251
	}
280
	}
252
}
281
}
253
public int nullStatus(FlowInfo flowInfo) {
282
public int nullStatus(FlowInfo flowInfo) {
283
	if (this.binding.isValidBinding()) {
284
		// try to retrieve null status of this message send from an annotation of the called method:
285
		long tagBits = this.binding.tagBits;
286
		if ((tagBits & TagBits.AnnotationNonNull) != 0)
287
			return FlowInfo.NON_NULL;
288
		if ((tagBits & TagBits.AnnotationNullable) != 0)
289
			return FlowInfo.POTENTIALLY_NULL | FlowInfo.POTENTIALLY_NON_NULL;
290
	}
254
	return FlowInfo.UNKNOWN;
291
	return FlowInfo.UNKNOWN;
255
}
292
}
256
257
/**
293
/**
258
 * @see org.eclipse.jdt.internal.compiler.ast.Expression#postConversionType(Scope)
294
 * @see org.eclipse.jdt.internal.compiler.ast.Expression#postConversionType(Scope)
259
 */
295
 */
(-)a/org.eclipse.jdt.core/compiler/org/eclipse/jdt/internal/compiler/ast/MethodDeclaration.java (-7 / +21 lines)
Lines 1-5 Link Here
1
/*******************************************************************************
1
/*******************************************************************************
2
 * Copyright (c) 2000, 2011 IBM Corporation and others.
2
 * Copyright (c) 2000, 2012 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 - Contributions for
11
 *								bug 349326 - [1.7] new warning for missing try-with-resources
12
 *								bug 186342 - [compiler][null] Using annotations for null checking
13
 *								bug 365519 - editorial cleanup after bug 186342 and bug 365387
14
 *								bug 368546 - [compiler][resource] Avoid remaining false positives found when compiling the Eclipse SDK
10
 *******************************************************************************/
15
 *******************************************************************************/
11
package org.eclipse.jdt.internal.compiler.ast;
16
package org.eclipse.jdt.internal.compiler.ast;
12
17
Lines 15-22 Link Here
15
import org.eclipse.jdt.internal.compiler.CompilationResult;
20
import org.eclipse.jdt.internal.compiler.CompilationResult;
16
import org.eclipse.jdt.internal.compiler.classfmt.ClassFileConstants;
21
import org.eclipse.jdt.internal.compiler.classfmt.ClassFileConstants;
17
import org.eclipse.jdt.internal.compiler.flow.ExceptionHandlingFlowContext;
22
import org.eclipse.jdt.internal.compiler.flow.ExceptionHandlingFlowContext;
23
import org.eclipse.jdt.internal.compiler.flow.FlowContext;
18
import org.eclipse.jdt.internal.compiler.flow.FlowInfo;
24
import org.eclipse.jdt.internal.compiler.flow.FlowInfo;
19
import org.eclipse.jdt.internal.compiler.flow.InitializationFlowContext;
20
import org.eclipse.jdt.internal.compiler.impl.CompilerOptions;
25
import org.eclipse.jdt.internal.compiler.impl.CompilerOptions;
21
import org.eclipse.jdt.internal.compiler.lookup.Binding;
26
import org.eclipse.jdt.internal.compiler.lookup.Binding;
22
import org.eclipse.jdt.internal.compiler.lookup.ClassScope;
27
import org.eclipse.jdt.internal.compiler.lookup.ClassScope;
Lines 43-49 Link Here
43
		super(compilationResult);
48
		super(compilationResult);
44
	}
49
	}
45
50
46
	public void analyseCode(ClassScope classScope, InitializationFlowContext initializationContext, FlowInfo flowInfo) {
51
	public void analyseCode(ClassScope classScope, FlowContext flowContext, FlowInfo flowInfo) {
47
		// starting of the code analysis for methods
52
		// starting of the code analysis for methods
48
		if (this.ignoreFurtherInvestigation)
53
		if (this.ignoreFurtherInvestigation)
49
			return;
54
			return;
Lines 71-87 Link Here
71
76
72
			ExceptionHandlingFlowContext methodContext =
77
			ExceptionHandlingFlowContext methodContext =
73
				new ExceptionHandlingFlowContext(
78
				new ExceptionHandlingFlowContext(
74
					initializationContext,
79
					flowContext,
75
					this,
80
					this,
76
					this.binding.thrownExceptions,
81
					this.binding.thrownExceptions,
77
					null,
82
					null,
78
					this.scope,
83
					this.scope,
79
					FlowInfo.DEAD_END);
84
					FlowInfo.DEAD_END);
80
85
81
			// tag parameters as being set
86
			// nullity and mark as assigned
87
			analyseArguments(flowInfo);
88
82
			if (this.arguments != null) {
89
			if (this.arguments != null) {
83
				for (int i = 0, count = this.arguments.length; i < count; i++) {
90
				for (int i = 0, count = this.arguments.length; i < count; i++) {
84
					flowInfo.markAsDefinitelyAssigned(this.arguments[i].binding);
85
					// if this method uses a type parameter declared by the declaring class,
91
					// if this method uses a type parameter declared by the declaring class,
86
					// it can't be static. https://bugs.eclipse.org/bugs/show_bug.cgi?id=318682
92
					// it can't be static. https://bugs.eclipse.org/bugs/show_bug.cgi?id=318682
87
					if (this.arguments[i].binding != null && (this.arguments[i].binding.type instanceof TypeVariableBinding)) {
93
					if (this.arguments[i].binding != null && (this.arguments[i].binding.type instanceof TypeVariableBinding)) {
Lines 100-106 Link Here
100
				int complaintLevel = (flowInfo.reachMode() & FlowInfo.UNREACHABLE) == 0 ? Statement.NOT_COMPLAINED : Statement.COMPLAINED_FAKE_REACHABLE;
106
				int complaintLevel = (flowInfo.reachMode() & FlowInfo.UNREACHABLE) == 0 ? Statement.NOT_COMPLAINED : Statement.COMPLAINED_FAKE_REACHABLE;
101
				for (int i = 0, count = this.statements.length; i < count; i++) {
107
				for (int i = 0, count = this.statements.length; i < count; i++) {
102
					Statement stat = this.statements[i];
108
					Statement stat = this.statements[i];
103
					if ((complaintLevel = stat.complainIfUnreachable(flowInfo, this.scope, complaintLevel)) < Statement.COMPLAINED_UNREACHABLE) {
109
					if ((complaintLevel = stat.complainIfUnreachable(flowInfo, this.scope, complaintLevel, true)) < Statement.COMPLAINED_UNREACHABLE) {
104
						flowInfo = stat.analyseCode(this.scope, methodContext, flowInfo);
110
						flowInfo = stat.analyseCode(this.scope, methodContext, flowInfo);
105
					}
111
					}
106
				}
112
				}
Lines 134-139 Link Here
134
				}
140
				}
135
					
141
					
136
			}
142
			}
143
			this.scope.checkUnclosedCloseables(flowInfo, null, null/*don't report against a specific location*/, null);
137
		} catch (AbortMethod e) {
144
		} catch (AbortMethod e) {
138
			this.ignoreFurtherInvestigation = true;
145
			this.ignoreFurtherInvestigation = true;
139
		}
146
		}
Lines 305-308 Link Here
305
	public TypeParameter[] typeParameters() {
312
	public TypeParameter[] typeParameters() {
306
	    return this.typeParameters;
313
	    return this.typeParameters;
307
	}
314
	}
315
	
316
	void validateNullAnnotations() {
317
		super.validateNullAnnotations();
318
		// null-annotations on the return type?
319
		if (this.binding != null)
320
			this.scope.validateNullAnnotation(this.binding.tagBits, this.returnType, this.annotations);
321
	}
308
}
322
}
(-)a/org.eclipse.jdt.core/compiler/org/eclipse/jdt/internal/compiler/ast/QualifiedAllocationExpression.java (-2 / +24 lines)
Lines 1-5 Link Here
1
/*******************************************************************************
1
/*******************************************************************************
2
 * Copyright (c) 2000, 2011 IBM Corporation and others.
2
 * Copyright (c) 2000, 2012 IBM Corporation and others.
3
 * All rights reserved. This program and the accompanying materials
3
 * All rights reserved. This program and the accompanying materials
4
 * are made available under the terms of the Eclipse Public License v1.0
4
 * are made available under the terms of the Eclipse Public License v1.0
5
 * which accompanies this distribution, and is available at
5
 * which accompanies this distribution, and is available at
Lines 7-13 Link Here
7
 * 
7
 * 
8
 * Contributors:
8
 * Contributors:
9
 *     IBM Corporation - initial API and implementation
9
 *     IBM Corporation - initial API and implementation
10
 *     Stephan Herrmann - Contribution for bug 319201 - [null] no warning when unboxing SingleNameReference causes NPE
10
 *     Stephan Herrmann - Contributions for
11
 *     							bug 319201 - [null] no warning when unboxing SingleNameReference causes NPE
12
 *     							bug 349326 - [1.7] new warning for missing try-with-resources
13
 *								bug 186342 - [compiler][null] Using annotations for null checking
14
 *								bug 368546 - [compiler][resource] Avoid remaining false positives found when compiling the Eclipse SDK
15
 *								bug 370639 - [compiler][resource] restore the default for resource leak warnings
11
 *******************************************************************************/
16
 *******************************************************************************/
12
package org.eclipse.jdt.internal.compiler.ast;
17
package org.eclipse.jdt.internal.compiler.ast;
13
18
Lines 59-64 Link Here
59
		// analyse the enclosing instance
64
		// analyse the enclosing instance
60
		if (this.enclosingInstance != null) {
65
		if (this.enclosingInstance != null) {
61
			flowInfo = this.enclosingInstance.analyseCode(currentScope, flowContext, flowInfo);
66
			flowInfo = this.enclosingInstance.analyseCode(currentScope, flowContext, flowInfo);
67
		} else {
68
			if (this.binding.declaringClass.superclass().isMemberType() && !this.binding.declaringClass.superclass().isStatic()) {
69
				// creating an anonymous type of a non-static member type without an enclosing instance of parent type
70
				currentScope.resetEnclosingMethodStaticFlag();
71
			}
62
		}
72
		}
63
73
64
		// check captured variables are initialized in current context (26134)
74
		// check captured variables are initialized in current context (26134)
Lines 71-82 Link Here
71
81
72
		// process arguments
82
		// process arguments
73
		if (this.arguments != null) {
83
		if (this.arguments != null) {
84
			boolean analyseResources = currentScope.compilerOptions().analyseResourceLeaks;
74
			for (int i = 0, count = this.arguments.length; i < count; i++) {
85
			for (int i = 0, count = this.arguments.length; i < count; i++) {
86
				if (analyseResources) {
87
					// if argument is an AutoCloseable insert info that it *may* be closed (by the target method, i.e.)
88
					flowInfo = FakedTrackingVariable.markPassedToOutside(currentScope, this.arguments[i], flowInfo, false);
89
				}
75
				flowInfo = this.arguments[i].analyseCode(currentScope, flowContext, flowInfo);
90
				flowInfo = this.arguments[i].analyseCode(currentScope, flowContext, flowInfo);
76
				if ((this.arguments[i].implicitConversion & TypeIds.UNBOXING) != 0) {
91
				if ((this.arguments[i].implicitConversion & TypeIds.UNBOXING) != 0) {
77
					this.arguments[i].checkNPE(currentScope, flowContext, flowInfo);
92
					this.arguments[i].checkNPE(currentScope, flowContext, flowInfo);
78
				}
93
				}
79
			}
94
			}
95
			analyseArguments(currentScope, flowContext, flowInfo, this.binding, this.arguments);
80
		}
96
		}
81
97
82
		// analyse the anonymous nested type
98
		// analyse the anonymous nested type
Lines 98-103 Link Here
98
				flowInfo.unconditionalCopy(),
114
				flowInfo.unconditionalCopy(),
99
				currentScope);
115
				currentScope);
100
		}
116
		}
117
118
		// after having analysed exceptions above start tracking newly allocated resource:
119
		if (FakedTrackingVariable.isAnyCloseable(this.resolvedType) && currentScope.compilerOptions().analyseResourceLeaks) {
120
			FakedTrackingVariable.analyseCloseableAllocation(currentScope, flowInfo, this);
121
		}
122
101
		manageEnclosingInstanceAccessIfNecessary(currentScope, flowInfo);
123
		manageEnclosingInstanceAccessIfNecessary(currentScope, flowInfo);
102
		manageSyntheticAccessIfNecessary(currentScope, flowInfo);
124
		manageSyntheticAccessIfNecessary(currentScope, flowInfo);
103
		return flowInfo;
125
		return flowInfo;
(-)a/org.eclipse.jdt.core/compiler/org/eclipse/jdt/internal/compiler/ast/QualifiedNameReference.java (-3 / +18 lines)
Lines 1-5 Link Here
1
/*******************************************************************************
1
/*******************************************************************************
2
 * Copyright (c) 2000, 2011 IBM Corporation and others.
2
 * Copyright (c) 2000, 2012 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 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 186342 - [compiler][null] Using annotations for null checking
13
 *								bug 365519 - editorial cleanup after bug 186342 and bug 365387
14
 *								bug 368546 - [compiler][resource] Avoid remaining false positives found when compiling the Eclipse SDK
11
 *******************************************************************************/
15
 *******************************************************************************/
12
package org.eclipse.jdt.internal.compiler.ast;
16
package org.eclipse.jdt.internal.compiler.ast;
13
17
Lines 782-787 Link Here
782
			: type;
786
			: type;
783
}
787
}
784
788
789
public boolean isFieldAccess() {
790
	if (this.otherBindings != null) {
791
		return true;
792
	}
793
	return (this.bits & ASTNode.RestrictiveFlagMASK) == Binding.FIELD;
794
}
795
785
public void manageEnclosingInstanceAccessIfNecessary(BlockScope currentScope, FlowInfo flowInfo) {
796
public void manageEnclosingInstanceAccessIfNecessary(BlockScope currentScope, FlowInfo flowInfo) {
786
	//If inlinable field, forget the access emulation, the code gen will directly target it
797
	//If inlinable field, forget the access emulation, the code gen will directly target it
787
	if (((this.bits & ASTNode.DepthMASK) == 0) || (this.constant != Constant.NotAConstant)) {
798
	if (((this.bits & ASTNode.DepthMASK) == 0) || (this.constant != Constant.NotAConstant)) {
Lines 963-969 Link Here
963
							&& methodScope.lastVisibleFieldID >= 0
974
							&& methodScope.lastVisibleFieldID >= 0
964
							&& fieldBinding.id >= methodScope.lastVisibleFieldID
975
							&& fieldBinding.id >= methodScope.lastVisibleFieldID
965
							&& (!fieldBinding.isStatic() || methodScope.isStatic)) {
976
							&& (!fieldBinding.isStatic() || methodScope.isStatic)) {
966
						scope.problemReporter().forwardReference(this, this.indexOfFirstFieldBinding-1, fieldBinding);
977
						if (methodScope.insideTypeAnnotation && fieldBinding.id == methodScope.lastVisibleFieldID) {
978
							// false alarm, location is NOT a field initializer but the value in a memberValuePair
979
						} else {
980
							scope.problemReporter().forwardReference(this, this.indexOfFirstFieldBinding-1, fieldBinding);
981
						}
967
					}
982
					}
968
					if (isFieldUseDeprecated(fieldBinding, scope, this.indexOfFirstFieldBinding == this.tokens.length ? this.bits : 0)) {
983
					if (isFieldUseDeprecated(fieldBinding, scope, this.indexOfFirstFieldBinding == this.tokens.length ? this.bits : 0)) {
969
						scope.problemReporter().deprecatedField(fieldBinding, this);	
984
						scope.problemReporter().deprecatedField(fieldBinding, this);	
(-)a/org.eclipse.jdt.core/compiler/org/eclipse/jdt/internal/compiler/ast/ReturnStatement.java (-7 / +57 lines)
Lines 1-5 Link Here
1
/*******************************************************************************
1
/*******************************************************************************
2
 * Copyright (c) 2000, 2011 IBM Corporation and others.
2
 * Copyright (c) 2000, 2012 IBM Corporation and others.
3
 * All rights reserved. This program and the accompanying materials
3
 * All rights reserved. This program and the accompanying materials
4
 * are made available under the terms of the Eclipse Public License v1.0
4
 * are made available under the terms of the Eclipse Public License v1.0
5
 * which accompanies this distribution, and is available at
5
 * which accompanies this distribution, and is available at
Lines 7-13 Link Here
7
 *
7
 *
8
 * Contributors:
8
 * Contributors:
9
 *     IBM Corporation - initial API and implementation
9
 *     IBM Corporation - initial API and implementation
10
 *     Stephan Herrmann - Contribution for bug 319201 - [null] no warning when unboxing SingleNameReference causes NPE
10
 *     Stephan Herrmann - Contributions for
11
 *     							bug 319201 - [null] no warning when unboxing SingleNameReference causes NPE
12
 *     							bug 349326 - [1.7] new warning for missing try-with-resources
13
 *     							bug 360328 - [compiler][null] detect null problems in nested code (local class inside a loop)
14
 *								bug 186342 - [compiler][null] Using annotations for null checking
15
 *								bug 365835 - [compiler][null] inconsistent error reporting.
16
 *								bug 365519 - editorial cleanup after bug 186342 and bug 365387
17
 *								bug 358903 - Filter practically unimportant resource leak warnings
18
 *								bug 368546 - [compiler][resource] Avoid remaining false positives found when compiling the Eclipse SDK
19
 *								bug 370639 - [compiler][resource] restore the default for resource leak warnings
11
 *******************************************************************************/
20
 *******************************************************************************/
12
package org.eclipse.jdt.internal.compiler.ast;
21
package org.eclipse.jdt.internal.compiler.ast;
13
22
Lines 35-53 Link Here
35
44
36
	// lookup the label, this should answer the returnContext
45
	// lookup the label, this should answer the returnContext
37
46
47
	MethodScope methodScope = currentScope.methodScope();
38
	if (this.expression != null) {
48
	if (this.expression != null) {
39
		flowInfo = this.expression.analyseCode(currentScope, flowContext, flowInfo);
49
		flowInfo = this.expression.analyseCode(currentScope, flowContext, flowInfo);
40
		if ((this.expression.implicitConversion & TypeIds.UNBOXING) != 0) {
50
		if ((this.expression.implicitConversion & TypeIds.UNBOXING) != 0) {
41
			this.expression.checkNPE(currentScope, flowContext, flowInfo);
51
			this.expression.checkNPE(currentScope, flowContext, flowInfo);
42
		}
52
		}
53
		if (flowInfo.reachMode() == FlowInfo.REACHABLE)
54
			checkAgainstNullAnnotation(currentScope, flowContext, this.expression.nullStatus(flowInfo));
55
		if (currentScope.compilerOptions().analyseResourceLeaks) {
56
			FakedTrackingVariable trackingVariable = FakedTrackingVariable.getCloseTrackingVariable(this.expression);
57
			if (trackingVariable != null) {
58
				if (methodScope != trackingVariable.methodScope)
59
					trackingVariable.markClosedInNestedMethod();
60
				// by returning the method passes the responsibility to the caller:
61
				flowInfo = FakedTrackingVariable.markPassedToOutside(currentScope, this.expression, flowInfo, true);
62
			}
63
		}
43
	}
64
	}
44
	this.initStateIndex =
65
	this.initStateIndex =
45
		currentScope.methodScope().recordInitializationStates(flowInfo);
66
		methodScope.recordInitializationStates(flowInfo);
46
	// compute the return sequence (running the finally blocks)
67
	// compute the return sequence (running the finally blocks)
47
	FlowContext traversedContext = flowContext;
68
	FlowContext traversedContext = flowContext;
48
	int subCount = 0;
69
	int subCount = 0;
49
	boolean saveValueNeeded = false;
70
	boolean saveValueNeeded = false;
50
	boolean hasValueToSave = needValueStore();
71
	boolean hasValueToSave = needValueStore();
72
	boolean noAutoCloseables = true;
51
	do {
73
	do {
52
		SubRoutineStatement sub;
74
		SubRoutineStatement sub;
53
		if ((sub = traversedContext.subroutine()) != null) {
75
		if ((sub = traversedContext.subroutine()) != null) {
Lines 62-67 Link Here
62
				saveValueNeeded = false;
84
				saveValueNeeded = false;
63
				this.bits |= ASTNode.IsAnySubRoutineEscaping;
85
				this.bits |= ASTNode.IsAnySubRoutineEscaping;
64
				break;
86
				break;
87
			}
88
			if (sub instanceof TryStatement) {
89
				if (((TryStatement) sub).resources.length > 0) {
90
					noAutoCloseables = false;
91
				}
65
			}
92
			}
66
		}
93
		}
67
		traversedContext.recordReturnFrom(flowInfo.unconditionalInits());
94
		traversedContext.recordReturnFrom(flowInfo.unconditionalInits());
Lines 79-92 Link Here
79
					}
106
					}
80
					saveValueNeeded = true;
107
					saveValueNeeded = true;
81
					this.initStateIndex =
108
					this.initStateIndex =
82
						currentScope.methodScope().recordInitializationStates(flowInfo);
109
						methodScope.recordInitializationStates(flowInfo);
83
				}
110
				}
84
			}
111
			}
85
		} else if (traversedContext instanceof InitializationFlowContext) {
112
		} else if (traversedContext instanceof InitializationFlowContext) {
86
				currentScope.problemReporter().cannotReturnInInitializer(this);
113
				currentScope.problemReporter().cannotReturnInInitializer(this);
87
				return FlowInfo.DEAD_END;
114
				return FlowInfo.DEAD_END;
88
		}
115
		}
89
	} while ((traversedContext = traversedContext.parent) != null);
116
	} while ((traversedContext = traversedContext.getLocalParent()) != null);
90
117
91
	// resize subroutines
118
	// resize subroutines
92
	if ((this.subroutines != null) && (subCount != this.subroutines.length)) {
119
	if ((this.subroutines != null) && (subCount != this.subroutines.length)) {
Lines 101-110 Link Here
101
	} else {
128
	} else {
102
		this.saveValueVariable = null;
129
		this.saveValueVariable = null;
103
		if (((this.bits & ASTNode.IsSynchronized) == 0) && this.expression != null && this.expression.resolvedType == TypeBinding.BOOLEAN) {
130
		if (((this.bits & ASTNode.IsSynchronized) == 0) && this.expression != null && this.expression.resolvedType == TypeBinding.BOOLEAN) {
104
			this.expression.bits |= ASTNode.IsReturnedValue;
131
			if (noAutoCloseables) { // can't abruptly return in the presence of autocloseables. See https://bugs.eclipse.org/bugs/show_bug.cgi?id=367566
132
				this.expression.bits |= ASTNode.IsReturnedValue;
133
			}
105
		}
134
		}
106
	}
135
	}
136
	currentScope.checkUnclosedCloseables(flowInfo, flowContext, this, currentScope);
107
	return FlowInfo.DEAD_END;
137
	return FlowInfo.DEAD_END;
138
}
139
void checkAgainstNullAnnotation(BlockScope scope, FlowContext flowContext, int nullStatus) {
140
	if (nullStatus != FlowInfo.NON_NULL) {
141
		// if we can't prove non-null check against declared null-ness of the enclosing method:
142
		long tagBits;
143
		MethodBinding methodBinding;
144
		try {
145
			methodBinding = scope.methodScope().referenceMethod().binding;
146
			tagBits = methodBinding.tagBits;
147
		} catch (NullPointerException npe) {
148
			// chain of references in try-block has several potential nulls;
149
			// any null means we cannot perform the following check
150
			return;			
151
		}
152
		if ((tagBits & TagBits.AnnotationNonNull) != 0) {
153
			flowContext.recordNullityMismatch(scope, this.expression, nullStatus, methodBinding.returnType);
154
		}
155
	}
108
}
156
}
109
157
110
/**
158
/**
Lines 142-152 Link Here
142
		}
190
		}
143
	}
191
	}
144
	if (this.saveValueVariable != null) {
192
	if (this.saveValueVariable != null) {
145
		codeStream.addVariable(this.saveValueVariable);
146
		codeStream.load(this.saveValueVariable);
193
		codeStream.load(this.saveValueVariable);
147
	}
194
	}
148
	if (this.expression != null && !alreadyGeneratedExpression) {
195
	if (this.expression != null && !alreadyGeneratedExpression) {
149
		this.expression.generateCode(currentScope, codeStream, true);
196
		this.expression.generateCode(currentScope, codeStream, true);
197
		// hook necessary for Code Snippet
150
		generateStoreSaveValueIfNecessary(codeStream);
198
		generateStoreSaveValueIfNecessary(codeStream);
151
	}
199
	}
152
	// output the suitable return bytecode or wrap the value inside a descriptor for doits
200
	// output the suitable return bytecode or wrap the value inside a descriptor for doits
Lines 173-178 Link Here
173
public void generateStoreSaveValueIfNecessary(CodeStream codeStream){
221
public void generateStoreSaveValueIfNecessary(CodeStream codeStream){
174
	if (this.saveValueVariable != null) {
222
	if (this.saveValueVariable != null) {
175
		codeStream.store(this.saveValueVariable, false);
223
		codeStream.store(this.saveValueVariable, false);
224
		// the variable is visible as soon as the local is stored
225
		codeStream.addVariable(this.saveValueVariable);
176
	}
226
	}
177
}
227
}
178
228
(-)a/org.eclipse.jdt.core/compiler/org/eclipse/jdt/internal/compiler/ast/SingleNameReference.java (-3 / +2 lines)
Lines 352-360 Link Here
352
			}
352
			}
353
			// 26903, need extra cast to store null in array local var
353
			// 26903, need extra cast to store null in array local var
354
			if (localBinding.type.isArrayType()
354
			if (localBinding.type.isArrayType()
355
				&& (assignment.expression.resolvedType == TypeBinding.NULL	// arrayLoc = null
355
				&& ((assignment.expression instanceof CastExpression)	// arrayLoc = (type[])null
356
					|| ((assignment.expression instanceof CastExpression)	// arrayLoc = (type[])null
356
						&& (((CastExpression)assignment.expression).innermostCastedExpression().resolvedType == TypeBinding.NULL))){
357
						&& (((CastExpression)assignment.expression).innermostCastedExpression().resolvedType == TypeBinding.NULL)))){
358
				codeStream.checkcast(localBinding.type);
357
				codeStream.checkcast(localBinding.type);
359
			}
358
			}
360
359
(-)a/org.eclipse.jdt.core/compiler/org/eclipse/jdt/internal/compiler/ast/Statement.java (-6 / +66 lines)
Lines 1-5 Link Here
1
/*******************************************************************************
1
/*******************************************************************************
2
 * Copyright (c) 2000, 2011 IBM Corporation and others.
2
 * Copyright (c) 2000, 2012 IBM Corporation and others.
3
 * All rights reserved. This program and the accompanying materials
3
 * All rights reserved. This program and the accompanying materials
4
 * are made available under the terms of the Eclipse Public License v1.0
4
 * are made available under the terms of the Eclipse Public License v1.0
5
 * which accompanies this distribution, and is available at
5
 * which accompanies this distribution, and is available at
Lines 7-13 Link Here
7
 *
7
 *
8
 * Contributors:
8
 * Contributors:
9
 *     IBM Corporation - initial API and implementation
9
 *     IBM Corporation - initial API and implementation
10
 *     Stephan Herrmann - Contribution for bug 335093 - [compiler][null] minimal hook for future null annotation support
10
 *     Stephan Herrmann - Contributions for
11
 *								bug 335093 - [compiler][null] minimal hook for future null annotation support
12
 *								bug 349326 - [1.7] new warning for missing try-with-resources
13
 *								bug 186342 - [compiler][null] Using annotations for null checking
14
 *								bug 365983 - [compiler][null] AIOOB with null annotation analysis and varargs
15
 *								bug 368546 - [compiler][resource] Avoid remaining false positives found when compiling the Eclipse SDK
16
 *								bug 370930 - NonNull annotation not considered for enhanced for loops
11
 *******************************************************************************/
17
 *******************************************************************************/
12
package org.eclipse.jdt.internal.compiler.ast;
18
package org.eclipse.jdt.internal.compiler.ast;
13
19
Lines 55-62 Link Here
55
	public static final int COMPLAINED_FAKE_REACHABLE = 1;
61
	public static final int COMPLAINED_FAKE_REACHABLE = 1;
56
	public static final int COMPLAINED_UNREACHABLE = 2;
62
	public static final int COMPLAINED_UNREACHABLE = 2;
57
	
63
	
58
/** Empty hook for checking null status against declaration using null annotations, once this will be supported. */
64
59
protected int checkAgainstNullAnnotation(BlockScope currentScope, LocalVariableBinding local, int nullStatus) {
65
/** Analysing arguments of MessageSend, ExplicitConstructorCall, AllocationExpression. */
66
protected void analyseArguments(BlockScope currentScope, FlowContext flowContext, FlowInfo flowInfo, MethodBinding methodBinding, Expression[] arguments)
67
{
68
	// compare actual null-status against parameter annotations of the called method:
69
	if (arguments != null && methodBinding.parameterNonNullness != null) {
70
71
		// check if varargs need special treatment:
72
		int numParamsToCheck = methodBinding.parameters.length;
73
		boolean passThrough = false;
74
		if (methodBinding.isVarargs()) {
75
			int varArgPos = numParamsToCheck-1;
76
			// this if-block essentially copied from generateArguments(..):
77
			if (numParamsToCheck == arguments.length) {
78
				TypeBinding varArgsType = methodBinding.parameters[varArgPos];
79
				TypeBinding lastType = arguments[varArgPos].resolvedType;
80
				if (lastType == TypeBinding.NULL
81
						|| (varArgsType.dimensions() == lastType.dimensions()
82
						&& lastType.isCompatibleWith(varArgsType)))
83
					passThrough = true; // pass directly as-is
84
			}
85
			if (!passThrough)
86
				numParamsToCheck--; // with non-passthrough varargs last param is fed from individual args -> don't check
87
		}
88
89
		for (int i = 0; i < numParamsToCheck; i++) {
90
			if (methodBinding.parameterNonNullness[i] == Boolean.TRUE) {
91
				TypeBinding expectedType = methodBinding.parameters[i];
92
				Expression argument = arguments[i];
93
				int nullStatus = argument.nullStatus(flowInfo); // slight loss of precision: should also use the null info from the receiver.
94
				if (nullStatus != FlowInfo.NON_NULL) // if required non-null is not provided
95
					flowContext.recordNullityMismatch(currentScope, argument, nullStatus, expectedType);
96
			}
97
		}
98
	}
99
}
100
101
/** Check null-ness of 'local' against a possible null annotation */
102
protected int checkAssignmentAgainstNullAnnotation(BlockScope currentScope, FlowContext flowContext,
103
												   LocalVariableBinding local, int nullStatus, Expression expression)
104
{
105
	if (local != null) {
106
		if ((local.tagBits & TagBits.AnnotationNonNull) != 0
107
				&& nullStatus != FlowInfo.NON_NULL) {
108
			flowContext.recordNullityMismatch(currentScope, expression, nullStatus, local.type);
109
			return FlowInfo.NON_NULL;
110
		} else if ((local.tagBits & TagBits.AnnotationNullable) != 0
111
				&& nullStatus == FlowInfo.UNKNOWN) {	// provided a legacy type?
112
			return FlowInfo.POTENTIALLY_NULL;			// -> use more specific info from the annotation
113
		}
114
	}
60
	return nullStatus;
115
	return nullStatus;
61
}
116
}
62
117
Lines 70-87 Link Here
70
125
71
// Report an error if necessary (if even more unreachable than previously reported
126
// Report an error if necessary (if even more unreachable than previously reported
72
// complaintLevel = 0 if was reachable up until now, 1 if fake reachable (deadcode), 2 if fatal unreachable (error)
127
// complaintLevel = 0 if was reachable up until now, 1 if fake reachable (deadcode), 2 if fatal unreachable (error)
73
public int complainIfUnreachable(FlowInfo flowInfo, BlockScope scope, int previousComplaintLevel) {
128
public int complainIfUnreachable(FlowInfo flowInfo, BlockScope scope, int previousComplaintLevel, boolean endOfBlock) {
74
	if ((flowInfo.reachMode() & FlowInfo.UNREACHABLE) != 0) {
129
	if ((flowInfo.reachMode() & FlowInfo.UNREACHABLE) != 0) {
75
		if ((flowInfo.reachMode() & FlowInfo.UNREACHABLE_OR_DEAD) != 0)
130
		if ((flowInfo.reachMode() & FlowInfo.UNREACHABLE_OR_DEAD) != 0)
76
			this.bits &= ~ASTNode.IsReachable;
131
			this.bits &= ~ASTNode.IsReachable;
77
		if (flowInfo == FlowInfo.DEAD_END) {
132
		if (flowInfo == FlowInfo.DEAD_END) {
78
			if (previousComplaintLevel < COMPLAINED_UNREACHABLE) {
133
			if (previousComplaintLevel < COMPLAINED_UNREACHABLE) {
79
				scope.problemReporter().unreachableCode(this);
134
				scope.problemReporter().unreachableCode(this);
135
				if (endOfBlock)
136
					scope.checkUnclosedCloseables(flowInfo, null, null, null);
80
			}
137
			}
81
			return COMPLAINED_UNREACHABLE;
138
			return COMPLAINED_UNREACHABLE;
82
		} else {
139
		} else {
83
			if (previousComplaintLevel < COMPLAINED_FAKE_REACHABLE) {
140
			if (previousComplaintLevel < COMPLAINED_FAKE_REACHABLE) {
84
				scope.problemReporter().fakeReachable(this);
141
				scope.problemReporter().fakeReachable(this);
142
				if (endOfBlock)
143
					scope.checkUnclosedCloseables(flowInfo, null, null, null);
85
			}
144
			}
86
			return COMPLAINED_FAKE_REACHABLE;
145
			return COMPLAINED_FAKE_REACHABLE;
87
		}
146
		}
Lines 155-164 Link Here
155
	if (scope.isBoxingCompatibleWith(expressionType, targetType))
214
	if (scope.isBoxingCompatibleWith(expressionType, targetType))
156
		return true;
215
		return true;
157
216
158
	return expressionType.isBaseType()  // narrowing then boxing ?
217
	return expressionType.isBaseType()  // narrowing then boxing ? Only allowed for some target types see 362279
159
		&& !targetType.isBaseType()
218
		&& !targetType.isBaseType()
160
		&& !targetType.isTypeVariable()
219
		&& !targetType.isTypeVariable()
161
		&& scope.compilerOptions().sourceLevel >= org.eclipse.jdt.internal.compiler.classfmt.ClassFileConstants.JDK1_5 // autoboxing
220
		&& scope.compilerOptions().sourceLevel >= org.eclipse.jdt.internal.compiler.classfmt.ClassFileConstants.JDK1_5 // autoboxing
221
		&& (targetType.id == TypeIds.T_JavaLangByte || targetType.id == TypeIds.T_JavaLangShort || targetType.id == TypeIds.T_JavaLangCharacter)
162
		&& expression.isConstantValueOfTypeAssignableToType(expressionType, scope.environment().computeBoxingType(targetType));
222
		&& expression.isConstantValueOfTypeAssignableToType(expressionType, scope.environment().computeBoxingType(targetType));
163
}
223
}
164
224
(-)a/org.eclipse.jdt.core/compiler/org/eclipse/jdt/internal/compiler/ast/SwitchStatement.java (-2 / +7 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 99-105 Link Here
99
					} else {
101
					} else {
100
						fallThroughState = FALLTHROUGH; // reset below if needed
102
						fallThroughState = FALLTHROUGH; // reset below if needed
101
					}
103
					}
102
					if ((complaintLevel = statement.complainIfUnreachable(caseInits, this.scope, complaintLevel)) < Statement.COMPLAINED_UNREACHABLE) {
104
					if ((complaintLevel = statement.complainIfUnreachable(caseInits, this.scope, complaintLevel, true)) < Statement.COMPLAINED_UNREACHABLE) {
103
						caseInits = statement.analyseCode(this.scope, switchContext, caseInits);
105
						caseInits = statement.analyseCode(this.scope, switchContext, caseInits);
104
						if (caseInits == FlowInfo.DEAD_END) {
106
						if (caseInits == FlowInfo.DEAD_END) {
105
							fallThroughState = ESCAPING;
107
							fallThroughState = ESCAPING;
Lines 461-466 Link Here
461
							break checkType;
463
							break checkType;
462
					} else if (expressionType.isEnum()) {
464
					} else if (expressionType.isEnum()) {
463
						isEnumSwitch = true;
465
						isEnumSwitch = true;
466
						if (upperScope.compilerOptions().complianceLevel < ClassFileConstants.JDK1_5) {
467
							upperScope.problemReporter().incorrectSwitchType(this.expression, expressionType); // https://bugs.eclipse.org/bugs/show_bug.cgi?id=360317
468
						}
464
						break checkType;
469
						break checkType;
465
					} else if (upperScope.isBoxingCompatibleWith(expressionType, TypeBinding.INT)) {
470
					} else if (upperScope.isBoxingCompatibleWith(expressionType, TypeBinding.INT)) {
466
						this.expression.computeConversion(upperScope, TypeBinding.INT, expressionType);
471
						this.expression.computeConversion(upperScope, TypeBinding.INT, expressionType);
(-)a/org.eclipse.jdt.core/compiler/org/eclipse/jdt/internal/compiler/ast/ThrowStatement.java (-1 / +5 lines)
Lines 1-5 Link Here
1
/*******************************************************************************
1
/*******************************************************************************
2
 * Copyright (c) 2000, 2009 IBM Corporation and others.
2
 * Copyright (c) 2000, 2012 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 - Contributions for
11
 *								bug 359334 - Analysis for resource leak warnings does not consider exceptions as method exit points
12
 *								bug 368546 - [compiler][resource] Avoid remaining false positives found when compiling the Eclipse SDK
10
 *******************************************************************************/
13
 *******************************************************************************/
11
package org.eclipse.jdt.internal.compiler.ast;
14
package org.eclipse.jdt.internal.compiler.ast;
12
15
Lines 35-40 Link Here
35
	this.exception.checkNPE(currentScope, flowContext, flowInfo);
38
	this.exception.checkNPE(currentScope, flowContext, flowInfo);
36
	// need to check that exception thrown is actually caught somewhere
39
	// need to check that exception thrown is actually caught somewhere
37
	flowContext.checkExceptionHandlers(this.exceptionType, this, flowInfo, currentScope);
40
	flowContext.checkExceptionHandlers(this.exceptionType, this, flowInfo, currentScope);
41
	currentScope.checkUnclosedCloseables(flowInfo, flowContext, this, currentScope);
38
	return FlowInfo.DEAD_END;
42
	return FlowInfo.DEAD_END;
39
}
43
}
40
44
(-)a/org.eclipse.jdt.core/compiler/org/eclipse/jdt/internal/compiler/ast/TryStatement.java (-12 / +46 lines)
Lines 1-5 Link Here
1
/*******************************************************************************
1
/*******************************************************************************
2
 * Copyright (c) 2000, 2011 IBM Corporation and others.
2
 * Copyright (c) 2000, 2012 IBM Corporation and others.
3
 * All rights reserved. This program and the accompanying materials
3
 * All rights reserved. This program and the accompanying materials
4
 * are made available under the terms of the Eclipse Public License v1.0
4
 * are made available under the terms of the Eclipse Public License v1.0
5
 * which accompanies this distribution, and is available at
5
 * which accompanies this distribution, and is available at
Lines 7-13 Link Here
7
 *
7
 *
8
 * Contributors:
8
 * Contributors:
9
 *     IBM Corporation - initial API and implementation
9
 *     IBM Corporation - initial API and implementation
10
 *     Stephan Herrmann - Contribution for bug 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 358827 - [1.7] exception analysis for t-w-r spoils null analysis
13
 *     							bug 349326 - [1.7] new warning for missing try-with-resources
14
 *     							bug 359334 - Analysis for resource leak warnings does not consider exceptions as method exit points
15
 *								bug 358903 - Filter practically unimportant resource leak warnings
11
 *******************************************************************************/
16
 *******************************************************************************/
12
package org.eclipse.jdt.internal.compiler.ast;
17
package org.eclipse.jdt.internal.compiler.ast;
13
18
Lines 65-70 Link Here
65
	// for local variables table attributes
70
	// for local variables table attributes
66
	int mergedInitStateIndex = -1;
71
	int mergedInitStateIndex = -1;
67
	int preTryInitStateIndex = -1;
72
	int preTryInitStateIndex = -1;
73
	int postTryInitStateIndex = -1;
68
	int[] postResourcesInitStateIndexes;
74
	int[] postResourcesInitStateIndexes;
69
	int naturalExitMergeInitStateIndex = -1;
75
	int naturalExitMergeInitStateIndex = -1;
70
	int[] catchExitInitStateIndexes;
76
	int[] catchExitInitStateIndexes;
Lines 124-131 Link Here
124
		for (int i = 0; i < resourcesLength; i++) {
130
		for (int i = 0; i < resourcesLength; i++) {
125
			flowInfo = this.resources[i].analyseCode(currentScope, handlingContext, flowInfo.copy());
131
			flowInfo = this.resources[i].analyseCode(currentScope, handlingContext, flowInfo.copy());
126
			this.postResourcesInitStateIndexes[i] = currentScope.methodScope().recordInitializationStates(flowInfo);
132
			this.postResourcesInitStateIndexes[i] = currentScope.methodScope().recordInitializationStates(flowInfo);
127
			this.resources[i].binding.useFlag = LocalVariableBinding.USED; // Is implicitly used anyways.
133
			LocalVariableBinding resourceBinding = this.resources[i].binding;
128
			TypeBinding type = this.resources[i].binding.type;
134
			resourceBinding.useFlag = LocalVariableBinding.USED; // Is implicitly used anyways.
135
			if (resourceBinding.closeTracker != null) {
136
				// this was false alarm, we don't need to track the resource
137
				this.tryBlock.scope.removeTrackingVar(resourceBinding.closeTracker);
138
				// keep the tracking variable in the resourceBinding in order to prevent creating a new one while analyzing the try block
139
			}
140
			TypeBinding type = resourceBinding.type;
129
			if (type != null && type.isValidBinding()) {
141
			if (type != null && type.isValidBinding()) {
130
				ReferenceBinding binding = (ReferenceBinding) type;
142
				ReferenceBinding binding = (ReferenceBinding) type;
131
				MethodBinding closeMethod = binding.getExactMethod(ConstantPool.Close, new TypeBinding [0], this.scope.compilationUnitScope()); // scope needs to be tighter
143
				MethodBinding closeMethod = binding.getExactMethod(ConstantPool.Close, new TypeBinding [0], this.scope.compilationUnitScope()); // scope needs to be tighter
Lines 145-151 Link Here
145
			if ((tryInfo.tagBits & FlowInfo.UNREACHABLE_OR_DEAD) != 0)
157
			if ((tryInfo.tagBits & FlowInfo.UNREACHABLE_OR_DEAD) != 0)
146
				this.bits |= ASTNode.IsTryBlockExiting;
158
				this.bits |= ASTNode.IsTryBlockExiting;
147
		}
159
		}
148
160
		if (resourcesLength > 0) { 
161
			this.postTryInitStateIndex = currentScope.methodScope().recordInitializationStates(tryInfo);
162
		}
149
		// check unreachable catch blocks
163
		// check unreachable catch blocks
150
		handlingContext.complainIfUnusedExceptionHandlers(this.scope, this);
164
		handlingContext.complainIfUnusedExceptionHandlers(this.scope, this);
151
165
Lines 229-234 Link Here
229
		if (subInfo == FlowInfo.DEAD_END) {
243
		if (subInfo == FlowInfo.DEAD_END) {
230
			this.bits |= ASTNode.IsSubRoutineEscaping;
244
			this.bits |= ASTNode.IsSubRoutineEscaping;
231
			this.scope.problemReporter().finallyMustCompleteNormally(this.finallyBlock);
245
			this.scope.problemReporter().finallyMustCompleteNormally(this.finallyBlock);
246
		} else {
247
			// for resource analysis we need the finallyInfo in these nested scopes:
248
			FlowInfo finallyInfo = subInfo.copy();
249
			this.tryBlock.scope.finallyInfo = finallyInfo;
250
			if (this.catchBlocks != null) {
251
				for (int i = 0; i < this.catchBlocks.length; i++)
252
					this.catchBlocks[i].scope.finallyInfo = finallyInfo;
253
			}
232
		}
254
		}
233
		this.subRoutineInits = subInfo;
255
		this.subRoutineInits = subInfo;
234
		// process the try block in a context handling the local exceptions.
256
		// process the try block in a context handling the local exceptions.
Lines 250-264 Link Here
250
		for (int i = 0; i < resourcesLength; i++) {
272
		for (int i = 0; i < resourcesLength; i++) {
251
			flowInfo = this.resources[i].analyseCode(currentScope, handlingContext, flowInfo.copy());
273
			flowInfo = this.resources[i].analyseCode(currentScope, handlingContext, flowInfo.copy());
252
			this.postResourcesInitStateIndexes[i] = currentScope.methodScope().recordInitializationStates(flowInfo);
274
			this.postResourcesInitStateIndexes[i] = currentScope.methodScope().recordInitializationStates(flowInfo);
253
			this.resources[i].binding.useFlag = LocalVariableBinding.USED; // Is implicitly used anyways.
275
			LocalVariableBinding resourceBinding = this.resources[i].binding;
254
			TypeBinding type = this.resources[i].binding.type;
276
			resourceBinding.useFlag = LocalVariableBinding.USED; // Is implicitly used anyways.
277
			if (resourceBinding.closeTracker != null) {
278
				// this was false alarm, we don't need to track the resource
279
				this.tryBlock.scope.removeTrackingVar(resourceBinding.closeTracker);
280
				// keep the tracking variable in the resourceBinding in order to prevent creating a new one while analyzing the try block
281
			} 
282
			TypeBinding type = resourceBinding.type;
255
			if (type != null && type.isValidBinding()) {
283
			if (type != null && type.isValidBinding()) {
256
				ReferenceBinding binding = (ReferenceBinding) type;
284
				ReferenceBinding binding = (ReferenceBinding) type;
257
				MethodBinding closeMethod = binding.getExactMethod(ConstantPool.Close, new TypeBinding [0], this.scope.compilationUnitScope()); // scope needs to be tighter
285
				MethodBinding closeMethod = binding.getExactMethod(ConstantPool.Close, new TypeBinding [0], this.scope.compilationUnitScope()); // scope needs to be tighter
258
				if (closeMethod != null && closeMethod.returnType.id == TypeIds.T_void) {
286
				if (closeMethod != null && closeMethod.returnType.id == TypeIds.T_void) {
259
					ReferenceBinding[] thrownExceptions = closeMethod.thrownExceptions;
287
					ReferenceBinding[] thrownExceptions = closeMethod.thrownExceptions;
260
					for (int j = 0, length = thrownExceptions.length; j < length; j++) {
288
					for (int j = 0, length = thrownExceptions.length; j < length; j++) {
261
						handlingContext.checkExceptionHandlers(thrownExceptions[j], this.resources[j], flowInfo, currentScope);
289
						handlingContext.checkExceptionHandlers(thrownExceptions[j], this.resources[i], flowInfo, currentScope, true);
262
					}
290
					}
263
				}
291
				}
264
			}
292
			}
Lines 271-277 Link Here
271
			if ((tryInfo.tagBits & FlowInfo.UNREACHABLE_OR_DEAD) != 0)
299
			if ((tryInfo.tagBits & FlowInfo.UNREACHABLE_OR_DEAD) != 0)
272
				this.bits |= ASTNode.IsTryBlockExiting;
300
				this.bits |= ASTNode.IsTryBlockExiting;
273
		}
301
		}
274
302
		if (resourcesLength > 0) {
303
			this.postTryInitStateIndex = currentScope.methodScope().recordInitializationStates(tryInfo);
304
		}
275
		// check unreachable catch blocks
305
		// check unreachable catch blocks
276
		handlingContext.complainIfUnusedExceptionHandlers(this.scope, this);
306
		handlingContext.complainIfUnusedExceptionHandlers(this.scope, this);
277
307
Lines 490-495 Link Here
490
					// inline resource closure
520
					// inline resource closure
491
					if (i > 0) {
521
					if (i > 0) {
492
						int invokeCloseStartPc = codeStream.position; // https://bugs.eclipse.org/bugs/show_bug.cgi?id=343785
522
						int invokeCloseStartPc = codeStream.position; // https://bugs.eclipse.org/bugs/show_bug.cgi?id=343785
523
						if (this.postTryInitStateIndex != -1) {
524
							/* https://bugs.eclipse.org/bugs/show_bug.cgi?id=361053, we are just past a synthetic instance of try-catch-finally.
525
							   Our initialization type state is the same as it was at the end of the just concluded try (catch rethrows)
526
							*/
527
							codeStream.removeNotDefinitelyAssignedVariables(currentScope, this.postTryInitStateIndex);
528
							codeStream.addDefinitelyAssignedVariables(currentScope, this.postTryInitStateIndex);
529
						}
493
						codeStream.load(localVariable);
530
						codeStream.load(localVariable);
494
						codeStream.ifnull(exitLabel);
531
						codeStream.ifnull(exitLabel);
495
						codeStream.load(localVariable);
532
						codeStream.load(localVariable);
Lines 876-884 Link Here
876
	if (finallyMode == FINALLY_INLINE) {
913
	if (finallyMode == FINALLY_INLINE) {
877
		if (isStackMapFrameCodeStream) {
914
		if (isStackMapFrameCodeStream) {
878
			((StackMapFrameCodeStream) codeStream).pushStateIndex(stateIndex);
915
			((StackMapFrameCodeStream) codeStream).pushStateIndex(stateIndex);
879
		}
880
		if (secretLocal != null) {
881
			codeStream.addVariable(secretLocal);
882
		}
916
		}
883
		// cannot use jsr bytecode, then simply inline the subroutine
917
		// cannot use jsr bytecode, then simply inline the subroutine
884
		// inside try block, ensure to deactivate all catch block exception handlers while inlining finally block
918
		// inside try block, ensure to deactivate all catch block exception handlers while inlining finally block
(-)a/org.eclipse.jdt.core/compiler/org/eclipse/jdt/internal/compiler/ast/TypeDeclaration.java (-7 / +22 lines)
Lines 1-5 Link Here
1
/*******************************************************************************
1
/*******************************************************************************
2
 * Copyright (c) 2000, 2011 IBM Corporation and others.
2
 * Copyright (c) 2000, 2012 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 360328 - [compiler][null] detect null problems in nested code (local class inside a loop)
10
 *******************************************************************************/
11
 *******************************************************************************/
11
package org.eclipse.jdt.internal.compiler.ast;
12
package org.eclipse.jdt.internal.compiler.ast;
12
13
Lines 493-498 Link Here
493
	return null;
494
	return null;
494
}
495
}
495
496
497
public CompilationUnitDeclaration getCompilationUnitDeclaration() {
498
	if (this.scope != null) {
499
		return this.scope.compilationUnitScope().referenceContext;
500
	}
501
	return null;
502
}
503
496
/**
504
/**
497
 * Generic bytecode generation for type
505
 * Generic bytecode generation for type
498
 */
506
 */
Lines 625-631 Link Here
625
			this.scope.problemReporter().unusedPrivateType(this);
633
			this.scope.problemReporter().unusedPrivateType(this);
626
		}
634
		}
627
	}
635
	}
628
	InitializationFlowContext initializerContext = new InitializationFlowContext(null, this, flowInfo, flowContext, this.initializerScope);
636
	// for local classes we use the flowContext as our parent, but never use an initialization context for this purpose
637
	// see Bug 360328 - [compiler][null] detect null problems in nested code (local class inside a loop)
638
	FlowContext parentContext = (flowContext instanceof InitializationFlowContext) ? null : flowContext;
639
	InitializationFlowContext initializerContext = new InitializationFlowContext(parentContext, this, flowInfo, flowContext, this.initializerScope);
640
	// no static initializer in local classes, thus no need to set parent:
629
	InitializationFlowContext staticInitializerContext = new InitializationFlowContext(null, this, flowInfo, flowContext, this.staticInitializerScope);
641
	InitializationFlowContext staticInitializerContext = new InitializationFlowContext(null, this, flowInfo, flowContext, this.staticInitializerScope);
630
	FlowInfo nonStaticFieldInfo = flowInfo.unconditionalFieldLessCopy();
642
	FlowInfo nonStaticFieldInfo = flowInfo.unconditionalFieldLessCopy();
631
	FlowInfo staticFieldInfo = flowInfo.unconditionalFieldLessCopy();
643
	FlowInfo staticFieldInfo = flowInfo.unconditionalFieldLessCopy();
Lines 684-691 Link Here
684
			if (method.ignoreFurtherInvestigation)
696
			if (method.ignoreFurtherInvestigation)
685
				continue;
697
				continue;
686
			if (method.isInitializationMethod()) {
698
			if (method.isInitializationMethod()) {
699
				// pass down the appropriate initializerContext:
687
				if (method.isStatic()) { // <clinit>
700
				if (method.isStatic()) { // <clinit>
688
					method.analyseCode(
701
					((Clinit)method).analyseCode(
689
						this.scope,
702
						this.scope,
690
						staticInitializerContext,
703
						staticInitializerContext,
691
						staticFieldInfo.unconditionalInits().discardNonFieldInitializations().addInitializationsFrom(outerInfo));
704
						staticFieldInfo.unconditionalInits().discardNonFieldInitializations().addInitializationsFrom(outerInfo));
Lines 693-699 Link Here
693
					((ConstructorDeclaration)method).analyseCode(this.scope, initializerContext, constructorInfo.copy(), flowInfo.reachMode());
706
					((ConstructorDeclaration)method).analyseCode(this.scope, initializerContext, constructorInfo.copy(), flowInfo.reachMode());
694
				}
707
				}
695
			} else { // regular method
708
			} else { // regular method
696
				method.analyseCode(this.scope, null, flowInfo.copy());
709
				// pass down the parentContext (NOT an initializer context, see above):
710
				((MethodDeclaration)method).analyseCode(this.scope, parentContext, flowInfo.copy());
697
			}
711
			}
698
		}
712
		}
699
	}
713
	}
Lines 1354-1362 Link Here
1354
			if (this.fields != null) {
1368
			if (this.fields != null) {
1355
				int length = this.fields.length;
1369
				int length = this.fields.length;
1356
				for (int i = 0; i < length; i++) {
1370
				for (int i = 0; i < length; i++) {
1357
					FieldDeclaration field;
1371
					FieldDeclaration field = this.fields[i];
1358
					if ((field = this.fields[i]).isStatic()) {
1372
					if (field.isStatic() && !field.isFinal()) {
1359
						// local type cannot have static fields
1373
						// local type cannot have static fields that are not final, https://bugs.eclipse.org/bugs/show_bug.cgi?id=244544
1360
					} else {
1374
					} else {
1361
						field.traverse(visitor, this.initializerScope);
1375
						field.traverse(visitor, this.initializerScope);
1362
					}
1376
					}
Lines 1457-1460 Link Here
1457
public boolean isSecondary() {
1471
public boolean isSecondary() {
1458
	return (this.bits & ASTNode.IsSecondaryType) != 0;
1472
	return (this.bits & ASTNode.IsSecondaryType) != 0;
1459
}
1473
}
1474
1460
}
1475
}
(-)a/org.eclipse.jdt.core/compiler/org/eclipse/jdt/internal/compiler/ast/WhileStatement.java (-2 / +4 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 113-119 Link Here
113
				currentScope.methodScope().recordInitializationStates(
115
				currentScope.methodScope().recordInitializationStates(
114
					condInfo.initsWhenTrue());
116
					condInfo.initsWhenTrue());
115
117
116
			if (this.action.complainIfUnreachable(actionInfo, currentScope, initialComplaintLevel) < Statement.COMPLAINED_UNREACHABLE) {
118
			if (this.action.complainIfUnreachable(actionInfo, currentScope, initialComplaintLevel, true) < Statement.COMPLAINED_UNREACHABLE) {
117
				actionInfo = this.action.analyseCode(currentScope, loopingContext, actionInfo);
119
				actionInfo = this.action.analyseCode(currentScope, loopingContext, actionInfo);
118
			}
120
			}
119
121
(-)a/org.eclipse.jdt.core/compiler/org/eclipse/jdt/internal/compiler/classfmt/AnnotationInfo.java (-8 lines)
Lines 303-312 Link Here
303
					currentOffset += 2;
303
					currentOffset += 2;
304
					return readTargetValue(currentOffset);
304
					return readTargetValue(currentOffset);
305
				}
305
				}
306
				if (CharOperation.equals(typeName, ConstantPool.JAVAX_ANNOTATION_PREDESTROY)) {
307
					this.standardAnnotationTagBits |= TagBits.AnnotationPreDestroy;
308
					return currentOffset;
309
				}
310
				break;
306
				break;
311
			case 32:
307
			case 32:
312
				if (CharOperation.equals(typeName, ConstantPool.JAVA_LANG_ANNOTATION_RETENTION)) {
308
				if (CharOperation.equals(typeName, ConstantPool.JAVA_LANG_ANNOTATION_RETENTION)) {
Lines 315-324 Link Here
315
				}
311
				}
316
				if (CharOperation.equals(typeName, ConstantPool.JAVA_LANG_ANNOTATION_INHERITED)) {
312
				if (CharOperation.equals(typeName, ConstantPool.JAVA_LANG_ANNOTATION_INHERITED)) {
317
					this.standardAnnotationTagBits |= TagBits.AnnotationInherited;
313
					this.standardAnnotationTagBits |= TagBits.AnnotationInherited;
318
					return currentOffset;
319
				}
320
				if (CharOperation.equals(typeName, ConstantPool.JAVAX_ANNOTATION_POSTCONSTRUCT)) {
321
					this.standardAnnotationTagBits |= TagBits.AnnotationPostConstruct;
322
					return currentOffset;
314
					return currentOffset;
323
				}
315
				}
324
				break;
316
				break;
(-)a/org.eclipse.jdt.core/compiler/org/eclipse/jdt/internal/compiler/classfmt/ClassFileConstants.java (-1 / +7 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 58-63 Link Here
58
	int MethodRefTag = 10;
58
	int MethodRefTag = 10;
59
	int InterfaceMethodRefTag = 11;
59
	int InterfaceMethodRefTag = 11;
60
	int NameAndTypeTag = 12;
60
	int NameAndTypeTag = 12;
61
	int MethodHandleTag = 15;
62
	int MethodTypeTag = 16;
63
	int InvokeDynamicTag = 18;
61
64
62
	int ConstantMethodRefFixedSize = 5;
65
	int ConstantMethodRefFixedSize = 5;
63
	int ConstantClassFixedSize = 3;
66
	int ConstantClassFixedSize = 3;
Lines 70-75 Link Here
70
	int ConstantStringFixedSize = 3;
73
	int ConstantStringFixedSize = 3;
71
	int ConstantUtf8FixedSize = 3;
74
	int ConstantUtf8FixedSize = 3;
72
	int ConstantNameAndTypeFixedSize = 5;
75
	int ConstantNameAndTypeFixedSize = 5;
76
	int ConstantMethodHandleFixedSize = 4;
77
	int ConstantMethodTypeFixedSize = 3;
78
	int ConstantInvokeDynamicFixedSize = 5;
73
79
74
	int MAJOR_VERSION_1_1 = 45;
80
	int MAJOR_VERSION_1_1 = 45;
75
	int MAJOR_VERSION_1_2 = 46;
81
	int MAJOR_VERSION_1_2 = 46;
(-)a/org.eclipse.jdt.core/compiler/org/eclipse/jdt/internal/compiler/classfmt/ClassFileReader.java (-1 / +25 lines)
Lines 1-5 Link Here
1
/*******************************************************************************
1
/*******************************************************************************
2
 * Copyright (c) 2000, 2010 IBM Corporation and others.
2
 * Copyright (c) 2000, 2011 IBM Corporation and others.
3
 * All rights reserved. This program and the accompanying materials
3
 * All rights reserved. This program and the accompanying materials
4
 * are made available under the terms of the Eclipse Public License v1.0
4
 * are made available under the terms of the Eclipse Public License v1.0
5
 * which accompanies this distribution, and is available at
5
 * which accompanies this distribution, and is available at
Lines 7-12 Link Here
7
 *
7
 *
8
 * Contributors:
8
 * Contributors:
9
 *     IBM Corporation - initial API and implementation
9
 *     IBM Corporation - initial API and implementation
10
 *     Stephan Herrmann - Contribution for bug 365992 - [builder] [null] Change of nullness for a parameter doesn't trigger a build for the files that call the method
10
 *******************************************************************************/
11
 *******************************************************************************/
11
package org.eclipse.jdt.internal.compiler.classfmt;
12
package org.eclipse.jdt.internal.compiler.classfmt;
12
13
Lines 207-212 Link Here
207
				case ClassFileConstants.NameAndTypeTag :
208
				case ClassFileConstants.NameAndTypeTag :
208
					this.constantPoolOffsets[i] = readOffset;
209
					this.constantPoolOffsets[i] = readOffset;
209
					readOffset += ClassFileConstants.ConstantNameAndTypeFixedSize;
210
					readOffset += ClassFileConstants.ConstantNameAndTypeFixedSize;
211
					break;
212
				case ClassFileConstants.MethodHandleTag :
213
					this.constantPoolOffsets[i] = readOffset;
214
					readOffset += ClassFileConstants.ConstantMethodHandleFixedSize;
215
					break;
216
				case ClassFileConstants.MethodTypeTag :
217
					this.constantPoolOffsets[i] = readOffset;
218
					readOffset += ClassFileConstants.ConstantMethodTypeFixedSize;
219
					break;
220
				case ClassFileConstants.InvokeDynamicTag :
221
					this.constantPoolOffsets[i] = readOffset;
222
					readOffset += ClassFileConstants.ConstantInvokeDynamicFixedSize;
223
					break;
210
			}
224
			}
211
		}
225
		}
212
		// Read and validate access flags
226
		// Read and validate access flags
Lines 1057-1062 Link Here
1057
		return true;
1071
		return true;
1058
	if (hasStructuralAnnotationChanges(currentMethodInfo.getAnnotations(), otherMethodInfo.getAnnotations()))
1072
	if (hasStructuralAnnotationChanges(currentMethodInfo.getAnnotations(), otherMethodInfo.getAnnotations()))
1059
		return true;
1073
		return true;
1074
	// parameter annotations:
1075
	int currentAnnotatedParamsCount = currentMethodInfo.getAnnotatedParametersCount();
1076
	int otherAnnotatedParamsCount = otherMethodInfo.getAnnotatedParametersCount();
1077
	if (currentAnnotatedParamsCount != otherAnnotatedParamsCount)
1078
		return true;
1079
	for (int i=0; i<currentAnnotatedParamsCount; i++) {
1080
		if (hasStructuralAnnotationChanges(currentMethodInfo.getParameterAnnotations(i), otherMethodInfo.getParameterAnnotations(i)))
1081
			return true;
1082
	}
1083
1060
	if (!CharOperation.equals(currentMethodInfo.getSelector(), otherMethodInfo.getSelector()))
1084
	if (!CharOperation.equals(currentMethodInfo.getSelector(), otherMethodInfo.getSelector()))
1061
		return true;
1085
		return true;
1062
	if (!CharOperation.equals(currentMethodInfo.getMethodDescriptor(), otherMethodInfo.getMethodDescriptor()))
1086
	if (!CharOperation.equals(currentMethodInfo.getMethodDescriptor(), otherMethodInfo.getMethodDescriptor()))
(-)a/org.eclipse.jdt.core/compiler/org/eclipse/jdt/internal/compiler/classfmt/MethodInfo.java (-1 / +5 lines)
Lines 1-5 Link Here
1
/*******************************************************************************
1
/*******************************************************************************
2
 * Copyright (c) 2000, 2009 IBM Corporation and others.
2
 * Copyright (c) 2000, 2011 IBM Corporation and others.
3
 * All rights reserved. This program and the accompanying materials
3
 * All rights reserved. This program and the accompanying materials
4
 * are made available under the terms of the Eclipse Public License v1.0
4
 * are made available under the terms of the Eclipse Public License v1.0
5
 * which accompanies this distribution, and is available at
5
 * which accompanies this distribution, and is available at
Lines 7-12 Link Here
7
 *
7
 *
8
 * Contributors:
8
 * Contributors:
9
 *     IBM Corporation - initial API and implementation
9
 *     IBM Corporation - initial API and implementation
10
 *     Stephan Herrmann - Contribution for bug 186342 - [compiler][null] Using annotations for null checking
10
 *******************************************************************************/
11
 *******************************************************************************/
11
package org.eclipse.jdt.internal.compiler.classfmt;
12
package org.eclipse.jdt.internal.compiler.classfmt;
12
13
Lines 270-275 Link Here
270
public IBinaryAnnotation[] getParameterAnnotations(int index) {
271
public IBinaryAnnotation[] getParameterAnnotations(int index) {
271
	return null;
272
	return null;
272
}
273
}
274
public int getAnnotatedParametersCount() {
275
	return 0;
276
}
273
/**
277
/**
274
 * Answer the name of the method.
278
 * Answer the name of the method.
275
 *
279
 *
(-)a/org.eclipse.jdt.core/compiler/org/eclipse/jdt/internal/compiler/classfmt/MethodInfoWithParameterAnnotations.java (+4 lines)
Lines 8-13 Link Here
8
 * Contributors:
8
 * Contributors:
9
 *    tyeung@bea.com  - initial API and implementation
9
 *    tyeung@bea.com  - initial API and implementation
10
 *    IBM Corporation - fix for bug 342757
10
 *    IBM Corporation - fix for bug 342757
11
 *    Stephan Herrmann - Contribution for bug 186342 - [compiler][null] Using annotations for null checking
11
 *******************************************************************************/
12
 *******************************************************************************/
12
package org.eclipse.jdt.internal.compiler.classfmt;
13
package org.eclipse.jdt.internal.compiler.classfmt;
13
14
Lines 36-41 Link Here
36
public IBinaryAnnotation[] getParameterAnnotations(int index) {
37
public IBinaryAnnotation[] getParameterAnnotations(int index) {
37
	return this.parameterAnnotations[index];
38
	return this.parameterAnnotations[index];
38
}
39
}
40
public int getAnnotatedParametersCount() {
41
	return this.parameterAnnotations == null ? 0 : this.parameterAnnotations.length;
42
}
39
protected void initialize() {
43
protected void initialize() {
40
	for (int i = 0, l = this.parameterAnnotations == null ? 0 : this.parameterAnnotations.length; i < l; i++) {
44
	for (int i = 0, l = this.parameterAnnotations == null ? 0 : this.parameterAnnotations.length; i < l; i++) {
41
		AnnotationInfo[] infos = this.parameterAnnotations[i];
45
		AnnotationInfo[] infos = this.parameterAnnotations[i];
(-)a/org.eclipse.jdt.core/compiler/org/eclipse/jdt/internal/compiler/codegen/ConstantPool.java (-3 / +1 lines)
Lines 1-5 Link Here
1
/*******************************************************************************
1
/*******************************************************************************
2
 * Copyright (c) 2000, 2011 IBM Corporation and others.
2
 * Copyright (c) 2000, 2012 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 248-255 Link Here
248
	public static final char[] JAVA_LANG_SAFEVARARGS = "Ljava/lang/SafeVarargs;".toCharArray(); //$NON-NLS-1$
248
	public static final char[] JAVA_LANG_SAFEVARARGS = "Ljava/lang/SafeVarargs;".toCharArray(); //$NON-NLS-1$
249
	// java 7 java.lang.invoke.MethodHandle.invokeExact(..)/invokeGeneric(..)
249
	// java 7 java.lang.invoke.MethodHandle.invokeExact(..)/invokeGeneric(..)
250
	public static final char[] JAVA_LANG_INVOKE_METHODHANDLE_POLYMORPHICSIGNATURE = "Ljava/lang/invoke/MethodHandle$PolymorphicSignature;".toCharArray(); //$NON-NLS-1$
250
	public static final char[] JAVA_LANG_INVOKE_METHODHANDLE_POLYMORPHICSIGNATURE = "Ljava/lang/invoke/MethodHandle$PolymorphicSignature;".toCharArray(); //$NON-NLS-1$
251
	public static final char[] JAVAX_ANNOTATION_POSTCONSTRUCT = "Ljavax/annotation/PostConstruct;".toCharArray(); //$NON-NLS-1$
252
	public static final char[] JAVAX_ANNOTATION_PREDESTROY = "Ljavax/annotation/PreDestroy;".toCharArray(); //$NON-NLS-1$
253
251
254
	public static final char[] HashCode = "hashCode".toCharArray(); //$NON-NLS-1$
252
	public static final char[] HashCode = "hashCode".toCharArray(); //$NON-NLS-1$
255
	public static final char[] HashCodeSignature = "()I".toCharArray(); //$NON-NLS-1$; 
253
	public static final char[] HashCodeSignature = "()I".toCharArray(); //$NON-NLS-1$; 
(-)a/org.eclipse.jdt.core/compiler/org/eclipse/jdt/internal/compiler/codegen/StackMapFrameCodeStream.java (-1 / +10 lines)
Lines 248-255 Link Here
248
		this.stackDepthMarkers.add(new StackDepthMarker(pc, delta, typeBinding));
248
		this.stackDepthMarkers.add(new StackDepthMarker(pc, delta, typeBinding));
249
	} else {
249
	} else {
250
		int size = this.stackDepthMarkers.size();
250
		int size = this.stackDepthMarkers.size();
251
		if (size == 0 || ((StackDepthMarker) this.stackDepthMarkers.get(size - 1)).pc != this.position) {
251
		if (size == 0) {
252
			this.stackDepthMarkers.add(new StackDepthMarker(pc, delta, typeBinding));
252
			this.stackDepthMarkers.add(new StackDepthMarker(pc, delta, typeBinding));
253
		} else {
254
			StackDepthMarker stackDepthMarker = (StackDepthMarker) this.stackDepthMarkers.get(size - 1);
255
			if (stackDepthMarker.pc != this.position) {
256
				this.stackDepthMarkers.add(new StackDepthMarker(pc, delta, typeBinding));
257
			} else {
258
				// We replace the recorded stack depth marker with a new value that contains the given typeBinding
259
				// This case can happen when multiple conditional expression are nested see bug 362591
260
				this.stackDepthMarkers.set(size - 1, new StackDepthMarker(pc, delta, typeBinding));
261
			}
253
		}
262
		}
254
	}
263
	}
255
}
264
}
(-)a/org.eclipse.jdt.core/compiler/org/eclipse/jdt/internal/compiler/env/IBinaryMethod.java (-1 / +9 lines)
Lines 1-5 Link Here
1
/*******************************************************************************
1
/*******************************************************************************
2
 * Copyright (c) 2000, 2010 IBM Corporation and others.
2
 * Copyright (c) 2000, 2011 IBM Corporation and others.
3
 * All rights reserved. This program and the accompanying materials
3
 * All rights reserved. This program and the accompanying materials
4
 * are made available under the terms of the Eclipse Public License v1.0
4
 * are made available under the terms of the Eclipse Public License v1.0
5
 * which accompanies this distribution, and is available at
5
 * which accompanies this distribution, and is available at
Lines 7-12 Link Here
7
 *
7
 *
8
 * Contributors:
8
 * Contributors:
9
 *     IBM Corporation - initial API and implementation
9
 *     IBM Corporation - initial API and implementation
10
 *     Stephan Herrmann - Contribution for bug 186342 - [compiler][null] Using annotations for null checking
10
 *******************************************************************************/
11
 *******************************************************************************/
11
package org.eclipse.jdt.internal.compiler.env;
12
package org.eclipse.jdt.internal.compiler.env;
12
13
Lines 66-71 Link Here
66
IBinaryAnnotation[] getParameterAnnotations(int index);
67
IBinaryAnnotation[] getParameterAnnotations(int index);
67
68
68
/**
69
/**
70
 * Answer the number of parameter annotations that can be retrieved
71
 * using {@link #getParameterAnnotations(int)}.
72
 * @return one beyond the highest legal argument to {@link #getParameterAnnotations(int)}.
73
 */
74
int getAnnotatedParametersCount();
75
76
/**
69
 * Answer the name of the method.
77
 * Answer the name of the method.
70
 *
78
 *
71
 * For a constructor, answer <init> & <clinit> for a clinit method.
79
 * For a constructor, answer <init> & <clinit> for a clinit method.
(-)a/org.eclipse.jdt.core/compiler/org/eclipse/jdt/internal/compiler/env/ICompilationUnit.java (-1 / +6 lines)
Lines 1-5 Link Here
1
/*******************************************************************************
1
/*******************************************************************************
2
 * Copyright (c) 2000, 2009 IBM Corporation and others.
2
 * Copyright (c) 2000, 2012 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 35-38 Link Here
35
 * For example, {java, lang}.
35
 * For example, {java, lang}.
36
 */
36
 */
37
char[][] getPackageName();
37
char[][] getPackageName();
38
/**
39
* Answer if optional problems should be ignored for this compilation unit.
40
* Implementors should return <code>false</code> if there is no preference.
41
*/
42
boolean ignoreOptionalProblems();
38
}
43
}
(-)a/org.eclipse.jdt.core/compiler/org/eclipse/jdt/internal/compiler/flow/ConditionalFlowInfo.java (+5 lines)
Lines 252-255 Link Here
252
	return (this.initsWhenTrue.isMarkedAsNullOrNonNullInAssertExpression(local)
252
	return (this.initsWhenTrue.isMarkedAsNullOrNonNullInAssertExpression(local)
253
		|| this.initsWhenFalse.isMarkedAsNullOrNonNullInAssertExpression(local));
253
		|| this.initsWhenFalse.isMarkedAsNullOrNonNullInAssertExpression(local));
254
}
254
}
255
256
public void resetAssignmentInfo(LocalVariableBinding local) {
257
	this.initsWhenTrue.resetAssignmentInfo(local);
258
	this.initsWhenFalse.resetAssignmentInfo(local);
259
}
255
}
260
}
(-)a/org.eclipse.jdt.core/compiler/org/eclipse/jdt/internal/compiler/flow/FinallyFlowContext.java (-20 / +53 lines)
Lines 1-5 Link Here
1
/*******************************************************************************
1
/*******************************************************************************
2
 * Copyright (c) 2000, 2011 IBM Corporation and others.
2
 * Copyright (c) 2000, 2012 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 - Contributions for
11
 *								bug 186342 - [compiler][null] Using annotations for null checking
12
 *								bug 365519 - editorial cleanup after bug 186342 and bug 365387
13
 *								bug 368546 - [compiler][resource] Avoid remaining false positives found when compiling the Eclipse SDK
10
 *******************************************************************************/
14
 *******************************************************************************/
11
package org.eclipse.jdt.internal.compiler.flow;
15
package org.eclipse.jdt.internal.compiler.flow;
12
16
Lines 17-22 Link Here
17
import org.eclipse.jdt.internal.compiler.lookup.FieldBinding;
21
import org.eclipse.jdt.internal.compiler.lookup.FieldBinding;
18
import org.eclipse.jdt.internal.compiler.lookup.LocalVariableBinding;
22
import org.eclipse.jdt.internal.compiler.lookup.LocalVariableBinding;
19
import org.eclipse.jdt.internal.compiler.lookup.Scope;
23
import org.eclipse.jdt.internal.compiler.lookup.Scope;
24
import org.eclipse.jdt.internal.compiler.lookup.TypeBinding;
20
import org.eclipse.jdt.internal.compiler.lookup.TypeIds;
25
import org.eclipse.jdt.internal.compiler.lookup.TypeIds;
21
import org.eclipse.jdt.internal.compiler.lookup.VariableBinding;
26
import org.eclipse.jdt.internal.compiler.lookup.VariableBinding;
22
27
Lines 30-39 Link Here
30
	VariableBinding[] finalVariables;
35
	VariableBinding[] finalVariables;
31
	int assignCount;
36
	int assignCount;
32
37
38
	// the following three arrays are in sync regarding their indices:
33
	LocalVariableBinding[] nullLocals;
39
	LocalVariableBinding[] nullLocals;
34
	Expression[] nullReferences;
40
	ASTNode[] nullReferences;	// Expressions for null checking, Statements for resource analysis
41
								// cast to Expression is safe if corresponding nullCheckType != EXIT_RESOURCE
35
	int[] nullCheckTypes;
42
	int[] nullCheckTypes;
36
	int nullCount;
43
	int nullCount;
44
	// see also the related field FlowContext#expectedTypes
37
45
38
	public FinallyFlowContext(FlowContext parent, ASTNode associatedNode) {
46
	public FinallyFlowContext(FlowContext parent, ASTNode associatedNode) {
39
		super(parent, associatedNode);
47
		super(parent, associatedNode);
Lines 60-66 Link Here
60
			}
68
			}
61
		} else {
69
		} else {
62
			// final local variable
70
			// final local variable
63
			if (flowInfo.isPotentiallyAssigned((LocalVariableBinding) variable)) {
71
			if (flowInfo.isPotentiallyAssigned((LocalVariableBinding)variable)) {
64
				complained = true;
72
				complained = true;
65
				scope.problemReporter().duplicateInitializationOfFinalLocal(
73
				scope.problemReporter().duplicateInitializationOfFinalLocal(
66
					(LocalVariableBinding) variable,
74
					(LocalVariableBinding) variable,
Lines 70-81 Link Here
70
		// any reference reported at this level is removed from the parent context
78
		// any reference reported at this level is removed from the parent context
71
		// where it could also be reported again
79
		// where it could also be reported again
72
		if (complained) {
80
		if (complained) {
73
			FlowContext currentContext = this.parent;
81
			FlowContext currentContext = this.getLocalParent();
74
			while (currentContext != null) {
82
			while (currentContext != null) {
75
				//if (currentContext.isSubRoutine()) {
83
				//if (currentContext.isSubRoutine()) {
76
				currentContext.removeFinalAssignmentIfAny(this.finalAssignments[i]);
84
				currentContext.removeFinalAssignmentIfAny(this.finalAssignments[i]);
77
				//}
85
				//}
78
				currentContext = currentContext.parent;
86
				currentContext = currentContext.getLocalParent();
79
			}
87
			}
80
		}
88
		}
81
	}
89
	}
Lines 83-95 Link Here
83
	// check inconsistent null checks
91
	// check inconsistent null checks
84
	if ((this.tagBits & FlowContext.DEFER_NULL_DIAGNOSTIC) != 0) { // within an enclosing loop, be conservative
92
	if ((this.tagBits & FlowContext.DEFER_NULL_DIAGNOSTIC) != 0) { // within an enclosing loop, be conservative
85
		for (int i = 0; i < this.nullCount; i++) {
93
		for (int i = 0; i < this.nullCount; i++) {
86
			this.parent.recordUsingNullReference(scope, this.nullLocals[i],
94
			if (this.nullCheckTypes[i] == ASSIGN_TO_NONNULL)
87
					this.nullReferences[i],	this.nullCheckTypes[i], flowInfo);
95
				this.parent.recordNullityMismatch(scope, (Expression)this.nullReferences[i],
96
						flowInfo.nullStatus(this.nullLocals[i]), this.expectedTypes[i]);
97
			else
98
				this.parent.recordUsingNullReference(scope, this.nullLocals[i],
99
						this.nullReferences[i],	this.nullCheckTypes[i], flowInfo);
100
88
		}
101
		}
89
	}
102
	}
90
	else { // no enclosing loop, be as precise as possible right now
103
	else { // no enclosing loop, be as precise as possible right now
91
		for (int i = 0; i < this.nullCount; i++) {
104
		for (int i = 0; i < this.nullCount; i++) {
92
			Expression expression = this.nullReferences[i];
105
			ASTNode location = this.nullReferences[i];
93
			// final local variable
106
			// final local variable
94
			LocalVariableBinding local = this.nullLocals[i];
107
			LocalVariableBinding local = this.nullLocals[i];
95
			switch (this.nullCheckTypes[i]) {
108
			switch (this.nullCheckTypes[i]) {
Lines 98-108 Link Here
98
					if (flowInfo.isDefinitelyNonNull(local)) {
111
					if (flowInfo.isDefinitelyNonNull(local)) {
99
						if (this.nullCheckTypes[i] == (CAN_ONLY_NULL_NON_NULL | IN_COMPARISON_NON_NULL)) {
112
						if (this.nullCheckTypes[i] == (CAN_ONLY_NULL_NON_NULL | IN_COMPARISON_NON_NULL)) {
100
							if ((this.tagBits & FlowContext.HIDE_NULL_COMPARISON_WARNING) == 0) {
113
							if ((this.tagBits & FlowContext.HIDE_NULL_COMPARISON_WARNING) == 0) {
101
								scope.problemReporter().localVariableRedundantCheckOnNonNull(local, expression);
114
								scope.problemReporter().localVariableRedundantCheckOnNonNull(local, location);
102
							}
115
							}
103
						} else {
116
						} else {
104
							if ((this.tagBits & FlowContext.HIDE_NULL_COMPARISON_WARNING) == 0) {
117
							if ((this.tagBits & FlowContext.HIDE_NULL_COMPARISON_WARNING) == 0) {
105
								scope.problemReporter().localVariableNonNullComparedToNull(local, expression);
118
								scope.problemReporter().localVariableNonNullComparedToNull(local, location);
106
							}
119
							}
107
						}
120
						}
108
						continue;
121
						continue;
Lines 112-117 Link Here
112
				case CAN_ONLY_NULL | IN_COMPARISON_NON_NULL:
125
				case CAN_ONLY_NULL | IN_COMPARISON_NON_NULL:
113
				case CAN_ONLY_NULL | IN_ASSIGNMENT:
126
				case CAN_ONLY_NULL | IN_ASSIGNMENT:
114
				case CAN_ONLY_NULL | IN_INSTANCEOF:
127
				case CAN_ONLY_NULL | IN_INSTANCEOF:
128
					Expression expression = (Expression) location;
115
					if (flowInfo.isDefinitelyNull(local)) {
129
					if (flowInfo.isDefinitelyNull(local)) {
116
						switch(this.nullCheckTypes[i] & CONTEXT_MASK) {
130
						switch(this.nullCheckTypes[i] & CONTEXT_MASK) {
117
							case FlowContext.IN_COMPARISON_NULL:
131
							case FlowContext.IN_COMPARISON_NULL:
Lines 160-170 Link Here
160
					break;
174
					break;
161
				case MAY_NULL:
175
				case MAY_NULL:
162
					if (flowInfo.isDefinitelyNull(local)) {
176
					if (flowInfo.isDefinitelyNull(local)) {
163
						scope.problemReporter().localVariableNullReference(local, expression);
177
						scope.problemReporter().localVariableNullReference(local, location);
164
						continue;
178
						continue;
165
					}
179
					}
166
					if (flowInfo.isPotentiallyNull(local)) {
180
					if (flowInfo.isPotentiallyNull(local)) {
167
						scope.problemReporter().localVariablePotentialNullReference(local, expression);
181
						scope.problemReporter().localVariablePotentialNullReference(local, location);
182
					}
183
					break;
184
				case ASSIGN_TO_NONNULL:
185
					int nullStatus = flowInfo.nullStatus(local);
186
					if (nullStatus != FlowInfo.NON_NULL) {
187
						char[][] annotationName = scope.environment().getNonNullAnnotationName();
188
						scope.problemReporter().nullityMismatch((Expression) location, this.expectedTypes[i], nullStatus, annotationName);
168
					}
189
					}
169
					break;
190
					break;
170
				default:
191
				default:
Lines 213-219 Link Here
213
	}
234
	}
214
235
215
	public void recordUsingNullReference(Scope scope, LocalVariableBinding local,
236
	public void recordUsingNullReference(Scope scope, LocalVariableBinding local,
216
			Expression reference, int checkType, FlowInfo flowInfo) {
237
			ASTNode location, int checkType, FlowInfo flowInfo) {
217
		if ((flowInfo.tagBits & FlowInfo.UNREACHABLE) == 0 && !flowInfo.isDefinitelyUnknown(local))	{
238
		if ((flowInfo.tagBits & FlowInfo.UNREACHABLE) == 0 && !flowInfo.isDefinitelyUnknown(local))	{
218
			if ((this.tagBits & FlowContext.DEFER_NULL_DIAGNOSTIC) != 0) { // within an enclosing loop, be conservative
239
			if ((this.tagBits & FlowContext.DEFER_NULL_DIAGNOSTIC) != 0) { // within an enclosing loop, be conservative
219
				switch (checkType) {
240
				switch (checkType) {
Lines 223-228 Link Here
223
					case CAN_ONLY_NULL | IN_COMPARISON_NON_NULL:
244
					case CAN_ONLY_NULL | IN_COMPARISON_NON_NULL:
224
					case CAN_ONLY_NULL | IN_ASSIGNMENT:
245
					case CAN_ONLY_NULL | IN_ASSIGNMENT:
225
					case CAN_ONLY_NULL | IN_INSTANCEOF:
246
					case CAN_ONLY_NULL | IN_INSTANCEOF:
247
						Expression reference = (Expression) location;
226
						if (flowInfo.cannotBeNull(local)) {
248
						if (flowInfo.cannotBeNull(local)) {
227
							if (checkType == (CAN_ONLY_NULL_NON_NULL | IN_COMPARISON_NON_NULL)) {
249
							if (checkType == (CAN_ONLY_NULL_NON_NULL | IN_COMPARISON_NON_NULL)) {
228
								if ((this.tagBits & FlowContext.HIDE_NULL_COMPARISON_WARNING) == 0) {
250
								if ((this.tagBits & FlowContext.HIDE_NULL_COMPARISON_WARNING) == 0) {
Lines 296-302 Link Here
296
							return;
318
							return;
297
						}
319
						}
298
						if (flowInfo.canOnlyBeNull(local)) {
320
						if (flowInfo.canOnlyBeNull(local)) {
299
							scope.problemReporter().localVariableNullReference(local, reference);
321
							scope.problemReporter().localVariableNullReference(local, location);
300
							return;
322
							return;
301
						}
323
						}
302
						break;
324
						break;
Lines 311-324 Link Here
311
						if (flowInfo.isDefinitelyNonNull(local)) {
333
						if (flowInfo.isDefinitelyNonNull(local)) {
312
							if (checkType == (CAN_ONLY_NULL_NON_NULL | IN_COMPARISON_NON_NULL)) {
334
							if (checkType == (CAN_ONLY_NULL_NON_NULL | IN_COMPARISON_NON_NULL)) {
313
								if ((this.tagBits & FlowContext.HIDE_NULL_COMPARISON_WARNING) == 0) {
335
								if ((this.tagBits & FlowContext.HIDE_NULL_COMPARISON_WARNING) == 0) {
314
									scope.problemReporter().localVariableRedundantCheckOnNonNull(local, reference);
336
									scope.problemReporter().localVariableRedundantCheckOnNonNull(local, location);
315
								}
337
								}
316
								if (!flowInfo.isMarkedAsNullOrNonNullInAssertExpression(local)) {
338
								if (!flowInfo.isMarkedAsNullOrNonNullInAssertExpression(local)) {
317
									flowInfo.initsWhenFalse().setReachMode(FlowInfo.UNREACHABLE_BY_NULLANALYSIS);
339
									flowInfo.initsWhenFalse().setReachMode(FlowInfo.UNREACHABLE_BY_NULLANALYSIS);
318
								}
340
								}
319
							} else {
341
							} else {
320
								if ((this.tagBits & FlowContext.HIDE_NULL_COMPARISON_WARNING) == 0) {
342
								if ((this.tagBits & FlowContext.HIDE_NULL_COMPARISON_WARNING) == 0) {
321
									scope.problemReporter().localVariableNonNullComparedToNull(local, reference);
343
									scope.problemReporter().localVariableNonNullComparedToNull(local, location);
322
								}
344
								}
323
								if (!flowInfo.isMarkedAsNullOrNonNullInAssertExpression(local)) {
345
								if (!flowInfo.isMarkedAsNullOrNonNullInAssertExpression(local)) {
324
									flowInfo.initsWhenTrue().setReachMode(FlowInfo.UNREACHABLE_BY_NULLANALYSIS);
346
									flowInfo.initsWhenTrue().setReachMode(FlowInfo.UNREACHABLE_BY_NULLANALYSIS);
Lines 331-336 Link Here
331
					case CAN_ONLY_NULL | IN_COMPARISON_NON_NULL:
353
					case CAN_ONLY_NULL | IN_COMPARISON_NON_NULL:
332
					case CAN_ONLY_NULL | IN_ASSIGNMENT:
354
					case CAN_ONLY_NULL | IN_ASSIGNMENT:
333
					case CAN_ONLY_NULL | IN_INSTANCEOF:
355
					case CAN_ONLY_NULL | IN_INSTANCEOF:
356
						Expression reference = (Expression) location;
334
						if (flowInfo.isDefinitelyNull(local)) {
357
						if (flowInfo.isDefinitelyNull(local)) {
335
							switch(checkType & CONTEXT_MASK) {
358
							switch(checkType & CONTEXT_MASK) {
336
								case FlowContext.IN_COMPARISON_NULL:
359
								case FlowContext.IN_COMPARISON_NULL:
Lines 383-393 Link Here
383
						break;
406
						break;
384
					case MAY_NULL :
407
					case MAY_NULL :
385
						if (flowInfo.isDefinitelyNull(local)) {
408
						if (flowInfo.isDefinitelyNull(local)) {
386
							scope.problemReporter().localVariableNullReference(local, reference);
409
							scope.problemReporter().localVariableNullReference(local, location);
387
							return;
410
							return;
388
						}
411
						}
389
						if (flowInfo.isPotentiallyNull(local)) {
412
						if (flowInfo.isPotentiallyNull(local)) {
390
							scope.problemReporter().localVariablePotentialNullReference(local, reference);
413
							scope.problemReporter().localVariablePotentialNullReference(local, location);
391
							return;
414
							return;
392
						}
415
						}
393
						if (flowInfo.isDefinitelyNonNull(local)) {
416
						if (flowInfo.isDefinitelyNonNull(local)) {
Lines 403-409 Link Here
403
			if(((this.tagBits & FlowContext.HIDE_NULL_COMPARISON_WARNING) == 0) || checkType == MAY_NULL
426
			if(((this.tagBits & FlowContext.HIDE_NULL_COMPARISON_WARNING) == 0) || checkType == MAY_NULL
404
					|| (checkType & CONTEXT_MASK) == FlowContext.IN_ASSIGNMENT
427
					|| (checkType & CONTEXT_MASK) == FlowContext.IN_ASSIGNMENT
405
					|| (checkType & CONTEXT_MASK) == FlowContext.IN_INSTANCEOF) {
428
					|| (checkType & CONTEXT_MASK) == FlowContext.IN_INSTANCEOF) {
406
				recordNullReference(local, reference, checkType);
429
				recordNullReference(local, location, checkType);
407
			}
430
			}
408
			// prepare to re-check with try/catch flow info
431
			// prepare to re-check with try/catch flow info
409
		}
432
		}
Lines 420-426 Link Here
420
	}
443
	}
421
444
422
protected void recordNullReference(LocalVariableBinding local,
445
protected void recordNullReference(LocalVariableBinding local,
423
	Expression expression, int status) {
446
	ASTNode expression, int status) {
424
	if (this.nullCount == 0) {
447
	if (this.nullCount == 0) {
425
		this.nullLocals = new LocalVariableBinding[5];
448
		this.nullLocals = new LocalVariableBinding[5];
426
		this.nullReferences = new Expression[5];
449
		this.nullReferences = new Expression[5];
Lines 442-445 Link Here
442
	this.nullReferences[this.nullCount] = expression;
465
	this.nullReferences[this.nullCount] = expression;
443
	this.nullCheckTypes[this.nullCount++] = status;
466
	this.nullCheckTypes[this.nullCount++] = status;
444
}
467
}
468
protected boolean internalRecordNullityMismatch(Expression expression, int nullStatus, TypeBinding expectedType, int checkType) {
469
	// cf. decision structure inside FinallyFlowContext.recordUsingNullReference(..)
470
	if (nullStatus == FlowInfo.UNKNOWN ||
471
			((this.tagBits & FlowContext.DEFER_NULL_DIAGNOSTIC) != 0 && nullStatus != FlowInfo.NULL)) {
472
		recordExpectedType(expectedType, this.nullCount);
473
		recordNullReference(expression.localVariableBinding(), expression, checkType);
474
		return true;
475
	}
476
	return false;
477
}
445
}
478
}
(-)a/org.eclipse.jdt.core/compiler/org/eclipse/jdt/internal/compiler/flow/FlowContext.java (-26 / +112 lines)
Lines 1-20 Link Here
1
/*******************************************************************************
1
/*******************************************************************************
2
 * Copyright (c) 2000, 2011 IBM Corporation and others.
2
 * Copyright (c) 2000, 2012 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
6
 * http://www.eclipse.org/legal/epl-v10.html
6
 * http://www.eclipse.org/legal/epl-v10.html
7
 * 
7
 *
8
 * Contributors:
8
 * Contributors:
9
 *     IBM Corporation - initial API and implementation
9
 *     IBM Corporation - initial API and implementation
10
 *     Stephan Herrmann - Contributions for
11
 *     							bug 358827 - [1.7] exception analysis for t-w-r spoils null analysis
12
 *								bug 186342 - [compiler][null] Using annotations for null checking
13
 *								bug 368546 - [compiler][resource] Avoid remaining false positives found when compiling the Eclipse SDK
10
 *******************************************************************************/
14
 *******************************************************************************/
11
package org.eclipse.jdt.internal.compiler.flow;
15
package org.eclipse.jdt.internal.compiler.flow;
12
16
13
import java.util.ArrayList;
17
import java.util.ArrayList;
18
14
import org.eclipse.jdt.core.compiler.CharOperation;
19
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;
20
import org.eclipse.jdt.internal.compiler.ast.ASTNode;
21
import org.eclipse.jdt.internal.compiler.ast.AbstractMethodDeclaration;
17
import org.eclipse.jdt.internal.compiler.ast.Expression;
22
import org.eclipse.jdt.internal.compiler.ast.Expression;
23
import org.eclipse.jdt.internal.compiler.ast.FakedTrackingVariable;
18
import org.eclipse.jdt.internal.compiler.ast.LabeledStatement;
24
import org.eclipse.jdt.internal.compiler.ast.LabeledStatement;
19
import org.eclipse.jdt.internal.compiler.ast.Reference;
25
import org.eclipse.jdt.internal.compiler.ast.Reference;
20
import org.eclipse.jdt.internal.compiler.ast.SingleNameReference;
26
import org.eclipse.jdt.internal.compiler.ast.SingleNameReference;
Lines 50-55 Link Here
50
		// any null related operation happening within the try block
56
		// any null related operation happening within the try block
51
57
52
	public int tagBits;
58
	public int tagBits;
59
60
	// array to store the expected type from the potential error location (for display in error messages):
61
	public TypeBinding[] expectedTypes = null;
62
53
	public static final int DEFER_NULL_DIAGNOSTIC = 0x1;
63
	public static final int DEFER_NULL_DIAGNOSTIC = 0x1;
54
	public static final int PREEMPT_NULL_DIAGNOSTIC = 0x2;
64
	public static final int PREEMPT_NULL_DIAGNOSTIC = 0x2;
55
	/**
65
	/**
Lines 64-69 Link Here
64
public static final int CAN_ONLY_NON_NULL = 0x0002;
74
public static final int CAN_ONLY_NON_NULL = 0x0002;
65
//check against non null, with definite values -- comparisons
75
//check against non null, with definite values -- comparisons
66
public static final int MAY_NULL = 0x0003;
76
public static final int MAY_NULL = 0x0003;
77
//check binding a value to a @NonNull variable 
78
public final static int ASSIGN_TO_NONNULL = 0x0080;
79
//check against unclosed resource at early exit:
80
public static final int EXIT_RESOURCE = 0x0800;
67
// check against null, with potential values -- NPE guard
81
// check against null, with potential values -- NPE guard
68
public static final int CHECK_MASK = 0x00FF;
82
public static final int CHECK_MASK = 0x00FF;
69
public static final int IN_COMPARISON_NULL = 0x0100;
83
public static final int IN_COMPARISON_NULL = 0x0100;
Lines 197-210 Link Here
197
211
198
		traversedContext.recordReturnFrom(flowInfo.unconditionalInits());
212
		traversedContext.recordReturnFrom(flowInfo.unconditionalInits());
199
213
200
		if (traversedContext instanceof InsideSubRoutineFlowContext) {
214
		if (!isExceptionOnAutoClose) {
201
			ASTNode node = traversedContext.associatedNode;
215
			if (traversedContext instanceof InsideSubRoutineFlowContext) {
202
			if (node instanceof TryStatement) {
216
				ASTNode node = traversedContext.associatedNode;
203
				TryStatement tryStatement = (TryStatement) node;
217
				if (node instanceof TryStatement) {
204
				flowInfo.addInitializationsFrom(tryStatement.subRoutineInits); // collect inits
218
					TryStatement tryStatement = (TryStatement) node;
219
					flowInfo.addInitializationsFrom(tryStatement.subRoutineInits); // collect inits
220
				}
205
			}
221
			}
206
		}
222
		}
207
		traversedContext = traversedContext.parent;
223
		traversedContext = traversedContext.getLocalParent();
208
	}
224
	}
209
	// if reaches this point, then there are some remaining unhandled exception types.
225
	// if reaches this point, then there are some remaining unhandled exception types.
210
	if (isExceptionOnAutoClose) {
226
	if (isExceptionOnAutoClose) {
Lines 350-356 Link Here
350
				flowInfo.addInitializationsFrom(tryStatement.subRoutineInits); // collect inits
366
				flowInfo.addInitializationsFrom(tryStatement.subRoutineInits); // collect inits
351
			}
367
			}
352
		}
368
		}
353
		traversedContext = traversedContext.parent;
369
		traversedContext = traversedContext.getLocalParent();
354
	}
370
	}
355
	// if reaches this point, then there are some remaining unhandled exception types.
371
	// if reaches this point, then there are some remaining unhandled exception types.
356
	nextReport: for (int i = 0; i < raisedCount; i++) {
372
	nextReport: for (int i = 0; i < raisedCount; i++) {
Lines 382-390 Link Here
382
			current = initializationContext.initializationParent;
398
			current = initializationContext.initializationParent;
383
		} else if (current instanceof ExceptionHandlingFlowContext) {
399
		} else if (current instanceof ExceptionHandlingFlowContext) {
384
			ExceptionHandlingFlowContext exceptionContext = (ExceptionHandlingFlowContext) current;
400
			ExceptionHandlingFlowContext exceptionContext = (ExceptionHandlingFlowContext) current;
385
			current = exceptionContext.initializationParent == null ? exceptionContext.parent : exceptionContext.initializationParent;
401
			current = exceptionContext.initializationParent == null ? exceptionContext.getLocalParent() : exceptionContext.initializationParent;
386
		} else {
402
		} else {
387
			current = current.parent;
403
			current = current.getLocalParent();
388
		}
404
		}
389
	} while (current != null);
405
	} while (current != null);
390
	// not found
406
	// not found
Lines 408-414 Link Here
408
				return current;
424
				return current;
409
			return lastNonReturningSubRoutine;
425
			return lastNonReturningSubRoutine;
410
		}
426
		}
411
		current = current.parent;
427
		current = current.getLocalParent();
412
	}
428
	}
413
	// not found
429
	// not found
414
	return null;
430
	return null;
Lines 445-451 Link Here
445
			// label is found, but not a continuable location
461
			// label is found, but not a continuable location
446
			return FlowContext.NotContinuableContext;
462
			return FlowContext.NotContinuableContext;
447
		}
463
		}
448
		current = current.parent;
464
		current = current.getLocalParent();
449
	}
465
	}
450
	// not found
466
	// not found
451
	return null;
467
	return null;
Lines 464-470 Link Here
464
			if (lastNonReturningSubRoutine == null) return current;
480
			if (lastNonReturningSubRoutine == null) return current;
465
			return lastNonReturningSubRoutine;
481
			return lastNonReturningSubRoutine;
466
		}
482
		}
467
		current = current.parent;
483
		current = current.getLocalParent();
468
	}
484
	}
469
	// not found
485
	// not found
470
	return null;
486
	return null;
Lines 484-493 Link Here
484
				return current;
500
				return current;
485
			return lastNonReturningSubRoutine;
501
			return lastNonReturningSubRoutine;
486
		}
502
		}
487
		current = current.parent;
503
		current = current.getLocalParent();
488
	}
504
	}
489
	// not found
505
	// not found
490
	return null;
506
	return null;
507
}
508
509
/** 
510
 * Answer the parent flow context but be careful not to cross the boundary of a nested type,
511
 * or null if no such parent exists. 
512
 */
513
public FlowContext getLocalParent() {
514
	if (this.associatedNode instanceof AbstractMethodDeclaration || this.associatedNode instanceof TypeDeclaration)
515
		return null;
516
	return this.parent;
491
}
517
}
492
518
493
public String individualToString() {
519
public String individualToString() {
Lines 534-539 Link Here
534
	// default implementation: do nothing
560
	// default implementation: do nothing
535
}
561
}
536
562
563
/** 
564
 * Record that we found an early exit from a method while a resource is in scope.
565
 * @param scope enclosing scope
566
 * @param flowInfo flowInfo at the point of the early exit
567
 * @param trackingVar representation of the resource
568
 * @param reference the return or throw statement marking the early exit
569
 * @return true if the situation has been handled by this flow context.
570
 */
571
public boolean recordExitAgainstResource(BlockScope scope, FlowInfo flowInfo, FakedTrackingVariable trackingVar, ASTNode reference) {
572
	return false; // not handled
573
}
574
575
protected void recordExpectedType(TypeBinding expectedType, int nullCount) {
576
	if (nullCount == 0) {
577
		this.expectedTypes = new TypeBinding[5];
578
	} else if (this.expectedTypes == null) {
579
		int size = 5;
580
		while (size <= nullCount) size *= 2;
581
		this.expectedTypes = new TypeBinding[size];
582
	}
583
	else if (nullCount >= this.expectedTypes.length) {
584
		int oldLen = this.expectedTypes.length;
585
		System.arraycopy(this.expectedTypes, 0,
586
			this.expectedTypes = new TypeBinding[nullCount * 2], 0, oldLen);
587
	}
588
	this.expectedTypes[nullCount] = expectedType;
589
}
590
537
protected boolean recordFinalAssignment(VariableBinding variable, Reference finalReference) {
591
protected boolean recordFinalAssignment(VariableBinding variable, Reference finalReference) {
538
	return true; // keep going
592
	return true; // keep going
539
}
593
}
Lines 542-548 Link Here
542
 * Record a null reference for use by deferred checks. Only looping or
596
 * Record a null reference for use by deferred checks. Only looping or
543
 * finally contexts really record that information.
597
 * finally contexts really record that information.
544
 * @param local the local variable involved in the check
598
 * @param local the local variable involved in the check
545
 * @param expression the expression within which local lays
599
 * @param location the location triggering the analysis, for normal null dereference
600
 *      this is an expression resolving to 'local', for resource leaks it is an
601
 *      early exit statement.
546
 * @param status the status against which the check must be performed; one of
602
 * @param status the status against which the check must be performed; one of
547
 * 		{@link #CAN_ONLY_NULL CAN_ONLY_NULL}, {@link #CAN_ONLY_NULL_NON_NULL
603
 * 		{@link #CAN_ONLY_NULL CAN_ONLY_NULL}, {@link #CAN_ONLY_NULL_NON_NULL
548
 * 		CAN_ONLY_NULL_NON_NULL}, {@link #MAY_NULL MAY_NULL},
604
 * 		CAN_ONLY_NULL_NON_NULL}, {@link #MAY_NULL MAY_NULL},
Lines 551-557 Link Here
551
 *      {@link #IN_COMPARISON_NON_NULL}, {@link #IN_ASSIGNMENT} or {@link #IN_INSTANCEOF})
607
 *      {@link #IN_COMPARISON_NON_NULL}, {@link #IN_ASSIGNMENT} or {@link #IN_INSTANCEOF})
552
 */
608
 */
553
protected void recordNullReference(LocalVariableBinding local,
609
protected void recordNullReference(LocalVariableBinding local,
554
	Expression expression, int status) {
610
	ASTNode location, int status) {
555
	// default implementation: do nothing
611
	// default implementation: do nothing
556
}
612
}
557
613
Lines 567-573 Link Here
567
		if (!context.recordFinalAssignment(variable, finalReference)) {
623
		if (!context.recordFinalAssignment(variable, finalReference)) {
568
			break; // no need to keep going
624
			break; // no need to keep going
569
		}
625
		}
570
		context = context.parent;
626
		context = context.getLocalParent();
571
	}
627
	}
572
	}
628
	}
573
}
629
}
Lines 582-588 Link Here
582
 * context).
638
 * context).
583
 * @param scope the scope into which the check is performed
639
 * @param scope the scope into which the check is performed
584
 * @param local the local variable involved in the check
640
 * @param local the local variable involved in the check
585
 * @param reference the expression within which local lies
641
 * @param location the location triggering the analysis, for normal null dereference
642
 *      this is an expression resolving to 'local', for resource leaks it is an
643
 *      early exit statement.
586
 * @param checkType the status against which the check must be performed; one
644
 * @param checkType the status against which the check must be performed; one
587
 * 		of {@link #CAN_ONLY_NULL CAN_ONLY_NULL}, {@link #CAN_ONLY_NULL_NON_NULL
645
 * 		of {@link #CAN_ONLY_NULL CAN_ONLY_NULL}, {@link #CAN_ONLY_NULL_NON_NULL
588
 * 		CAN_ONLY_NULL_NON_NULL}, {@link #MAY_NULL MAY_NULL}, potentially
646
 * 		CAN_ONLY_NULL_NON_NULL}, {@link #MAY_NULL MAY_NULL}, potentially
Lines 594-600 Link Here
594
 * 		code that follows the current point)
652
 * 		code that follows the current point)
595
 */
653
 */
596
public void recordUsingNullReference(Scope scope, LocalVariableBinding local,
654
public void recordUsingNullReference(Scope scope, LocalVariableBinding local,
597
		Expression reference, int checkType, FlowInfo flowInfo) {
655
		ASTNode location, int checkType, FlowInfo flowInfo) {
598
	if ((flowInfo.tagBits & FlowInfo.UNREACHABLE) != 0 ||
656
	if ((flowInfo.tagBits & FlowInfo.UNREACHABLE) != 0 ||
599
			flowInfo.isDefinitelyUnknown(local)) {
657
			flowInfo.isDefinitelyUnknown(local)) {
600
		return;
658
		return;
Lines 605-618 Link Here
605
			if (flowInfo.isDefinitelyNonNull(local)) {
663
			if (flowInfo.isDefinitelyNonNull(local)) {
606
				if (checkType == (CAN_ONLY_NULL_NON_NULL | IN_COMPARISON_NON_NULL)) {
664
				if (checkType == (CAN_ONLY_NULL_NON_NULL | IN_COMPARISON_NON_NULL)) {
607
					if ((this.tagBits & FlowContext.HIDE_NULL_COMPARISON_WARNING) == 0) {
665
					if ((this.tagBits & FlowContext.HIDE_NULL_COMPARISON_WARNING) == 0) {
608
						scope.problemReporter().localVariableRedundantCheckOnNonNull(local, reference);
666
						scope.problemReporter().localVariableRedundantCheckOnNonNull(local, location);
609
					}
667
					}
610
					if (!flowInfo.isMarkedAsNullOrNonNullInAssertExpression(local)) {
668
					if (!flowInfo.isMarkedAsNullOrNonNullInAssertExpression(local)) {
611
						flowInfo.initsWhenFalse().setReachMode(FlowInfo.UNREACHABLE_BY_NULLANALYSIS);
669
						flowInfo.initsWhenFalse().setReachMode(FlowInfo.UNREACHABLE_BY_NULLANALYSIS);
612
					}
670
					}
613
				} else {
671
				} else {
614
					if ((this.tagBits & FlowContext.HIDE_NULL_COMPARISON_WARNING) == 0) {
672
					if ((this.tagBits & FlowContext.HIDE_NULL_COMPARISON_WARNING) == 0) {
615
						scope.problemReporter().localVariableNonNullComparedToNull(local, reference);
673
						scope.problemReporter().localVariableNonNullComparedToNull(local, location);
616
					}
674
					}
617
					if (!flowInfo.isMarkedAsNullOrNonNullInAssertExpression(local)) {
675
					if (!flowInfo.isMarkedAsNullOrNonNullInAssertExpression(local)) {
618
						flowInfo.initsWhenTrue().setReachMode(FlowInfo.UNREACHABLE_BY_NULLANALYSIS);
676
						flowInfo.initsWhenTrue().setReachMode(FlowInfo.UNREACHABLE_BY_NULLANALYSIS);
Lines 628-633 Link Here
628
		case CAN_ONLY_NULL | IN_COMPARISON_NON_NULL:
686
		case CAN_ONLY_NULL | IN_COMPARISON_NON_NULL:
629
		case CAN_ONLY_NULL | IN_ASSIGNMENT:
687
		case CAN_ONLY_NULL | IN_ASSIGNMENT:
630
		case CAN_ONLY_NULL | IN_INSTANCEOF:
688
		case CAN_ONLY_NULL | IN_INSTANCEOF:
689
			Expression reference = (Expression)location;
631
			if (flowInfo.isDefinitelyNull(local)) {
690
			if (flowInfo.isDefinitelyNull(local)) {
632
				switch(checkType & CONTEXT_MASK) {
691
				switch(checkType & CONTEXT_MASK) {
633
					case FlowContext.IN_COMPARISON_NULL:
692
					case FlowContext.IN_COMPARISON_NULL:
Lines 682-692 Link Here
682
			break;
741
			break;
683
		case MAY_NULL :
742
		case MAY_NULL :
684
			if (flowInfo.isDefinitelyNull(local)) {
743
			if (flowInfo.isDefinitelyNull(local)) {
685
				scope.problemReporter().localVariableNullReference(local, reference);
744
				scope.problemReporter().localVariableNullReference(local, location);
686
				return;
745
				return;
687
			}
746
			}
688
			if (flowInfo.isPotentiallyNull(local)) {
747
			if (flowInfo.isPotentiallyNull(local)) {
689
				scope.problemReporter().localVariablePotentialNullReference(local, reference);
748
				scope.problemReporter().localVariablePotentialNullReference(local, location);
690
				return;
749
				return;
691
			}
750
			}
692
			break;
751
			break;
Lines 694-700 Link Here
694
			// never happens
753
			// never happens
695
	}
754
	}
696
	if (this.parent != null) {
755
	if (this.parent != null) {
697
		this.parent.recordUsingNullReference(scope, local, reference, checkType,
756
		this.parent.recordUsingNullReference(scope, local, location, checkType,
698
				flowInfo);
757
				flowInfo);
699
	}
758
	}
700
}
759
}
Lines 732-735 Link Here
732
	buffer.append(individualToString()).append('\n');
791
	buffer.append(individualToString()).append('\n');
733
	return buffer.toString();
792
	return buffer.toString();
734
}
793
}
794
795
/**
796
 * Record that a nullity mismatch was detected against an annotated type reference.
797
 * @param currentScope scope for error reporting
798
 * @param expression the expression violating the specification
799
 * @param nullStatus the null status of expression at the current location
800
 * @param expectedType the declared type of the spec'ed variable, for error reporting.
801
 */
802
public void recordNullityMismatch(BlockScope currentScope, Expression expression, int nullStatus, TypeBinding expectedType) {
803
	if (expression.localVariableBinding() != null) { // flowContext cannot yet handle non-localvar expressions (e.g., fields)
804
		// find the inner-most flowContext that might need deferred handling:
805
		FlowContext currentContext = this;
806
		while (currentContext != null) {
807
			// some flow contexts implement deferred checking, should we participate in that?
808
			if (currentContext.internalRecordNullityMismatch(expression, nullStatus, expectedType, ASSIGN_TO_NONNULL))
809
				return;
810
			currentContext = currentContext.parent;
811
		}
812
	}
813
	// no reason to defer, so report now:
814
	char[][] annotationName = currentScope.environment().getNonNullAnnotationName();
815
	currentScope.problemReporter().nullityMismatch(expression, expectedType, nullStatus, annotationName);
816
}
817
protected boolean internalRecordNullityMismatch(Expression expression, int nullStatus, TypeBinding expectedType, int checkType) {
818
	// nop, to be overridden in subclasses
819
	return false; // not recorded
820
}
735
}
821
}
(-)a/org.eclipse.jdt.core/compiler/org/eclipse/jdt/internal/compiler/flow/FlowInfo.java (-5 / +42 lines)
Lines 405-416 Link Here
405
public static UnconditionalFlowInfo mergedOptimizedBranchesIfElse(
405
public static UnconditionalFlowInfo mergedOptimizedBranchesIfElse(
406
		FlowInfo initsWhenTrue, boolean isOptimizedTrue,
406
		FlowInfo initsWhenTrue, boolean isOptimizedTrue,
407
		FlowInfo initsWhenFalse, boolean isOptimizedFalse,
407
		FlowInfo initsWhenFalse, boolean isOptimizedFalse,
408
		boolean allowFakeDeadBranch, FlowInfo flowInfo, IfStatement ifStatement) {
408
		boolean allowFakeDeadBranch, FlowInfo flowInfo, IfStatement ifStatement,
409
		boolean reportDeadCodeInKnownPattern) {
409
	UnconditionalFlowInfo mergedInfo;
410
	UnconditionalFlowInfo mergedInfo;
410
	if (isOptimizedTrue){
411
	if (isOptimizedTrue){
411
		if (initsWhenTrue == FlowInfo.DEAD_END && allowFakeDeadBranch) {
412
		if (initsWhenTrue == FlowInfo.DEAD_END && allowFakeDeadBranch) {
412
			mergedInfo = initsWhenFalse.setReachMode(FlowInfo.UNREACHABLE_OR_DEAD).
413
			if (!reportDeadCodeInKnownPattern) {
413
				unconditionalInits();
414
				// https://bugs.eclipse.org/bugs/show_bug.cgi?id=256796
415
				// do not report code even after if-else as dead as a consequence of analysis done in known dead code pattern
416
				// when the CompilerOptions$reportDeadCodeInTrivialIfStatement option is disabled
417
				if (ifStatement.elseStatement == null) {
418
					mergedInfo = flowInfo.unconditionalInits();
419
				} else {
420
					mergedInfo = initsWhenFalse.unconditionalInits();
421
					if (initsWhenFalse != FlowInfo.DEAD_END) {
422
						// let the definitely true status of known dead code pattern not affect the reachability
423
						mergedInfo.setReachMode(flowInfo.reachMode());
424
					}
425
				}
426
			} else {
427
				mergedInfo = initsWhenFalse.setReachMode(FlowInfo.UNREACHABLE_OR_DEAD).
428
					unconditionalInits();
429
			}
414
		}
430
		}
415
		else {
431
		else {
416
			mergedInfo =
432
			mergedInfo =
Lines 421-428 Link Here
421
	}
437
	}
422
	else if (isOptimizedFalse) {
438
	else if (isOptimizedFalse) {
423
		if (initsWhenFalse == FlowInfo.DEAD_END && allowFakeDeadBranch) {
439
		if (initsWhenFalse == FlowInfo.DEAD_END && allowFakeDeadBranch) {
424
			mergedInfo = initsWhenTrue.setReachMode(FlowInfo.UNREACHABLE_OR_DEAD).
440
			if (!reportDeadCodeInKnownPattern) {
425
				unconditionalInits();
441
				// https://bugs.eclipse.org/bugs/show_bug.cgi?id=256796
442
				// do not report code even after if-else as dead as a consequence of analysis done in known dead code pattern
443
				// when the CompilerOptions$reportDeadCodeInTrivialIfStatement option is disabled
444
				if (ifStatement.thenStatement == null) {
445
					mergedInfo = flowInfo.unconditionalInits();
446
				} else {
447
					mergedInfo = initsWhenTrue.unconditionalInits();
448
					if (initsWhenTrue != FlowInfo.DEAD_END) {
449
						// let the definitely false status of known dead code pattern not affect the reachability
450
						mergedInfo.setReachMode(flowInfo.reachMode());
451
					}
452
				}
453
			} else {
454
				mergedInfo = initsWhenTrue.setReachMode(FlowInfo.UNREACHABLE_OR_DEAD).
455
					unconditionalInits();
456
			}
426
		}
457
		}
427
		else {
458
		else {
428
			mergedInfo =
459
			mergedInfo =
Lines 578-581 Link Here
578
 */
609
 */
579
//https://bugs.eclipse.org/bugs/show_bug.cgi?id=303448
610
//https://bugs.eclipse.org/bugs/show_bug.cgi?id=303448
580
abstract public boolean isMarkedAsNullOrNonNullInAssertExpression(LocalVariableBinding local);
611
abstract public boolean isMarkedAsNullOrNonNullInAssertExpression(LocalVariableBinding local);
612
613
/**
614
 * Resets the definite and potential initialization info for the given local variable
615
 * @param local
616
 */
617
abstract public void resetAssignmentInfo(LocalVariableBinding local);
581
}
618
}
(-)a/org.eclipse.jdt.core/compiler/org/eclipse/jdt/internal/compiler/flow/LabelFlowContext.java (-3 / +3 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 31-44 Link Here
31
31
32
void checkLabelValidity(BlockScope scope) {
32
void checkLabelValidity(BlockScope scope) {
33
	// check if label was already defined above
33
	// check if label was already defined above
34
	FlowContext current = this.parent;
34
	FlowContext current = this.getLocalParent();
35
	while (current != null) {
35
	while (current != null) {
36
		char[] currentLabelName;
36
		char[] currentLabelName;
37
		if (((currentLabelName = current.labelName()) != null)
37
		if (((currentLabelName = current.labelName()) != null)
38
			&& CharOperation.equals(currentLabelName, this.labelName)) {
38
			&& CharOperation.equals(currentLabelName, this.labelName)) {
39
			scope.problemReporter().alreadyDefinedLabel(this.labelName, this.associatedNode);
39
			scope.problemReporter().alreadyDefinedLabel(this.labelName, this.associatedNode);
40
		}
40
		}
41
		current = current.parent;
41
		current = current.getLocalParent();
42
	}
42
	}
43
}
43
}
44
44
(-)a/org.eclipse.jdt.core/compiler/org/eclipse/jdt/internal/compiler/flow/LoopingFlowContext.java (-28 / +111 lines)
Lines 1-5 Link Here
1
/*******************************************************************************
1
/*******************************************************************************
2
 * Copyright (c) 2000, 2011 IBM Corporation and others.
2
 * Copyright (c) 2000, 2012 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-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 336428 - [compiler][null] bogus warning "redundant null check" in condition of do {} while() loop
10
 *     Stephan Herrmann - contributions for
11
 *     							bug 336428 - [compiler][null] bogus warning "redundant null check" in condition of do {} while() loop
12
 *								bug 186342 - [compiler][null] Using annotations for null checking
13
 *								bug 365519 - editorial cleanup after bug 186342 and bug 365387
14
 *								bug 368546 - [compiler][resource] Avoid remaining false positives found when compiling the Eclipse SDK
11
 *******************************************************************************/
15
 *******************************************************************************/
12
package org.eclipse.jdt.internal.compiler.flow;
16
package org.eclipse.jdt.internal.compiler.flow;
13
17
14
import java.util.ArrayList;
18
import java.util.ArrayList;
19
15
import org.eclipse.jdt.internal.compiler.ast.ASTNode;
20
import org.eclipse.jdt.internal.compiler.ast.ASTNode;
16
import org.eclipse.jdt.internal.compiler.ast.Expression;
21
import org.eclipse.jdt.internal.compiler.ast.Expression;
22
import org.eclipse.jdt.internal.compiler.ast.FakedTrackingVariable;
17
import org.eclipse.jdt.internal.compiler.ast.Reference;
23
import org.eclipse.jdt.internal.compiler.ast.Reference;
18
import org.eclipse.jdt.internal.compiler.codegen.BranchLabel;
24
import org.eclipse.jdt.internal.compiler.codegen.BranchLabel;
19
import org.eclipse.jdt.internal.compiler.lookup.BlockScope;
25
import org.eclipse.jdt.internal.compiler.lookup.BlockScope;
Lines 21-26 Link Here
21
import org.eclipse.jdt.internal.compiler.lookup.LocalVariableBinding;
27
import org.eclipse.jdt.internal.compiler.lookup.LocalVariableBinding;
22
import org.eclipse.jdt.internal.compiler.lookup.ReferenceBinding;
28
import org.eclipse.jdt.internal.compiler.lookup.ReferenceBinding;
23
import org.eclipse.jdt.internal.compiler.lookup.Scope;
29
import org.eclipse.jdt.internal.compiler.lookup.Scope;
30
import org.eclipse.jdt.internal.compiler.lookup.TypeBinding;
24
import org.eclipse.jdt.internal.compiler.lookup.TypeIds;
31
import org.eclipse.jdt.internal.compiler.lookup.TypeIds;
25
import org.eclipse.jdt.internal.compiler.lookup.VariableBinding;
32
import org.eclipse.jdt.internal.compiler.lookup.VariableBinding;
26
33
Lines 43-52 Link Here
43
	VariableBinding finalVariables[];
50
	VariableBinding finalVariables[];
44
	int assignCount = 0;
51
	int assignCount = 0;
45
52
53
	// the following three arrays are in sync regarding their indices:
46
	LocalVariableBinding[] nullLocals;
54
	LocalVariableBinding[] nullLocals;
47
	Expression[] nullReferences;
55
	ASTNode[] nullReferences;	// Expressions for null checking, Statements for resource analysis
56
								// cast to Expression is safe if corresponding nullCheckType != EXIT_RESOURCE
48
	int[] nullCheckTypes;
57
	int[] nullCheckTypes;
49
	int nullCount;
58
	int nullCount;
59
	// see also the related field FlowContext#expectedTypes
50
60
51
	// https://bugs.eclipse.org/bugs/show_bug.cgi?id=321926
61
	// https://bugs.eclipse.org/bugs/show_bug.cgi?id=321926
52
	static private class EscapingExceptionCatchSite {
62
	static private class EscapingExceptionCatchSite {
Lines 95-108 Link Here
95
		if (variable == null) continue;
105
		if (variable == null) continue;
96
		boolean complained = false; // remember if have complained on this final assignment
106
		boolean complained = false; // remember if have complained on this final assignment
97
		if (variable instanceof FieldBinding) {
107
		if (variable instanceof FieldBinding) {
98
			if (flowInfo.isPotentiallyAssigned((FieldBinding) variable)) {
108
			if (flowInfo.isPotentiallyAssigned((FieldBinding)variable)) {
99
				complained = true;
109
				complained = true;
100
				scope.problemReporter().duplicateInitializationOfBlankFinalField(
110
				scope.problemReporter().duplicateInitializationOfBlankFinalField(
101
					(FieldBinding) variable,
111
					(FieldBinding) variable,
102
					this.finalAssignments[i]);
112
					this.finalAssignments[i]);
103
			}
113
			}
104
		} else {
114
		} else {
105
			if (flowInfo.isPotentiallyAssigned((LocalVariableBinding) variable)) {
115
			if (flowInfo.isPotentiallyAssigned((LocalVariableBinding)variable)) {
106
				complained = true;
116
				complained = true;
107
				scope.problemReporter().duplicateInitializationOfFinalLocal(
117
				scope.problemReporter().duplicateInitializationOfFinalLocal(
108
					(LocalVariableBinding) variable,
118
					(LocalVariableBinding) variable,
Lines 112-121 Link Here
112
		// any reference reported at this level is removed from the parent context where it
122
		// any reference reported at this level is removed from the parent context where it
113
		// could also be reported again
123
		// could also be reported again
114
		if (complained) {
124
		if (complained) {
115
			FlowContext context = this.parent;
125
			FlowContext context = this.getLocalParent();
116
			while (context != null) {
126
			while (context != null) {
117
				context.removeFinalAssignmentIfAny(this.finalAssignments[i]);
127
				context.removeFinalAssignmentIfAny(this.finalAssignments[i]);
118
				context = context.parent;
128
				context = context.getLocalParent();
119
			}
129
			}
120
		}
130
		}
121
	}
131
	}
Lines 140-146 Link Here
140
		// check only immutable null checks on innermost looping context
150
		// check only immutable null checks on innermost looping context
141
		for (int i = 0; i < this.nullCount; i++) {
151
		for (int i = 0; i < this.nullCount; i++) {
142
			LocalVariableBinding local = this.nullLocals[i];
152
			LocalVariableBinding local = this.nullLocals[i];
143
			Expression expression = this.nullReferences[i];
153
			ASTNode location = this.nullReferences[i];
144
			// final local variable
154
			// final local variable
145
			switch (this.nullCheckTypes[i]) {
155
			switch (this.nullCheckTypes[i]) {
146
				case CAN_ONLY_NON_NULL | IN_COMPARISON_NULL:
156
				case CAN_ONLY_NON_NULL | IN_COMPARISON_NULL:
Lines 149-159 Link Here
149
						this.nullReferences[i] = null;
159
						this.nullReferences[i] = null;
150
						if (this.nullCheckTypes[i] == (CAN_ONLY_NON_NULL | IN_COMPARISON_NON_NULL)) {
160
						if (this.nullCheckTypes[i] == (CAN_ONLY_NON_NULL | IN_COMPARISON_NON_NULL)) {
151
							if ((this.tagBits & FlowContext.HIDE_NULL_COMPARISON_WARNING) == 0) {
161
							if ((this.tagBits & FlowContext.HIDE_NULL_COMPARISON_WARNING) == 0) {
152
								scope.problemReporter().localVariableRedundantCheckOnNonNull(local, expression);
162
								scope.problemReporter().localVariableRedundantCheckOnNonNull(local, location);
153
							}
163
							}
154
						} else {
164
						} else {
155
							if ((this.tagBits & FlowContext.HIDE_NULL_COMPARISON_WARNING) == 0) {
165
							if ((this.tagBits & FlowContext.HIDE_NULL_COMPARISON_WARNING) == 0) {
156
								scope.problemReporter().localVariableNonNullComparedToNull(local, expression);
166
								scope.problemReporter().localVariableNonNullComparedToNull(local, location);
157
							}
167
							}
158
						}
168
						}
159
						continue;
169
						continue;
Lines 165-175 Link Here
165
						this.nullReferences[i] = null;
175
						this.nullReferences[i] = null;
166
						if (this.nullCheckTypes[i] == (CAN_ONLY_NULL_NON_NULL | IN_COMPARISON_NON_NULL)) {
176
						if (this.nullCheckTypes[i] == (CAN_ONLY_NULL_NON_NULL | IN_COMPARISON_NON_NULL)) {
167
							if ((this.tagBits & FlowContext.HIDE_NULL_COMPARISON_WARNING) == 0) {
177
							if ((this.tagBits & FlowContext.HIDE_NULL_COMPARISON_WARNING) == 0) {
168
								scope.problemReporter().localVariableRedundantCheckOnNonNull(local, expression);
178
								scope.problemReporter().localVariableRedundantCheckOnNonNull(local, location);
169
							}
179
							}
170
						} else {
180
						} else {
171
							if ((this.tagBits & FlowContext.HIDE_NULL_COMPARISON_WARNING) == 0) {
181
							if ((this.tagBits & FlowContext.HIDE_NULL_COMPARISON_WARNING) == 0) {
172
								scope.problemReporter().localVariableNonNullComparedToNull(local, expression);
182
								scope.problemReporter().localVariableNonNullComparedToNull(local, location);
173
							}
183
							}
174
						}
184
						}
175
						continue;
185
						continue;
Lines 178-188 Link Here
178
						this.nullReferences[i] = null;
188
						this.nullReferences[i] = null;
179
						if (this.nullCheckTypes[i] == (CAN_ONLY_NULL_NON_NULL | IN_COMPARISON_NULL)) {
189
						if (this.nullCheckTypes[i] == (CAN_ONLY_NULL_NON_NULL | IN_COMPARISON_NULL)) {
180
							if ((this.tagBits & FlowContext.HIDE_NULL_COMPARISON_WARNING) == 0) {
190
							if ((this.tagBits & FlowContext.HIDE_NULL_COMPARISON_WARNING) == 0) {
181
								scope.problemReporter().localVariableRedundantCheckOnNull(local, expression);
191
								scope.problemReporter().localVariableRedundantCheckOnNull(local, location);
182
							}
192
							}
183
						} else {
193
						} else {
184
							if ((this.tagBits & FlowContext.HIDE_NULL_COMPARISON_WARNING) == 0) {
194
							if ((this.tagBits & FlowContext.HIDE_NULL_COMPARISON_WARNING) == 0) {
185
								scope.problemReporter().localVariableNullComparedToNonNull(local, expression);
195
								scope.problemReporter().localVariableNullComparedToNonNull(local, location);
186
							}
196
							}
187
						}
197
						}
188
						continue;
198
						continue;
Lines 192-197 Link Here
192
				case CAN_ONLY_NULL | IN_COMPARISON_NON_NULL:
202
				case CAN_ONLY_NULL | IN_COMPARISON_NON_NULL:
193
				case CAN_ONLY_NULL | IN_ASSIGNMENT:
203
				case CAN_ONLY_NULL | IN_ASSIGNMENT:
194
				case CAN_ONLY_NULL | IN_INSTANCEOF:
204
				case CAN_ONLY_NULL | IN_INSTANCEOF:
205
					Expression expression = (Expression)location;
195
					if (flowInfo.isDefinitelyNull(local)) {
206
					if (flowInfo.isDefinitelyNull(local)) {
196
						this.nullReferences[i] = null;
207
						this.nullReferences[i] = null;
197
						switch(this.nullCheckTypes[i] & CONTEXT_MASK) {
208
						switch(this.nullCheckTypes[i] & CONTEXT_MASK) {
Lines 242-262 Link Here
242
				case MAY_NULL:
253
				case MAY_NULL:
243
					if (flowInfo.isDefinitelyNull(local)) {
254
					if (flowInfo.isDefinitelyNull(local)) {
244
						this.nullReferences[i] = null;
255
						this.nullReferences[i] = null;
245
						scope.problemReporter().localVariableNullReference(local, expression);
256
						scope.problemReporter().localVariableNullReference(local, location);
246
						continue;
257
						continue;
247
					}
258
					}
259
					break;
260
				case ASSIGN_TO_NONNULL:
261
					this.parent.recordNullityMismatch(scope, (Expression)location, flowInfo.nullStatus(local), this.expectedTypes[i]);
262
					break;
263
				case EXIT_RESOURCE:
264
						FakedTrackingVariable trackingVar = local.closeTracker;
265
						if (trackingVar != null) {
266
							if (trackingVar.hasDefinitelyNoResource(flowInfo)) {
267
								continue; // no resource - no warning.
268
							}
269
							if (trackingVar.isClosedInFinallyOfEnclosing(scope)) {
270
								continue;
271
							}
272
							if (this.parent.recordExitAgainstResource(scope, flowInfo, trackingVar, location)) {
273
								this.nullReferences[i] = null;
274
								continue;
275
							}
276
						}
248
					break;
277
					break;
249
				default:
278
				default:
250
					// never happens
279
					// never happens
251
			}
280
			}
252
			this.parent.recordUsingNullReference(scope, local, expression,
281
			this.parent.recordUsingNullReference(scope, local, location,
253
					this.nullCheckTypes[i], flowInfo);
282
					this.nullCheckTypes[i], flowInfo);
254
		}
283
		}
255
	}
284
	}
256
	else {
285
	else {
257
		// check inconsistent null checks on outermost looping context
286
		// check inconsistent null checks on outermost looping context
258
		for (int i = 0; i < this.nullCount; i++) {
287
		for (int i = 0; i < this.nullCount; i++) {
259
			Expression expression = this.nullReferences[i];
288
			ASTNode location = this.nullReferences[i];
260
			// final local variable
289
			// final local variable
261
			LocalVariableBinding local = this.nullLocals[i];
290
			LocalVariableBinding local = this.nullLocals[i];
262
			switch (this.nullCheckTypes[i]) {
291
			switch (this.nullCheckTypes[i]) {
Lines 266-276 Link Here
266
						this.nullReferences[i] = null;
295
						this.nullReferences[i] = null;
267
						if (this.nullCheckTypes[i] == (CAN_ONLY_NULL_NON_NULL | IN_COMPARISON_NON_NULL)) {
296
						if (this.nullCheckTypes[i] == (CAN_ONLY_NULL_NON_NULL | IN_COMPARISON_NON_NULL)) {
268
							if ((this.tagBits & FlowContext.HIDE_NULL_COMPARISON_WARNING) == 0) {
297
							if ((this.tagBits & FlowContext.HIDE_NULL_COMPARISON_WARNING) == 0) {
269
								scope.problemReporter().localVariableRedundantCheckOnNonNull(local, expression);
298
								scope.problemReporter().localVariableRedundantCheckOnNonNull(local, location);
270
							}
299
							}
271
						} else {
300
						} else {
272
							if ((this.tagBits & FlowContext.HIDE_NULL_COMPARISON_WARNING) == 0) {
301
							if ((this.tagBits & FlowContext.HIDE_NULL_COMPARISON_WARNING) == 0) {
273
								scope.problemReporter().localVariableNonNullComparedToNull(local, expression);
302
								scope.problemReporter().localVariableNonNullComparedToNull(local, location);
274
							}
303
							}
275
						}
304
						}
276
						continue;
305
						continue;
Lines 280-285 Link Here
280
				case CAN_ONLY_NULL | IN_COMPARISON_NON_NULL:
309
				case CAN_ONLY_NULL | IN_COMPARISON_NON_NULL:
281
				case CAN_ONLY_NULL | IN_ASSIGNMENT:
310
				case CAN_ONLY_NULL | IN_ASSIGNMENT:
282
				case CAN_ONLY_NULL | IN_INSTANCEOF:
311
				case CAN_ONLY_NULL | IN_INSTANCEOF:
312
					Expression expression = (Expression) location;
283
					if (flowInfo.isDefinitelyNull(local)) {
313
					if (flowInfo.isDefinitelyNull(local)) {
284
						this.nullReferences[i] = null;
314
						this.nullReferences[i] = null;
285
						switch(this.nullCheckTypes[i] & CONTEXT_MASK) {
315
						switch(this.nullCheckTypes[i] & CONTEXT_MASK) {
Lines 330-342 Link Here
330
				case MAY_NULL:
360
				case MAY_NULL:
331
					if (flowInfo.isDefinitelyNull(local)) {
361
					if (flowInfo.isDefinitelyNull(local)) {
332
						this.nullReferences[i] = null;
362
						this.nullReferences[i] = null;
333
						scope.problemReporter().localVariableNullReference(local, expression);
363
						scope.problemReporter().localVariableNullReference(local, location);
334
						continue;
364
						continue;
335
					}
365
					}
336
					if (flowInfo.isPotentiallyNull(local)) {
366
					if (flowInfo.isPotentiallyNull(local)) {
337
						this.nullReferences[i] = null;
367
						this.nullReferences[i] = null;
338
						scope.problemReporter().localVariablePotentialNullReference(local, expression);
368
						scope.problemReporter().localVariablePotentialNullReference(local, location);
339
						continue;
369
						continue;
370
					}
371
					break;
372
				case ASSIGN_TO_NONNULL:
373
					int nullStatus = flowInfo.nullStatus(local);
374
					if (nullStatus != FlowInfo.NON_NULL) {
375
						char[][] annotationName = scope.environment().getNonNullAnnotationName();
376
						scope.problemReporter().nullityMismatch((Expression) location, this.expectedTypes[i], nullStatus, annotationName);
377
					}
378
					break;
379
				case EXIT_RESOURCE:
380
					nullStatus = flowInfo.nullStatus(local);
381
					if (nullStatus != FlowInfo.NON_NULL) {
382
						FakedTrackingVariable closeTracker = local.closeTracker;
383
						if (closeTracker != null) {
384
							if (closeTracker.hasDefinitelyNoResource(flowInfo)) {
385
								continue; // no resource - no warning.
386
							}
387
							if (closeTracker.isClosedInFinallyOfEnclosing(scope)) {
388
								continue;
389
							}
390
							nullStatus = closeTracker.findMostSpecificStatus(flowInfo, scope, null);
391
							closeTracker.recordErrorLocation(this.nullReferences[i], nullStatus);
392
							closeTracker.reportRecordedErrors(scope, nullStatus);
393
							this.nullReferences[i] = null;
394
							continue;
395
						}
340
					}
396
					}
341
					break;
397
					break;
342
				default:
398
				default:
Lines 396-401 Link Here
396
		FlowContext inner = innerFlowContext;
452
		FlowContext inner = innerFlowContext;
397
		while (inner != this && !(inner instanceof LoopingFlowContext)) {
453
		while (inner != this && !(inner instanceof LoopingFlowContext)) {
398
			inner = inner.parent;
454
			inner = inner.parent;
455
			// we know that inner is reachable from this without crossing a type boundary 
399
		}
456
		}
400
		if (inner == this) {
457
		if (inner == this) {
401
			this.upstreamNullFlowInfo.
458
			this.upstreamNullFlowInfo.
Lines 460-476 Link Here
460
	}
517
	}
461
518
462
protected void recordNullReference(LocalVariableBinding local,
519
protected void recordNullReference(LocalVariableBinding local,
463
	Expression expression, int status) {
520
	ASTNode expression, int status) {
464
	if (this.nullCount == 0) {
521
	if (this.nullCount == 0) {
465
		this.nullLocals = new LocalVariableBinding[5];
522
		this.nullLocals = new LocalVariableBinding[5];
466
		this.nullReferences = new Expression[5];
523
		this.nullReferences = new ASTNode[5];
467
		this.nullCheckTypes = new int[5];
524
		this.nullCheckTypes = new int[5];
468
	}
525
	}
469
	else if (this.nullCount == this.nullLocals.length) {
526
	else if (this.nullCount == this.nullLocals.length) {
470
		System.arraycopy(this.nullLocals, 0,
527
		System.arraycopy(this.nullLocals, 0,
471
			this.nullLocals = new LocalVariableBinding[this.nullCount * 2], 0, this.nullCount);
528
			this.nullLocals = new LocalVariableBinding[this.nullCount * 2], 0, this.nullCount);
472
		System.arraycopy(this.nullReferences, 0,
529
		System.arraycopy(this.nullReferences, 0,
473
			this.nullReferences = new Expression[this.nullCount * 2], 0, this.nullCount);
530
			this.nullReferences = new ASTNode[this.nullCount * 2], 0, this.nullCount);
474
		System.arraycopy(this.nullCheckTypes, 0,
531
		System.arraycopy(this.nullCheckTypes, 0,
475
			this.nullCheckTypes = new int[this.nullCount * 2], 0, this.nullCount);
532
			this.nullCheckTypes = new int[this.nullCount * 2], 0, this.nullCount);
476
	}
533
	}
Lines 479-486 Link Here
479
	this.nullCheckTypes[this.nullCount++] = status;
536
	this.nullCheckTypes[this.nullCount++] = status;
480
}
537
}
481
538
539
/** Record the fact that we see an early exit (in 'reference') while 'trackingVar' is in scope and may be unclosed. */
540
public boolean recordExitAgainstResource(BlockScope scope, FlowInfo flowInfo, FakedTrackingVariable trackingVar, ASTNode reference) {
541
	LocalVariableBinding local = trackingVar.binding;
542
	if (flowInfo.isDefinitelyNonNull(local)) {
543
		return false;
544
	}
545
	if (flowInfo.isDefinitelyNull(local)) {
546
		scope.problemReporter().unclosedCloseable(trackingVar, reference);
547
		return true; // handled
548
	}
549
	if (flowInfo.isPotentiallyNull(local)) {
550
		scope.problemReporter().potentiallyUnclosedCloseable(trackingVar, reference);
551
		return true; // handled
552
	}
553
	recordNullReference(trackingVar.binding, reference, EXIT_RESOURCE);
554
	return true; // handled
555
}
556
482
public void recordUsingNullReference(Scope scope, LocalVariableBinding local,
557
public void recordUsingNullReference(Scope scope, LocalVariableBinding local,
483
		Expression reference, int checkType, FlowInfo flowInfo) {
558
		ASTNode location, int checkType, FlowInfo flowInfo) {
484
	if ((flowInfo.tagBits & FlowInfo.UNREACHABLE) != 0 ||
559
	if ((flowInfo.tagBits & FlowInfo.UNREACHABLE) != 0 ||
485
			flowInfo.isDefinitelyUnknown(local)) {
560
			flowInfo.isDefinitelyUnknown(local)) {
486
		return;
561
		return;
Lines 488-493 Link Here
488
	switch (checkType) {
563
	switch (checkType) {
489
		case CAN_ONLY_NULL_NON_NULL | IN_COMPARISON_NULL:
564
		case CAN_ONLY_NULL_NON_NULL | IN_COMPARISON_NULL:
490
		case CAN_ONLY_NULL_NON_NULL | IN_COMPARISON_NON_NULL:
565
		case CAN_ONLY_NULL_NON_NULL | IN_COMPARISON_NON_NULL:
566
			Expression reference = (Expression)location;
491
			if (flowInfo.isDefinitelyNonNull(local)) {
567
			if (flowInfo.isDefinitelyNonNull(local)) {
492
				if (checkType == (CAN_ONLY_NULL_NON_NULL | IN_COMPARISON_NON_NULL)) {
568
				if (checkType == (CAN_ONLY_NULL_NON_NULL | IN_COMPARISON_NON_NULL)) {
493
					if ((this.tagBits & FlowContext.HIDE_NULL_COMPARISON_WARNING) == 0) {
569
					if ((this.tagBits & FlowContext.HIDE_NULL_COMPARISON_WARNING) == 0) {
Lines 547-552 Link Here
547
		case CAN_ONLY_NULL | IN_COMPARISON_NON_NULL:
623
		case CAN_ONLY_NULL | IN_COMPARISON_NON_NULL:
548
		case CAN_ONLY_NULL | IN_ASSIGNMENT:
624
		case CAN_ONLY_NULL | IN_ASSIGNMENT:
549
		case CAN_ONLY_NULL | IN_INSTANCEOF:
625
		case CAN_ONLY_NULL | IN_INSTANCEOF:
626
			reference = (Expression)location;
550
			if (flowInfo.isPotentiallyNonNull(local)
627
			if (flowInfo.isPotentiallyNonNull(local)
551
					|| flowInfo.isPotentiallyUnknown(local)
628
					|| flowInfo.isPotentiallyUnknown(local)
552
					|| flowInfo.isProtectedNonNull(local)) {
629
					|| flowInfo.isProtectedNonNull(local)) {
Lines 616-629 Link Here
616
				return;
693
				return;
617
			}
694
			}
618
			if (flowInfo.isDefinitelyNull(local)) {
695
			if (flowInfo.isDefinitelyNull(local)) {
619
				scope.problemReporter().localVariableNullReference(local, reference);
696
				scope.problemReporter().localVariableNullReference(local, location);
620
				return;
697
				return;
621
			}
698
			}
622
			if (flowInfo.isPotentiallyNull(local)) {
699
			if (flowInfo.isPotentiallyNull(local)) {
623
				scope.problemReporter().localVariablePotentialNullReference(local, reference);
700
				scope.problemReporter().localVariablePotentialNullReference(local, location);
624
				return;
701
				return;
625
			}
702
			}
626
			recordNullReference(local, reference, checkType);
703
			recordNullReference(local, location, checkType);
627
			return;
704
			return;
628
		default:
705
		default:
629
			// never happens
706
			// never happens
Lines 666-669 Link Here
666
	public boolean hasEscapingExceptions() {
743
	public boolean hasEscapingExceptions() {
667
		return this.escapingExceptionCatchSites != null;
744
		return this.escapingExceptionCatchSites != null;
668
	}
745
	}
746
747
	protected boolean internalRecordNullityMismatch(Expression expression, int nullStatus, TypeBinding expectedType, int checkType) {
748
		recordExpectedType(expectedType, this.nullCount);
749
		recordNullReference(expression.localVariableBinding(), expression, checkType);
750
		return true;
751
	}
669
}
752
}
(-)a/org.eclipse.jdt.core/compiler/org/eclipse/jdt/internal/compiler/flow/UnconditionalFlowInfo.java (-6 / +31 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]
Lines 2130-2134 Link Here
2130
		}
2131
		}
2131
	}
2132
	}
2132
}
2133
}
2134
2135
public void resetAssignmentInfo(LocalVariableBinding local) {
2136
	resetAssignmentInfo(local.id + this.maxFieldCount);
2137
}
2138
2139
public void resetAssignmentInfo(int position) {
2140
	if (this != DEAD_END) {
2141
		// position is zero-based
2142
		if (position < BitCacheSize) {
2143
			// use bits
2144
			long mask;
2145
			this.definiteInits &= (mask = ~(1L << position));
2146
			this.potentialInits &= mask;
2147
		} else {
2148
			// use extra vector
2149
			int vectorIndex = (position / BitCacheSize) - 1;
2150
			if (this.extra == null || vectorIndex >= this.extra[0].length) return;	// variable doesnt exist in flow info
2151
			long mask;
2152
			this.extra[0][vectorIndex] &=
2153
				(mask = ~(1L << (position % BitCacheSize)));
2154
			this.extra[1][vectorIndex] &= mask;
2155
		}
2156
	}
2157
}
2133
}
2158
}
2134
2159
(-)a/org.eclipse.jdt.core/compiler/org/eclipse/jdt/internal/compiler/impl/CompilerOptions.java (-5 / +159 lines)
Lines 1-5 Link Here
1
/*******************************************************************************
1
/*******************************************************************************
2
 * Copyright (c) 2000, 2011 IBM Corporation and others.
2
 * Copyright (c) 2000, 2012 IBM Corporation and others.
3
 * All rights reserved. This program and the accompanying materials
3
 * All rights reserved. This program and the accompanying materials
4
 * are made available under the terms of the Eclipse Public License v1.0
4
 * are made available under the terms of the Eclipse Public License v1.0
5
 * which accompanies this distribution, and is available at
5
 * which accompanies this distribution, and is available at
Lines 8-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
15
 *								bug 186342 - [compiler][null] Using annotations for null checking
16
 *								bug 370639 - [compiler][resource] restore the default for resource leak warnings
17
 *								bug 366063 - Compiler should not add synthetic @NonNull annotations
13
 *******************************************************************************/
18
 *******************************************************************************/
14
package org.eclipse.jdt.internal.compiler.impl;
19
package org.eclipse.jdt.internal.compiler.impl;
15
20
Lines 24-29 Link Here
24
import org.eclipse.jdt.internal.compiler.ast.ASTNode;
29
import org.eclipse.jdt.internal.compiler.ast.ASTNode;
25
import org.eclipse.jdt.internal.compiler.classfmt.ClassFileConstants;
30
import org.eclipse.jdt.internal.compiler.classfmt.ClassFileConstants;
26
import org.eclipse.jdt.internal.compiler.lookup.ExtraCompilerModifiers;
31
import org.eclipse.jdt.internal.compiler.lookup.ExtraCompilerModifiers;
32
import org.eclipse.jdt.internal.compiler.lookup.TagBits;
27
import org.eclipse.jdt.internal.compiler.problem.ProblemSeverities;
33
import org.eclipse.jdt.internal.compiler.problem.ProblemSeverities;
28
import org.eclipse.jdt.internal.compiler.util.Util;
34
import org.eclipse.jdt.internal.compiler.util.Util;
29
35
Lines 137-142 Link Here
137
	public static final String OPTION_ReportMethodCanBeStatic = "org.eclipse.jdt.core.compiler.problem.reportMethodCanBeStatic";  //$NON-NLS-1$
143
	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$
144
	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$
145
	public static final String OPTION_ReportRedundantSpecificationOfTypeArguments =  "org.eclipse.jdt.core.compiler.problem.redundantSpecificationOfTypeArguments"; //$NON-NLS-1$
146
	public static final String OPTION_ReportUnclosedCloseable = "org.eclipse.jdt.core.compiler.problem.unclosedCloseable"; //$NON-NLS-1$
147
	public static final String OPTION_ReportPotentiallyUnclosedCloseable = "org.eclipse.jdt.core.compiler.problem.potentiallyUnclosedCloseable"; //$NON-NLS-1$
148
	public static final String OPTION_ReportExplicitlyClosedAutoCloseable = "org.eclipse.jdt.core.compiler.problem.explicitlyClosedAutoCloseable"; //$NON-NLS-1$
149
	public static final String OPTION_ReportNullSpecViolation = "org.eclipse.jdt.core.compiler.problem.nullSpecViolation";  //$NON-NLS-1$
150
	public static final String OPTION_ReportPotentialNullSpecViolation = "org.eclipse.jdt.core.compiler.problem.potentialNullSpecViolation";  //$NON-NLS-1$
151
	public static final String OPTION_ReportNullSpecInsufficientInfo = "org.eclipse.jdt.core.compiler.problem.nullSpecInsufficientInfo";  //$NON-NLS-1$
152
	public static final String OPTION_ReportRedundantNullAnnotation = "org.eclipse.jdt.core.compiler.problem.redundantNullAnnotation";  //$NON-NLS-1$
153
	public static final String OPTION_AnnotationBasedNullAnalysis = "org.eclipse.jdt.core.compiler.annotation.nullanalysis"; //$NON-NLS-1$
154
	public static final String OPTION_NullableAnnotationName = "org.eclipse.jdt.core.compiler.annotation.nullable"; //$NON-NLS-1$
155
	public static final String OPTION_NonNullAnnotationName = "org.eclipse.jdt.core.compiler.annotation.nonnull"; //$NON-NLS-1$
156
	public static final String OPTION_NonNullByDefaultAnnotationName = "org.eclipse.jdt.core.compiler.annotation.nonnullbydefault"; //$NON-NLS-1$
157
	// defaults for the above:
158
	static final char[][] DEFAULT_NULLABLE_ANNOTATION_NAME = CharOperation.splitOn('.', "org.eclipse.jdt.annotation.Nullable".toCharArray()); //$NON-NLS-1$
159
	static final char[][] DEFAULT_NONNULL_ANNOTATION_NAME = CharOperation.splitOn('.', "org.eclipse.jdt.annotation.NonNull".toCharArray()); //$NON-NLS-1$
160
	static final char[][] DEFAULT_NONNULLBYDEFAULT_ANNOTATION_NAME = CharOperation.splitOn('.', "org.eclipse.jdt.annotation.NonNullByDefault".toCharArray()); //$NON-NLS-1$
161
	public static final String OPTION_NonNullIsDefault = "org.eclipse.jdt.core.compiler.annotation.nonnullisdefault";  //$NON-NLS-1$
140
	/**
162
	/**
141
	 * Possible values for configurable options
163
	 * Possible values for configurable options
142
	 */
164
	 */
Lines 240-245 Link Here
240
	public static final int MethodCanBeStatic = IrritantSet.GROUP2 | ASTNode.Bit5;
262
	public static final int MethodCanBeStatic = IrritantSet.GROUP2 | ASTNode.Bit5;
241
	public static final int MethodCanBePotentiallyStatic = IrritantSet.GROUP2 | ASTNode.Bit6;
263
	public static final int MethodCanBePotentiallyStatic = IrritantSet.GROUP2 | ASTNode.Bit6;
242
	public static final int RedundantSpecificationOfTypeArguments = IrritantSet.GROUP2 | ASTNode.Bit7;
264
	public static final int RedundantSpecificationOfTypeArguments = IrritantSet.GROUP2 | ASTNode.Bit7;
265
	public static final int UnclosedCloseable = IrritantSet.GROUP2 | ASTNode.Bit8;
266
	public static final int PotentiallyUnclosedCloseable = IrritantSet.GROUP2 | ASTNode.Bit9;
267
	public static final int ExplicitlyClosedAutoCloseable = IrritantSet.GROUP2 | ASTNode.Bit10;
268
	public static final int NullSpecViolation = IrritantSet.GROUP2 | ASTNode.Bit11;
269
	public static final int PotentialNullSpecViolation = IrritantSet.GROUP2 | ASTNode.Bit12;
270
	public static final int NullSpecInsufficientInfo = IrritantSet.GROUP2 | ASTNode.Bit13;
271
	public static final int RedundantNullAnnotation = IrritantSet.GROUP2 | ASTNode.Bit14;
243
272
244
	// Severity level for handlers
273
	// Severity level for handlers
245
	/** 
274
	/** 
Lines 362-367 Link Here
362
	/** Controls whether forced generic type problems get reported  */
391
	/** Controls whether forced generic type problems get reported  */
363
	public boolean reportUnavoidableGenericTypeProblems;
392
	public boolean reportUnavoidableGenericTypeProblems;
364
393
394
	// === Support for Null Annotations: ===
395
	/** Master switch for null analysis based on annotations: */
396
	public boolean isAnnotationBasedNullAnalysisEnabled;
397
	/** Fully qualified name of annotation to use as marker for nullable types. */
398
	public char[][] nullableAnnotationName;
399
	/** Fully qualified name of annotation to use as marker for nonnull types. */
400
	public char[][] nonNullAnnotationName;
401
	/** Fully qualified name of annotation to use as marker for default nonnull. */
402
	public char[][] nonNullByDefaultAnnotationName;
403
	/** TagBits-encoded default for non-annotated types. */
404
	public long intendedDefaultNonNullness; // 0 or TagBits#AnnotationNonNull
405
	/** Should resources (objects of type Closeable) be analysed for matching calls to close()? */
406
	public boolean analyseResourceLeaks;
407
365
	// keep in sync with warningTokenToIrritant and warningTokenFromIrritant
408
	// keep in sync with warningTokenToIrritant and warningTokenFromIrritant
366
	public final static String[] warningTokens = {
409
	public final static String[] warningTokens = {
367
		"all", //$NON-NLS-1$
410
		"all", //$NON-NLS-1$
Lines 376-388 Link Here
376
		"javadoc", //$NON-NLS-1$
419
		"javadoc", //$NON-NLS-1$
377
		"nls", //$NON-NLS-1$
420
		"nls", //$NON-NLS-1$
378
		"null", //$NON-NLS-1$
421
		"null", //$NON-NLS-1$
379
		"restriction", //$NON-NLS-1$
380
		"rawtypes", //$NON-NLS-1$
422
		"rawtypes", //$NON-NLS-1$
423
		"resource", //$NON-NLS-1$
424
		"restriction", //$NON-NLS-1$		
381
		"serial", //$NON-NLS-1$
425
		"serial", //$NON-NLS-1$
382
		"static-access", //$NON-NLS-1$
426
		"static-access", //$NON-NLS-1$
383
		"static-method", //$NON-NLS-1$
427
		"static-method", //$NON-NLS-1$
384
		"super", //$NON-NLS-1$
428
		"super", //$NON-NLS-1$
385
		"synthetic-access", //$NON-NLS-1$
429
		"synthetic-access", //$NON-NLS-1$
430
		"sync-override",	//$NON-NLS-1$
386
		"unchecked", //$NON-NLS-1$
431
		"unchecked", //$NON-NLS-1$
387
		"unqualified-field-access", //$NON-NLS-1$
432
		"unqualified-field-access", //$NON-NLS-1$
388
		"unused", //$NON-NLS-1$
433
		"unused", //$NON-NLS-1$
Lines 551-556 Link Here
551
				return OPTION_ReportMethodCanBePotentiallyStatic;
596
				return OPTION_ReportMethodCanBePotentiallyStatic;
552
			case RedundantSpecificationOfTypeArguments :
597
			case RedundantSpecificationOfTypeArguments :
553
				return OPTION_ReportRedundantSpecificationOfTypeArguments;
598
				return OPTION_ReportRedundantSpecificationOfTypeArguments;
599
			case UnclosedCloseable :
600
				return OPTION_ReportUnclosedCloseable;
601
			case PotentiallyUnclosedCloseable :
602
				return OPTION_ReportPotentiallyUnclosedCloseable;
603
			case ExplicitlyClosedAutoCloseable :
604
				return OPTION_ReportExplicitlyClosedAutoCloseable;
605
			case NullSpecViolation :
606
				return OPTION_ReportNullSpecViolation;
607
			case PotentialNullSpecViolation :
608
				return OPTION_ReportPotentialNullSpecViolation;
609
			case NullSpecInsufficientInfo :
610
				return OPTION_ReportNullSpecInsufficientInfo;
611
			case RedundantNullAnnotation :
612
				return OPTION_ReportRedundantNullAnnotation;
554
		}
613
		}
555
		return null;
614
		return null;
556
	}
615
	}
Lines 714-719 Link Here
714
			OPTION_ReportUnusedTypeArgumentsForMethodInvocation,
773
			OPTION_ReportUnusedTypeArgumentsForMethodInvocation,
715
			OPTION_ReportUnusedWarningToken,
774
			OPTION_ReportUnusedWarningToken,
716
			OPTION_ReportVarargsArgumentNeedCast,
775
			OPTION_ReportVarargsArgumentNeedCast,
776
			OPTION_ReportUnclosedCloseable,
777
			OPTION_ReportPotentiallyUnclosedCloseable,
778
			OPTION_ReportExplicitlyClosedAutoCloseable,
779
			OPTION_AnnotationBasedNullAnalysis,
780
			OPTION_NonNullAnnotationName,
781
			OPTION_NullableAnnotationName,
782
			OPTION_NonNullByDefaultAnnotationName,
783
			OPTION_NonNullIsDefault,
784
			OPTION_ReportNullSpecViolation,
785
			OPTION_ReportPotentialNullSpecViolation,
786
			OPTION_ReportNullSpecInsufficientInfo,
787
			OPTION_ReportRedundantNullAnnotation
717
		};
788
		};
718
		return result;
789
		return result;
719
	}
790
	}
Lines 776-781 Link Here
776
			case NullReference :
847
			case NullReference :
777
			case PotentialNullReference :
848
			case PotentialNullReference :
778
			case RedundantNullCheck :
849
			case RedundantNullCheck :
850
			case NullSpecViolation :
851
			case PotentialNullSpecViolation :
852
			case NullSpecInsufficientInfo :
853
			case RedundantNullAnnotation :
779
				return "null"; //$NON-NLS-1$
854
				return "null"; //$NON-NLS-1$
780
			case FallthroughCase :
855
			case FallthroughCase :
781
				return "fallthrough"; //$NON-NLS-1$
856
				return "fallthrough"; //$NON-NLS-1$
Lines 784-793 Link Here
784
			case MethodCanBeStatic :
859
			case MethodCanBeStatic :
785
			case MethodCanBePotentiallyStatic :
860
			case MethodCanBePotentiallyStatic :
786
				return "static-method"; //$NON-NLS-1$
861
				return "static-method"; //$NON-NLS-1$
862
			case PotentiallyUnclosedCloseable:
863
			case UnclosedCloseable:
864
			case ExplicitlyClosedAutoCloseable:
865
				return "resource"; //$NON-NLS-1$
787
			case InvalidJavadoc :
866
			case InvalidJavadoc :
788
			case MissingJavadocComments :
867
			case MissingJavadocComments :
789
			case MissingJavadocTags:
868
			case MissingJavadocTags:
790
				return "javadoc"; //$NON-NLS-1$				
869
				return "javadoc"; //$NON-NLS-1$
870
			case MissingSynchronizedModifierInInheritedMethod:
871
				return "sync-override";	 //$NON-NLS-1$
791
		}
872
		}
792
		return null;
873
		return null;
793
	}
874
	}
Lines 841-846 Link Here
841
			case 'r' :
922
			case 'r' :
842
				if ("rawtypes".equals(warningToken)) //$NON-NLS-1$
923
				if ("rawtypes".equals(warningToken)) //$NON-NLS-1$
843
					return IrritantSet.RAW;
924
					return IrritantSet.RAW;
925
				if ("resource".equals(warningToken)) //$NON-NLS-1$
926
					return IrritantSet.RESOURCE;
844
				if ("restriction".equals(warningToken)) //$NON-NLS-1$
927
				if ("restriction".equals(warningToken)) //$NON-NLS-1$
845
					return IrritantSet.RESTRICTION;
928
					return IrritantSet.RESTRICTION;
846
				break;
929
				break;
Lines 856-861 Link Here
856
				if ("super".equals(warningToken)) { //$NON-NLS-1$
939
				if ("super".equals(warningToken)) { //$NON-NLS-1$
857
					return IrritantSet.SUPER;
940
					return IrritantSet.SUPER;
858
				}
941
				}
942
				if ("sync-override".equals(warningToken)) //$NON-NLS-1$
943
					return IrritantSet.SYNCHRONIZED;
859
				break;
944
				break;
860
			case 'u' :
945
			case 'u' :
861
				if ("unused".equals(warningToken)) //$NON-NLS-1$
946
				if ("unused".equals(warningToken)) //$NON-NLS-1$
Lines 980-985 Link Here
980
		optionsMap.put(OPTION_ReportMethodCanBeStatic, getSeverityString(MethodCanBeStatic));
1065
		optionsMap.put(OPTION_ReportMethodCanBeStatic, getSeverityString(MethodCanBeStatic));
981
		optionsMap.put(OPTION_ReportMethodCanBePotentiallyStatic, getSeverityString(MethodCanBePotentiallyStatic));
1066
		optionsMap.put(OPTION_ReportMethodCanBePotentiallyStatic, getSeverityString(MethodCanBePotentiallyStatic));
982
		optionsMap.put(OPTION_ReportRedundantSpecificationOfTypeArguments, getSeverityString(RedundantSpecificationOfTypeArguments));
1067
		optionsMap.put(OPTION_ReportRedundantSpecificationOfTypeArguments, getSeverityString(RedundantSpecificationOfTypeArguments));
1068
		optionsMap.put(OPTION_ReportUnclosedCloseable, getSeverityString(UnclosedCloseable));
1069
		optionsMap.put(OPTION_ReportPotentiallyUnclosedCloseable, getSeverityString(PotentiallyUnclosedCloseable));
1070
		optionsMap.put(OPTION_ReportExplicitlyClosedAutoCloseable, getSeverityString(ExplicitlyClosedAutoCloseable));
1071
		optionsMap.put(OPTION_AnnotationBasedNullAnalysis, this.isAnnotationBasedNullAnalysisEnabled ? ENABLED : DISABLED);
1072
		optionsMap.put(OPTION_ReportNullSpecViolation, getSeverityString(NullSpecViolation));
1073
		optionsMap.put(OPTION_ReportPotentialNullSpecViolation, getSeverityString(PotentialNullSpecViolation));
1074
		optionsMap.put(OPTION_ReportNullSpecInsufficientInfo, getSeverityString(NullSpecInsufficientInfo));
1075
		optionsMap.put(OPTION_ReportRedundantNullAnnotation, getSeverityString(RedundantNullAnnotation));
1076
		optionsMap.put(OPTION_NullableAnnotationName, String.valueOf(CharOperation.concatWith(this.nullableAnnotationName, '.')));
1077
		optionsMap.put(OPTION_NonNullAnnotationName, String.valueOf(CharOperation.concatWith(this.nonNullAnnotationName, '.')));
1078
		optionsMap.put(OPTION_NonNullByDefaultAnnotationName, String.valueOf(CharOperation.concatWith(this.nonNullByDefaultAnnotationName, '.')));
1079
		if (this.intendedDefaultNonNullness == TagBits.AnnotationNonNull)
1080
			optionsMap.put(OPTION_NonNullIsDefault, CompilerOptions.ENABLED);
1081
		else
1082
			optionsMap.put(OPTION_NonNullIsDefault, CompilerOptions.DISABLED);
983
		return optionsMap;
1083
		return optionsMap;
984
	}
1084
	}
985
1085
Lines 1130-1135 Link Here
1130
		
1230
		
1131
		// allow null info from asserts to be considered downstream by default
1231
		// allow null info from asserts to be considered downstream by default
1132
		this.includeNullInfoFromAsserts = false;
1232
		this.includeNullInfoFromAsserts = false;
1233
		
1234
		this.isAnnotationBasedNullAnalysisEnabled = false;
1235
		this.nullableAnnotationName = DEFAULT_NULLABLE_ANNOTATION_NAME;
1236
		this.nonNullAnnotationName = DEFAULT_NONNULL_ANNOTATION_NAME;
1237
		this.nonNullByDefaultAnnotationName = DEFAULT_NONNULLBYDEFAULT_ANNOTATION_NAME;
1238
		this.intendedDefaultNonNullness = 0;
1239
		
1240
		this.analyseResourceLeaks = true;
1133
	}
1241
	}
1134
1242
1135
	public void set(Map optionsMap) {
1243
	public void set(Map optionsMap) {
Lines 1410-1415 Link Here
1410
		if ((optionValue = optionsMap.get(OPTION_ReportMethodCanBeStatic)) != null) updateSeverity(MethodCanBeStatic, optionValue);
1518
		if ((optionValue = optionsMap.get(OPTION_ReportMethodCanBeStatic)) != null) updateSeverity(MethodCanBeStatic, optionValue);
1411
		if ((optionValue = optionsMap.get(OPTION_ReportMethodCanBePotentiallyStatic)) != null) updateSeverity(MethodCanBePotentiallyStatic, optionValue);
1519
		if ((optionValue = optionsMap.get(OPTION_ReportMethodCanBePotentiallyStatic)) != null) updateSeverity(MethodCanBePotentiallyStatic, optionValue);
1412
		if ((optionValue = optionsMap.get(OPTION_ReportRedundantSpecificationOfTypeArguments)) != null) updateSeverity(RedundantSpecificationOfTypeArguments, optionValue);
1520
		if ((optionValue = optionsMap.get(OPTION_ReportRedundantSpecificationOfTypeArguments)) != null) updateSeverity(RedundantSpecificationOfTypeArguments, optionValue);
1521
		if ((optionValue = optionsMap.get(OPTION_ReportUnclosedCloseable)) != null) updateSeverity(UnclosedCloseable, optionValue);
1522
		if ((optionValue = optionsMap.get(OPTION_ReportPotentiallyUnclosedCloseable)) != null) updateSeverity(PotentiallyUnclosedCloseable, optionValue);
1523
		if ((optionValue = optionsMap.get(OPTION_ReportExplicitlyClosedAutoCloseable)) != null) updateSeverity(ExplicitlyClosedAutoCloseable, optionValue);
1524
		if (getSeverity(UnclosedCloseable) == ProblemSeverities.Ignore
1525
				&& getSeverity(PotentiallyUnclosedCloseable) == ProblemSeverities.Ignore
1526
				&& getSeverity(ExplicitlyClosedAutoCloseable) == ProblemSeverities.Ignore) {
1527
			this.analyseResourceLeaks = false;
1528
		} else {
1529
			this.analyseResourceLeaks = true;
1530
		}
1531
		if ((optionValue = optionsMap.get(OPTION_AnnotationBasedNullAnalysis)) != null) {
1532
			this.isAnnotationBasedNullAnalysisEnabled = ENABLED.equals(optionValue);
1533
		}
1534
		if (this.isAnnotationBasedNullAnalysisEnabled) {
1535
			if ((optionValue = optionsMap.get(OPTION_ReportNullSpecViolation)) != null) {
1536
				if (ERROR.equals(optionValue)) {
1537
					this.errorThreshold.set(NullSpecViolation);
1538
					this.warningThreshold.clear(NullSpecViolation);
1539
				} else if (WARNING.equals(optionValue)) {
1540
					this.errorThreshold.clear(NullSpecViolation);
1541
					this.warningThreshold.set(NullSpecViolation);
1542
				}
1543
				// "ignore" is not valid for this option
1544
			}
1545
			if ((optionValue = optionsMap.get(OPTION_ReportPotentialNullSpecViolation)) != null) updateSeverity(PotentialNullSpecViolation, optionValue);
1546
			if ((optionValue = optionsMap.get(OPTION_ReportNullSpecInsufficientInfo)) != null) updateSeverity(NullSpecInsufficientInfo, optionValue);
1547
			if ((optionValue = optionsMap.get(OPTION_ReportRedundantNullAnnotation)) != null) updateSeverity(RedundantNullAnnotation, optionValue);
1548
			if ((optionValue = optionsMap.get(OPTION_NullableAnnotationName)) != null) {
1549
				this.nullableAnnotationName = CharOperation.splitAndTrimOn('.', ((String)optionValue).toCharArray());
1550
			}
1551
			if ((optionValue = optionsMap.get(OPTION_NonNullAnnotationName)) != null) {
1552
				this.nonNullAnnotationName = CharOperation.splitAndTrimOn('.', ((String)optionValue).toCharArray());
1553
			}
1554
			if ((optionValue = optionsMap.get(OPTION_NonNullByDefaultAnnotationName)) != null) {
1555
				this.nonNullByDefaultAnnotationName = CharOperation.splitAndTrimOn('.', ((String)optionValue).toCharArray());
1556
			}
1557
			if ((optionValue = optionsMap.get(OPTION_NonNullIsDefault)) != null) {
1558
				if (CompilerOptions.ENABLED.equals(optionValue))
1559
					this.intendedDefaultNonNullness = TagBits.AnnotationNonNull;
1560
				else if (CompilerOptions.DISABLED.equals(optionValue))
1561
					this.intendedDefaultNonNullness = 0;
1562
			}
1563
		}
1413
1564
1414
		// Javadoc options
1565
		// Javadoc options
1415
		if ((optionValue = optionsMap.get(OPTION_DocCommentSupport)) != null) {
1566
		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$
1776
		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$
1777
		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$
1778
		buf.append("\n\t- redundant specification of type arguments: ").append(getSeverityString(RedundantSpecificationOfTypeArguments)); //$NON-NLS-1$
1779
		buf.append("\n\t- resource is not closed: ").append(getSeverityString(UnclosedCloseable)); //$NON-NLS-1$
1780
		buf.append("\n\t- resource may not be closed: ").append(getSeverityString(PotentiallyUnclosedCloseable)); //$NON-NLS-1$
1781
		buf.append("\n\t- resource should be handled by try-with-resources: ").append(getSeverityString(ExplicitlyClosedAutoCloseable)); //$NON-NLS-1$
1628
		return buf.toString();
1782
		return buf.toString();
1629
	}
1783
	}
1630
	
1784
	
(-)a/org.eclipse.jdt.core/compiler/org/eclipse/jdt/internal/compiler/impl/IrritantSet.java (-4 / +25 lines)
Lines 1-5 Link Here
1
/*******************************************************************************
1
/*******************************************************************************
2
 * Copyright (c) 2000, 2011 IBM Corporation and others.
2
 * Copyright (c) 2000, 2012 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 - Contributions for
11
 *     							bug 349326 - [1.7] new warning for missing try-with-resources
12
 *								bug 186342 - [compiler][null] Using annotations for null checking
13
 *								bug 370639 - [compiler][resource] restore the default for resource leak warnings
10
 *******************************************************************************/
14
 *******************************************************************************/
11
15
12
package org.eclipse.jdt.internal.compiler.impl;
16
package org.eclipse.jdt.internal.compiler.impl;
Lines 53-62 Link Here
53
	public static final IrritantSet STATIC_ACCESS = new IrritantSet(CompilerOptions.IndirectStaticAccess);
57
	public static final IrritantSet STATIC_ACCESS = new IrritantSet(CompilerOptions.IndirectStaticAccess);
54
	public static final IrritantSet STATIC_METHOD = new IrritantSet(CompilerOptions.MethodCanBeStatic);
58
	public static final IrritantSet STATIC_METHOD = new IrritantSet(CompilerOptions.MethodCanBeStatic);
55
	public static final IrritantSet SYNTHETIC_ACCESS = new IrritantSet(CompilerOptions.AccessEmulation);
59
	public static final IrritantSet SYNTHETIC_ACCESS = new IrritantSet(CompilerOptions.AccessEmulation);
60
	public static final IrritantSet SYNCHRONIZED = new IrritantSet(CompilerOptions.MissingSynchronizedModifierInInheritedMethod);
56
	public static final IrritantSet SUPER = new IrritantSet(CompilerOptions.OverridingMethodWithoutSuperInvocation);
61
	public static final IrritantSet SUPER = new IrritantSet(CompilerOptions.OverridingMethodWithoutSuperInvocation);
57
	public static final IrritantSet UNUSED = new IrritantSet(CompilerOptions.UnusedLocalVariable);
62
	public static final IrritantSet UNUSED = new IrritantSet(CompilerOptions.UnusedLocalVariable);
58
	public static final IrritantSet UNCHECKED = new IrritantSet(CompilerOptions.UncheckedTypeOperation);
63
	public static final IrritantSet UNCHECKED = new IrritantSet(CompilerOptions.UncheckedTypeOperation);
59
	public static final IrritantSet UNQUALIFIED_FIELD_ACCESS = new IrritantSet(CompilerOptions.UnqualifiedFieldAccess);
64
	public static final IrritantSet UNQUALIFIED_FIELD_ACCESS = new IrritantSet(CompilerOptions.UnqualifiedFieldAccess);
65
	public static final IrritantSet RESOURCE = new IrritantSet(CompilerOptions.UnclosedCloseable);
60
66
61
	public static final IrritantSet JAVADOC = new IrritantSet(CompilerOptions.InvalidJavadoc);
67
	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	
68
	public static final IrritantSet COMPILER_DEFAULT_ERRORS = new IrritantSet(0); // no optional error by default	
Lines 99-106 Link Here
99
			// group-2 warnings enabled by default
105
			// group-2 warnings enabled by default
100
			.set(
106
			.set(
101
				CompilerOptions.DeadCode
107
				CompilerOptions.DeadCode
102
				|CompilerOptions.Tasks);
108
				|CompilerOptions.Tasks
103
			
109
				|CompilerOptions.UnclosedCloseable
110
				|CompilerOptions.NullSpecInsufficientInfo
111
				|CompilerOptions.RedundantNullAnnotation);
112
		// default errors IF AnnotationBasedNullAnalysis is enabled:
113
		COMPILER_DEFAULT_ERRORS.set(
114
				CompilerOptions.NullSpecViolation
115
				|CompilerOptions.PotentialNullSpecViolation);
116
104
		ALL.setAll();
117
		ALL.setAll();
105
		HIDING
118
		HIDING
106
			.set(CompilerOptions.FieldHiding)
119
			.set(CompilerOptions.FieldHiding)
Lines 108-114 Link Here
108
			.set(CompilerOptions.TypeHiding);
121
			.set(CompilerOptions.TypeHiding);
109
		NULL
122
		NULL
110
			.set(CompilerOptions.PotentialNullReference)
123
			.set(CompilerOptions.PotentialNullReference)
111
			.set(CompilerOptions.RedundantNullCheck);
124
			.set(CompilerOptions.RedundantNullCheck)
125
			.set(CompilerOptions.NullSpecViolation)
126
			.set(CompilerOptions.PotentialNullSpecViolation)
127
			.set(CompilerOptions.NullSpecInsufficientInfo)
128
			.set(CompilerOptions.RedundantNullAnnotation);
129
112
		RESTRICTION.set(CompilerOptions.DiscouragedReference);
130
		RESTRICTION.set(CompilerOptions.DiscouragedReference);
113
		STATIC_ACCESS.set(CompilerOptions.NonStaticAccessToStatic);
131
		STATIC_ACCESS.set(CompilerOptions.NonStaticAccessToStatic);
114
		UNUSED
132
		UNUSED
Lines 124-129 Link Here
124
			.set(CompilerOptions.RedundantSpecificationOfTypeArguments);
142
			.set(CompilerOptions.RedundantSpecificationOfTypeArguments);
125
		STATIC_METHOD
143
		STATIC_METHOD
126
		    .set(CompilerOptions.MethodCanBePotentiallyStatic);
144
		    .set(CompilerOptions.MethodCanBePotentiallyStatic);
145
		RESOURCE
146
			.set(CompilerOptions.PotentiallyUnclosedCloseable)
147
			.set(CompilerOptions.ExplicitlyClosedAutoCloseable);
127
		String suppressRawWhenUnchecked = System.getProperty("suppressRawWhenUnchecked"); //$NON-NLS-1$
148
		String suppressRawWhenUnchecked = System.getProperty("suppressRawWhenUnchecked"); //$NON-NLS-1$
128
		if (suppressRawWhenUnchecked != null && "true".equalsIgnoreCase(suppressRawWhenUnchecked)) { //$NON-NLS-1$
149
		if (suppressRawWhenUnchecked != null && "true".equalsIgnoreCase(suppressRawWhenUnchecked)) { //$NON-NLS-1$
129
			UNCHECKED.set(CompilerOptions.RawTypeReference);
150
			UNCHECKED.set(CompilerOptions.RawTypeReference);
(-)a/org.eclipse.jdt.core/compiler/org/eclipse/jdt/internal/compiler/impl/ReferenceContext.java (-1 / +5 lines)
Lines 1-5 Link Here
1
/*******************************************************************************
1
/*******************************************************************************
2
 * Copyright (c) 2000, 2009 IBM Corporation and others.
2
 * Copyright (c) 2000, 2012 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 18-23 Link Here
18
18
19
import org.eclipse.jdt.core.compiler.CategorizedProblem;
19
import org.eclipse.jdt.core.compiler.CategorizedProblem;
20
import org.eclipse.jdt.internal.compiler.CompilationResult;
20
import org.eclipse.jdt.internal.compiler.CompilationResult;
21
import org.eclipse.jdt.internal.compiler.ast.CompilationUnitDeclaration;
21
22
22
public interface ReferenceContext {
23
public interface ReferenceContext {
23
24
Lines 25-31 Link Here
25
26
26
	CompilationResult compilationResult();
27
	CompilationResult compilationResult();
27
28
29
	CompilationUnitDeclaration getCompilationUnitDeclaration();
30
28
	boolean hasErrors();
31
	boolean hasErrors();
29
32
30
	void tagAsHavingErrors();
33
	void tagAsHavingErrors();
34
31
}
35
}
(-)a/org.eclipse.jdt.core/compiler/org/eclipse/jdt/internal/compiler/lookup/AnnotationBinding.java (-10 / +5 lines)
Lines 1-5 Link Here
1
/*******************************************************************************
1
/*******************************************************************************
2
 * Copyright (c) 2000, 2011 IBM Corporation and others.
2
 * Copyright (c) 2000, 2012 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 54-64 Link Here
54
		count++;
54
		count++;
55
	if ((annotationTagBits & TagBits.AnnotationSafeVarargs) != 0)
55
	if ((annotationTagBits & TagBits.AnnotationSafeVarargs) != 0)
56
		count++;
56
		count++;
57
	if ((annotationTagBits & TagBits.AnnotationPostConstruct) != 0)
57
	if (count == 0) {
58
		count++;
58
		// this is possible if bits were set for null annotations
59
	if ((annotationTagBits & TagBits.AnnotationPreDestroy) != 0)
59
		return recordedAnnotations;
60
		count++;
60
	}
61
	// count must be different from 0
62
61
63
	int index = recordedAnnotations.length;
62
	int index = recordedAnnotations.length;
64
	AnnotationBinding[] result = new AnnotationBinding[index + count];
63
	AnnotationBinding[] result = new AnnotationBinding[index + count];
Lines 81-90 Link Here
81
		result[index++] = buildMarkerAnnotationForMemberType(TypeConstants.JAVA_LANG_INVOKE_METHODHANDLE_$_POLYMORPHICSIGNATURE, env);
80
		result[index++] = buildMarkerAnnotationForMemberType(TypeConstants.JAVA_LANG_INVOKE_METHODHANDLE_$_POLYMORPHICSIGNATURE, env);
82
	if ((annotationTagBits & TagBits.AnnotationSafeVarargs) != 0)
81
	if ((annotationTagBits & TagBits.AnnotationSafeVarargs) != 0)
83
		result[index++] = buildMarkerAnnotation(TypeConstants.JAVA_LANG_SAFEVARARGS, env);
82
		result[index++] = buildMarkerAnnotation(TypeConstants.JAVA_LANG_SAFEVARARGS, env);
84
	if ((annotationTagBits & TagBits.AnnotationPostConstruct) != 0)
85
		result[index++] = buildMarkerAnnotation(TypeConstants.JAVAX_ANNOTATION_POSTCONSTRUCT, env);
86
	if ((annotationTagBits & TagBits.AnnotationPreDestroy) != 0)
87
		result[index++] = buildMarkerAnnotation(TypeConstants.JAVAX_ANNOTATION_PREDESTROY, env);
88
	return result;
83
	return result;
89
}
84
}
90
85
(-)a/org.eclipse.jdt.core/compiler/org/eclipse/jdt/internal/compiler/lookup/BinaryTypeBinding.java (-39 / +228 lines)
Lines 1-5 Link Here
1
/*******************************************************************************
1
/*******************************************************************************
2
 * Copyright (c) 2000, 2011 IBM Corporation and others.
2
 * Copyright (c) 2000, 2012 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 - Contributions for
11
 *								bug 349326 - [1.7] new warning for missing try-with-resources
12
 *								bug 186342 - [compiler][null] Using annotations for null checking
13
 *								bug 364890 - BinaryTypeBinding should use char constants from Util
14
 *								bug 365387 - [compiler][null] bug 186342: Issues to follow up post review and verification.
15
 *								bug 358903 - Filter practically unimportant resource leak warnings
16
 *								bug 365531 - [compiler][null] investigate alternative strategy for internally encoding nullness defaults
10
 *******************************************************************************/
17
 *******************************************************************************/
11
package org.eclipse.jdt.internal.compiler.lookup;
18
package org.eclipse.jdt.internal.compiler.lookup;
12
19
Lines 15-23 Link Here
15
import org.eclipse.jdt.core.compiler.CharOperation;
22
import org.eclipse.jdt.core.compiler.CharOperation;
16
import org.eclipse.jdt.internal.compiler.classfmt.ClassFileConstants;
23
import org.eclipse.jdt.internal.compiler.classfmt.ClassFileConstants;
17
import org.eclipse.jdt.internal.compiler.env.*;
24
import org.eclipse.jdt.internal.compiler.env.*;
25
import org.eclipse.jdt.internal.compiler.impl.BooleanConstant;
18
import org.eclipse.jdt.internal.compiler.impl.Constant;
26
import org.eclipse.jdt.internal.compiler.impl.Constant;
19
import org.eclipse.jdt.internal.compiler.problem.AbortCompilation;
27
import org.eclipse.jdt.internal.compiler.problem.AbortCompilation;
20
import org.eclipse.jdt.internal.compiler.util.SimpleLookupTable;
28
import org.eclipse.jdt.internal.compiler.util.SimpleLookupTable;
29
import org.eclipse.jdt.internal.compiler.util.Util;
21
30
22
/*
31
/*
23
Not all fields defined by this type are initialized when it is created.
32
Not all fields defined by this type are initialized when it is created.
Lines 155-161 Link Here
155
	   of generics.
164
	   of generics.
156
	 */
165
	 */
157
	char[] typeSignature = binaryType.getGenericSignature();
166
	char[] typeSignature = binaryType.getGenericSignature();
158
	this.typeVariables = typeSignature != null && typeSignature.length > 0 && typeSignature[0] == '<'
167
	this.typeVariables = typeSignature != null && typeSignature.length > 0 && typeSignature[0] == Util.C_GENERIC_START
159
		? null // is initialized in cachePartsFrom (called from LookupEnvironment.createBinaryTypeFrom())... must set to null so isGenericType() answers true
168
		? null // is initialized in cachePartsFrom (called from LookupEnvironment.createBinaryTypeFrom())... must set to null so isGenericType() answers true
160
		: Binding.NO_TYPE_VARIABLES;
169
		: Binding.NO_TYPE_VARIABLES;
161
170
Lines 178-184 Link Here
178
		// attempt to find the enclosing type if it exists in the cache (otherwise - resolve it when requested)
187
		// attempt to find the enclosing type if it exists in the cache (otherwise - resolve it when requested)
179
		this.enclosingType = environment.getTypeFromConstantPoolName(enclosingTypeName, 0, -1, true, null /* could not be missing */); // pretend parameterized to avoid raw
188
		this.enclosingType = environment.getTypeFromConstantPoolName(enclosingTypeName, 0, -1, true, null /* could not be missing */); // pretend parameterized to avoid raw
180
		this.tagBits |= TagBits.MemberTypeMask;   // must be a member type not a top-level or local type
189
		this.tagBits |= TagBits.MemberTypeMask;   // must be a member type not a top-level or local type
181
		this.tagBits |= 	TagBits.HasUnresolvedEnclosingType;
190
		this.tagBits |= TagBits.HasUnresolvedEnclosingType;
182
		if (enclosingType().isStrictfp())
191
		if (enclosingType().isStrictfp())
183
			this.modifiers |= ClassFileConstants.AccStrictfp;
192
			this.modifiers |= ClassFileConstants.AccStrictfp;
184
		if (enclosingType().isDeprecated())
193
		if (enclosingType().isDeprecated())
Lines 283-292 Link Here
283
			int size = memberTypeStructures.length;
292
			int size = memberTypeStructures.length;
284
			if (size > 0) {
293
			if (size > 0) {
285
				this.memberTypes = new ReferenceBinding[size];
294
				this.memberTypes = new ReferenceBinding[size];
286
				for (int i = 0; i < size; i++)
295
				for (int i = 0; i < size; i++) {
287
					// attempt to find each member type if it exists in the cache (otherwise - resolve it when requested)
296
					// attempt to find each member type if it exists in the cache (otherwise - resolve it when requested)
288
					this.memberTypes[i] = this.environment.getTypeFromConstantPoolName(memberTypeStructures[i].getName(), 0, -1, false, null /* could not be missing */);
297
					this.memberTypes[i] = this.environment.getTypeFromConstantPoolName(memberTypeStructures[i].getName(), 0, -1, false, null /* could not be missing */);
289
				this.tagBits |= 	TagBits.HasUnresolvedMemberTypes;
298
				}
299
				this.tagBits |= TagBits.HasUnresolvedMemberTypes;
290
			}
300
			}
291
		}
301
		}
292
302
Lines 304-310 Link Here
304
		if (typeSignature != null) {
314
		if (typeSignature != null) {
305
			// ClassSignature = ParameterPart(optional) super_TypeSignature interface_signature
315
			// ClassSignature = ParameterPart(optional) super_TypeSignature interface_signature
306
			wrapper = new SignatureWrapper(typeSignature);
316
			wrapper = new SignatureWrapper(typeSignature);
307
			if (wrapper.signature[wrapper.start] == '<') {
317
			if (wrapper.signature[wrapper.start] == Util.C_GENERIC_START) {
308
				// ParameterPart = '<' ParameterSignature(s) '>'
318
				// ParameterPart = '<' ParameterSignature(s) '>'
309
				wrapper.start++; // skip '<'
319
				wrapper.start++; // skip '<'
310
				this.typeVariables = createTypeVariables(wrapper, true, missingTypeNames);
320
				this.typeVariables = createTypeVariables(wrapper, true, missingTypeNames);
Lines 358-363 Link Here
358
				types.toArray(this.superInterfaces);
368
				types.toArray(this.superInterfaces);
359
				this.tagBits |= TagBits.HasUnresolvedSuperinterfaces;
369
				this.tagBits |= TagBits.HasUnresolvedSuperinterfaces;
360
			}
370
			}
371
		}
372
373
		// need type annotations before processing methods (for @NonNullByDefault)
374
		if (this.environment.globalOptions.isAnnotationBasedNullAnalysisEnabled) {
375
			scanTypeForNullDefaultAnnotation(binaryType);
361
		}
376
		}
362
377
363
		if (needFieldsAndMethods) {
378
		if (needFieldsAndMethods) {
Lines 459-469 Link Here
459
		int numOfParams = 0;
474
		int numOfParams = 0;
460
		char nextChar;
475
		char nextChar;
461
		int index = 0; // first character is always '(' so skip it
476
		int index = 0; // first character is always '(' so skip it
462
		while ((nextChar = methodDescriptor[++index]) != ')') {
477
		while ((nextChar = methodDescriptor[++index]) != Util.C_PARAM_END) {
463
			if (nextChar != '[') {
478
			if (nextChar != Util.C_ARRAY) {
464
				numOfParams++;
479
				numOfParams++;
465
				if (nextChar == 'L')
480
				if (nextChar == Util.C_RESOLVED)
466
					while ((nextChar = methodDescriptor[++index]) != ';'){/*empty*/}
481
					while ((nextChar = methodDescriptor[++index]) != Util.C_NAME_END){/*empty*/}
467
			}
482
			}
468
		}
483
		}
469
484
Lines 487-495 Link Here
487
			index = 1;
502
			index = 1;
488
			int end = 0;   // first character is always '(' so skip it
503
			int end = 0;   // first character is always '(' so skip it
489
			for (int i = 0; i < numOfParams; i++) {
504
			for (int i = 0; i < numOfParams; i++) {
490
				while ((nextChar = methodDescriptor[++end]) == '['){/*empty*/}
505
				while ((nextChar = methodDescriptor[++end]) == Util.C_ARRAY){/*empty*/}
491
				if (nextChar == 'L')
506
				if (nextChar == Util.C_RESOLVED)
492
					while ((nextChar = methodDescriptor[++end]) != ';'){/*empty*/}
507
					while ((nextChar = methodDescriptor[++end]) != Util.C_NAME_END){/*empty*/}
493
508
494
				if (i >= startIndex) {   // skip the synthetic arg if necessary
509
				if (i >= startIndex) {   // skip the synthetic arg if necessary
495
					parameters[i - startIndex] = this.environment.getTypeFromSignature(methodDescriptor, index, end, false, this, missingTypeNames);
510
					parameters[i - startIndex] = this.environment.getTypeFromSignature(methodDescriptor, index, end, false, this, missingTypeNames);
Lines 518-524 Link Here
518
		methodModifiers |= ExtraCompilerModifiers.AccGenericSignature;
533
		methodModifiers |= ExtraCompilerModifiers.AccGenericSignature;
519
		// MethodTypeSignature = ParameterPart(optional) '(' TypeSignatures ')' return_typeSignature ['^' TypeSignature (optional)]
534
		// MethodTypeSignature = ParameterPart(optional) '(' TypeSignatures ')' return_typeSignature ['^' TypeSignature (optional)]
520
		SignatureWrapper wrapper = new SignatureWrapper(methodSignature, use15specifics);
535
		SignatureWrapper wrapper = new SignatureWrapper(methodSignature, use15specifics);
521
		if (wrapper.signature[wrapper.start] == '<') {
536
		if (wrapper.signature[wrapper.start] == Util.C_GENERIC_START) {
522
			// <A::Ljava/lang/annotation/Annotation;>(Ljava/lang/Class<TA;>;)TA;
537
			// <A::Ljava/lang/annotation/Annotation;>(Ljava/lang/Class<TA;>;)TA;
523
			// ParameterPart = '<' ParameterSignature(s) '>'
538
			// ParameterPart = '<' ParameterSignature(s) '>'
524
			wrapper.start++; // skip '<'
539
			wrapper.start++; // skip '<'
Lines 526-538 Link Here
526
			wrapper.start++; // skip '>'
541
			wrapper.start++; // skip '>'
527
		}
542
		}
528
543
529
		if (wrapper.signature[wrapper.start] == '(') {
544
		if (wrapper.signature[wrapper.start] == Util.C_PARAM_START) {
530
			wrapper.start++; // skip '('
545
			wrapper.start++; // skip '('
531
			if (wrapper.signature[wrapper.start] == ')') {
546
			if (wrapper.signature[wrapper.start] == Util.C_PARAM_END) {
532
				wrapper.start++; // skip ')'
547
				wrapper.start++; // skip ')'
533
			} else {
548
			} else {
534
				java.util.ArrayList types = new java.util.ArrayList(2);
549
				java.util.ArrayList types = new java.util.ArrayList(2);
535
				while (wrapper.signature[wrapper.start] != ')')
550
				while (wrapper.signature[wrapper.start] != Util.C_PARAM_END)
536
					types.add(this.environment.getTypeFromTypeSignature(wrapper, typeVars, this, missingTypeNames));
551
					types.add(this.environment.getTypeFromTypeSignature(wrapper, typeVars, this, missingTypeNames));
537
				wrapper.start++; // skip ')'
552
				wrapper.start++; // skip ')'
538
				int numParam = types.size();
553
				int numParam = types.size();
Lines 549-561 Link Here
549
		// always retrieve return type (for constructors, its V for void - will be ignored)
564
		// always retrieve return type (for constructors, its V for void - will be ignored)
550
		returnType = this.environment.getTypeFromTypeSignature(wrapper, typeVars, this, missingTypeNames);
565
		returnType = this.environment.getTypeFromTypeSignature(wrapper, typeVars, this, missingTypeNames);
551
566
552
		if (!wrapper.atEnd() && wrapper.signature[wrapper.start] == '^') {
567
		if (!wrapper.atEnd() && wrapper.signature[wrapper.start] == Util.C_EXCEPTION_START) {
553
			// attempt to find each exception if it exists in the cache (otherwise - resolve it when requested)
568
			// attempt to find each exception if it exists in the cache (otherwise - resolve it when requested)
554
			java.util.ArrayList types = new java.util.ArrayList(2);
569
			java.util.ArrayList types = new java.util.ArrayList(2);
555
			do {
570
			do {
556
				wrapper.start++; // skip '^'
571
				wrapper.start++; // skip '^'
557
				types.add(this.environment.getTypeFromTypeSignature(wrapper, typeVars, this, missingTypeNames));
572
				types.add(this.environment.getTypeFromTypeSignature(wrapper, typeVars, this, missingTypeNames));
558
			} while (!wrapper.atEnd() && wrapper.signature[wrapper.start] == '^');
573
			} while (!wrapper.atEnd() && wrapper.signature[wrapper.start] == Util.C_EXCEPTION_START);
559
			exceptions = new ReferenceBinding[types.size()];
574
			exceptions = new ReferenceBinding[types.size()];
560
			types.toArray(exceptions);
575
			types.toArray(exceptions);
561
		} else { // get the exceptions the old way
576
		} else { // get the exceptions the old way
Lines 587-592 Link Here
587
	// fixup the declaring element of the type variable
602
	// fixup the declaring element of the type variable
588
	for (int i = 0, length = typeVars.length; i < length; i++)
603
	for (int i = 0, length = typeVars.length; i < length; i++)
589
		typeVars[i].declaringElement = result;
604
		typeVars[i].declaringElement = result;
605
606
	scanMethodForNullAnnotation(method, result);
607
590
	return result;
608
	return result;
591
}
609
}
592
610
Lines 610-616 Link Here
610
				total--;
628
				total--;
611
			} else if (iClinit == -1) {
629
			} else if (iClinit == -1) {
612
				char[] methodName = method.getSelector();
630
				char[] methodName = method.getSelector();
613
				if (methodName.length == 8 && methodName[0] == '<') {
631
				if (methodName.length == 8 && methodName[0] == Util.C_GENERIC_START) {
614
					// discard <clinit>
632
					// discard <clinit>
615
					iClinit = i;
633
					iClinit = i;
616
					total--;
634
					total--;
Lines 655-675 Link Here
655
	createVariables: {
673
	createVariables: {
656
		for (int i = 1; i < length; i++) {
674
		for (int i = 1; i < length; i++) {
657
			switch(typeSignature[i]) {
675
			switch(typeSignature[i]) {
658
				case '<' :
676
				case Util.C_GENERIC_START :
659
					depth++;
677
					depth++;
660
					break;
678
					break;
661
				case '>' :
679
				case Util.C_GENERIC_END :
662
					if (--depth < 0)
680
					if (--depth < 0)
663
						break createVariables;
681
						break createVariables;
664
					break;
682
					break;
665
				case ';' :
683
				case Util.C_NAME_END :
666
					if ((depth == 0) && (i +1 < length) && (typeSignature[i+1] != ':'))
684
					if ((depth == 0) && (i +1 < length) && (typeSignature[i+1] != Util.C_COLON))
667
						pendingVariable = true;
685
						pendingVariable = true;
668
					break;
686
					break;
669
				default:
687
				default:
670
					if (pendingVariable) {
688
					if (pendingVariable) {
671
						pendingVariable = false;
689
						pendingVariable = false;
672
						int colon = CharOperation.indexOf(':', typeSignature, i);
690
						int colon = CharOperation.indexOf(Util.C_COLON, typeSignature, i);
673
						char[] variableName = CharOperation.subarray(typeSignature, i, colon);
691
						char[] variableName = CharOperation.subarray(typeSignature, i, colon);
674
						variables.add(new TypeVariableBinding(variableName, this, rank++, this.environment));
692
						variables.add(new TypeVariableBinding(variableName, this, rank++, this.environment));
675
					}
693
					}
Lines 722-728 Link Here
722
740
723
private MethodBinding findMethod(char[] methodDescriptor, char[][][] missingTypeNames) {
741
private MethodBinding findMethod(char[] methodDescriptor, char[][][] missingTypeNames) {
724
	int index = -1;
742
	int index = -1;
725
	while (methodDescriptor[++index] != '(') {
743
	while (methodDescriptor[++index] != Util.C_PARAM_START) {
726
		// empty
744
		// empty
727
	}
745
	}
728
	char[] selector = new char[index];
746
	char[] selector = new char[index];
Lines 731-741 Link Here
731
	int numOfParams = 0;
749
	int numOfParams = 0;
732
	char nextChar;
750
	char nextChar;
733
	int paramStart = index;
751
	int paramStart = index;
734
	while ((nextChar = methodDescriptor[++index]) != ')') {
752
	while ((nextChar = methodDescriptor[++index]) != Util.C_PARAM_END) {
735
		if (nextChar != '[') {
753
		if (nextChar != Util.C_ARRAY) {
736
			numOfParams++;
754
			numOfParams++;
737
			if (nextChar == 'L')
755
			if (nextChar == Util.C_RESOLVED)
738
				while ((nextChar = methodDescriptor[++index]) != ';'){/*empty*/}
756
				while ((nextChar = methodDescriptor[++index]) != Util.C_NAME_END){/*empty*/}
739
		}
757
		}
740
	}
758
	}
741
	if (numOfParams > 0) {
759
	if (numOfParams > 0) {
Lines 743-751 Link Here
743
		index = paramStart + 1;
761
		index = paramStart + 1;
744
		int end = paramStart; // first character is always '(' so skip it
762
		int end = paramStart; // first character is always '(' so skip it
745
		for (int i = 0; i < numOfParams; i++) {
763
		for (int i = 0; i < numOfParams; i++) {
746
			while ((nextChar = methodDescriptor[++end]) == '['){/*empty*/}
764
			while ((nextChar = methodDescriptor[++end]) == Util.C_ARRAY){/*empty*/}
747
			if (nextChar == 'L')
765
			if (nextChar == Util.C_RESOLVED)
748
				while ((nextChar = methodDescriptor[++end]) != ';'){/*empty*/}
766
				while ((nextChar = methodDescriptor[++end]) != Util.C_NAME_END){/*empty*/}
749
767
750
			TypeBinding param = this.environment.getTypeFromSignature(methodDescriptor, index, end, false, this, missingTypeNames);
768
			TypeBinding param = this.environment.getTypeFromSignature(methodDescriptor, index, end, false, this, missingTypeNames);
751
			if (param instanceof UnresolvedReferenceBinding) {
769
			if (param instanceof UnresolvedReferenceBinding) {
Lines 971-984 Link Here
971
	variable.resolve();
989
	variable.resolve();
972
	return variable;
990
	return variable;
973
}
991
}
992
public boolean hasTypeBit(int bit) {
993
	// ensure hierarchy is resolved, which will propagate bits down to us
994
	boolean wasToleratingMissingTypeProcessingAnnotations = this.environment.mayTolerateMissingType;
995
	this.environment.mayTolerateMissingType = true;
996
	try {
997
		superclass();
998
		superInterfaces();
999
	} finally {
1000
		this.environment.mayTolerateMissingType = wasToleratingMissingTypeProcessingAnnotations;
1001
	}
1002
	return (this.typeBits & bit) != 0;
1003
}
974
private void initializeTypeVariable(TypeVariableBinding variable, TypeVariableBinding[] existingVariables, SignatureWrapper wrapper, char[][][] missingTypeNames) {
1004
private void initializeTypeVariable(TypeVariableBinding variable, TypeVariableBinding[] existingVariables, SignatureWrapper wrapper, char[][][] missingTypeNames) {
975
	// ParameterSignature = Identifier ':' TypeSignature
1005
	// ParameterSignature = Identifier ':' TypeSignature
976
	//   or Identifier ':' TypeSignature(optional) InterfaceBound(s)
1006
	//   or Identifier ':' TypeSignature(optional) InterfaceBound(s)
977
	// InterfaceBound = ':' TypeSignature
1007
	// InterfaceBound = ':' TypeSignature
978
	int colon = CharOperation.indexOf(':', wrapper.signature, wrapper.start);
1008
	int colon = CharOperation.indexOf(Util.C_COLON, wrapper.signature, wrapper.start);
979
	wrapper.start = colon + 1; // skip name + ':'
1009
	wrapper.start = colon + 1; // skip name + ':'
980
	ReferenceBinding type, firstBound = null;
1010
	ReferenceBinding type, firstBound = null;
981
	if (wrapper.signature[wrapper.start] == ':') {
1011
	if (wrapper.signature[wrapper.start] == Util.C_COLON) {
982
		type = this.environment.getResolvedType(TypeConstants.JAVA_LANG_OBJECT, null);
1012
		type = this.environment.getResolvedType(TypeConstants.JAVA_LANG_OBJECT, null);
983
	} else {
1013
	} else {
984
		TypeBinding typeFromTypeSignature = this.environment.getTypeFromTypeSignature(wrapper, existingVariables, this, missingTypeNames);
1014
		TypeBinding typeFromTypeSignature = this.environment.getTypeFromTypeSignature(wrapper, existingVariables, this, missingTypeNames);
Lines 996-1007 Link Here
996
	variable.superclass = type;
1026
	variable.superclass = type;
997
1027
998
	ReferenceBinding[] bounds = null;
1028
	ReferenceBinding[] bounds = null;
999
	if (wrapper.signature[wrapper.start] == ':') {
1029
	if (wrapper.signature[wrapper.start] == Util.C_COLON) {
1000
		java.util.ArrayList types = new java.util.ArrayList(2);
1030
		java.util.ArrayList types = new java.util.ArrayList(2);
1001
		do {
1031
		do {
1002
			wrapper.start++; // skip ':'
1032
			wrapper.start++; // skip ':'
1003
			types.add(this.environment.getTypeFromTypeSignature(wrapper, existingVariables, this, missingTypeNames));
1033
			types.add(this.environment.getTypeFromTypeSignature(wrapper, existingVariables, this, missingTypeNames));
1004
		} while (wrapper.signature[wrapper.start] == ':');
1034
		} while (wrapper.signature[wrapper.start] == Util.C_COLON);
1005
		bounds = new ReferenceBinding[types.size()];
1035
		bounds = new ReferenceBinding[types.size()];
1006
		types.toArray(bounds);
1036
		types.toArray(bounds);
1007
	}
1037
	}
Lines 1128-1133 Link Here
1128
	}
1158
	}
1129
	return this.storedAnnotations;
1159
	return this.storedAnnotations;
1130
}
1160
}
1161
void scanMethodForNullAnnotation(IBinaryMethod method, MethodBinding methodBinding) {
1162
	if (!this.environment.globalOptions.isAnnotationBasedNullAnalysisEnabled)
1163
		return;
1164
	char[][] nullableAnnotationName = this.environment.getNullableAnnotationName();
1165
	char[][] nonNullAnnotationName = this.environment.getNonNullAnnotationName();
1166
	char[][] nonNullByDefaultAnnotationName = this.environment.getNonNullByDefaultAnnotationName();
1167
	if (nullableAnnotationName == null || nonNullAnnotationName == null || nonNullByDefaultAnnotationName == null)
1168
		return; // not well-configured to use null annotations
1169
1170
	int currentDefault = NO_NULL_DEFAULT;
1171
	if ((this.tagBits & TagBits.AnnotationNonNullByDefault) != 0) {
1172
		currentDefault = NONNULL_BY_DEFAULT;
1173
	} else if ((this.tagBits & TagBits.AnnotationNullUnspecifiedByDefault) != 0) {
1174
		currentDefault = NULL_UNSPECIFIED_BY_DEFAULT;
1175
	}
1176
1177
	// return:
1178
	IBinaryAnnotation[] annotations = method.getAnnotations();
1179
	boolean explicitNullness = false;
1180
	if (annotations != null) {
1181
		for (int i = 0; i < annotations.length; i++) {
1182
			char[] annotationTypeName = annotations[i].getTypeName();
1183
			if (annotationTypeName[0] != Util.C_RESOLVED)
1184
				continue;
1185
			char[][] typeName = CharOperation.splitOn('/', annotationTypeName, 1, annotationTypeName.length-1); // cut of leading 'L' and trailing ';'
1186
			if (CharOperation.equals(typeName, nonNullByDefaultAnnotationName)) {
1187
				methodBinding.tagBits |= TagBits.AnnotationNonNullByDefault;
1188
				currentDefault = NONNULL_BY_DEFAULT;
1189
			}
1190
			if (!explicitNullness && CharOperation.equals(typeName, nonNullAnnotationName)) {
1191
				methodBinding.tagBits |= TagBits.AnnotationNonNull;
1192
				explicitNullness = true;
1193
			}
1194
			if (!explicitNullness && CharOperation.equals(typeName, nullableAnnotationName)) {
1195
				methodBinding.tagBits |= TagBits.AnnotationNullable;
1196
				explicitNullness = true;
1197
			}
1198
		}
1199
	}
1200
	if (!explicitNullness && currentDefault == NONNULL_BY_DEFAULT) {
1201
		methodBinding.tagBits |= TagBits.AnnotationNonNull;
1202
	}
1203
1204
	// parameters:
1205
	TypeBinding[] parameters = methodBinding.parameters;
1206
	int numVisibleParams = parameters.length;
1207
	int numParamAnnotations = method.getAnnotatedParametersCount();
1208
	if (numParamAnnotations > 0 || currentDefault == NONNULL_BY_DEFAULT) {
1209
		for (int j = 0; j < numVisibleParams; j++) {
1210
			explicitNullness = false;
1211
			if (numParamAnnotations > 0) {
1212
				int startIndex = numParamAnnotations - numVisibleParams;
1213
				IBinaryAnnotation[] paramAnnotations = method.getParameterAnnotations(j+startIndex);
1214
				if (paramAnnotations != null) {
1215
					for (int i = 0; i < paramAnnotations.length; i++) {
1216
						char[] annotationTypeName = paramAnnotations[i].getTypeName();
1217
						if (annotationTypeName[0] != Util.C_RESOLVED)
1218
							continue;
1219
						char[][] typeName = CharOperation.splitOn('/', annotationTypeName, 1, annotationTypeName.length-1); // cut of leading 'L' and trailing ';'
1220
						if (CharOperation.equals(typeName, nonNullAnnotationName)) {
1221
							if (methodBinding.parameterNonNullness == null)
1222
								methodBinding.parameterNonNullness = new Boolean[numVisibleParams];
1223
							methodBinding.parameterNonNullness[j] = Boolean.TRUE;
1224
							explicitNullness = true;
1225
							break;
1226
						} else if (CharOperation.equals(typeName, nullableAnnotationName)) {
1227
							if (methodBinding.parameterNonNullness == null)
1228
								methodBinding.parameterNonNullness = new Boolean[numVisibleParams];
1229
							methodBinding.parameterNonNullness[j] = Boolean.FALSE;
1230
							explicitNullness = true;
1231
							break;
1232
						}
1233
					}
1234
				}
1235
			}
1236
			if (!explicitNullness && currentDefault == NONNULL_BY_DEFAULT) {
1237
				if (methodBinding.parameterNonNullness == null)
1238
					methodBinding.parameterNonNullness = new Boolean[numVisibleParams];
1239
				methodBinding.parameterNonNullness[j] = Boolean.TRUE;
1240
			}
1241
		}
1242
	}
1243
}
1244
void scanTypeForNullDefaultAnnotation(IBinaryType binaryType) {
1245
	char[][] nonNullByDefaultAnnotationName = this.environment.getNonNullByDefaultAnnotationName();
1246
	if (nonNullByDefaultAnnotationName == null)
1247
		return; // not well-configured to use null annotations
1248
1249
	IBinaryAnnotation[] annotations = binaryType.getAnnotations();
1250
	if (annotations != null) {
1251
		long annotationBit = 0L;
1252
		int nullness = NO_NULL_DEFAULT;
1253
		int length = annotations.length;
1254
		for (int i = 0; i < length; i++) {
1255
			char[] annotationTypeName = annotations[i].getTypeName();
1256
			if (annotationTypeName[0] != Util.C_RESOLVED)
1257
				continue;
1258
			char[][] typeName = CharOperation.splitOn('/', annotationTypeName, 1, annotationTypeName.length-1); // cut of leading 'L' and trailing ';'
1259
			if (CharOperation.equals(typeName, nonNullByDefaultAnnotationName)) {
1260
				IBinaryElementValuePair[] elementValuePairs = annotations[i].getElementValuePairs();
1261
				if (elementValuePairs != null && elementValuePairs.length == 1) {
1262
					Object value = elementValuePairs[0].getValue();
1263
					if (value instanceof BooleanConstant
1264
						&& !((BooleanConstant)value).booleanValue())
1265
					{
1266
						// parameter is 'false': this means we cancel defaults from outer scopes:
1267
						annotationBit = TagBits.AnnotationNullUnspecifiedByDefault;
1268
						nullness = NULL_UNSPECIFIED_BY_DEFAULT;
1269
						break;
1270
					}
1271
				}
1272
				annotationBit = TagBits.AnnotationNonNullByDefault;
1273
				nullness = NONNULL_BY_DEFAULT;
1274
				break;
1275
			}
1276
		}
1277
		if (annotationBit != 0L) {
1278
			this.tagBits |= annotationBit;
1279
			if (CharOperation.equals(this.sourceName(), TypeConstants.PACKAGE_INFO_NAME))
1280
				this.getPackage().defaultNullness = nullness;
1281
		} else {
1282
			switch (this.getPackage().defaultNullness) {
1283
				case NONNULL_BY_DEFAULT : 
1284
					this.tagBits |= TagBits.AnnotationNonNullByDefault;
1285
					break;
1286
				case NULL_UNSPECIFIED_BY_DEFAULT :
1287
					this.tagBits |= TagBits.AnnotationNullUnspecifiedByDefault;
1288
					break;
1289
			}
1290
		}
1291
	}
1292
}
1293
1131
/* Answer the receiver's superclass... null if the receiver is Object or an interface.
1294
/* Answer the receiver's superclass... null if the receiver is Object or an interface.
1132
*
1295
*
1133
* NOTE: superclass of a binary type is resolved when needed
1296
* NOTE: superclass of a binary type is resolved when needed
Lines 1139-1146 Link Here
1139
	// finish resolving the type
1302
	// finish resolving the type
1140
	this.superclass = (ReferenceBinding) resolveType(this.superclass, this.environment, true /* raw conversion */);
1303
	this.superclass = (ReferenceBinding) resolveType(this.superclass, this.environment, true /* raw conversion */);
1141
	this.tagBits &= ~TagBits.HasUnresolvedSuperclass;
1304
	this.tagBits &= ~TagBits.HasUnresolvedSuperclass;
1142
	if (this.superclass.problemId() == ProblemReasons.NotFound)
1305
	if (this.superclass.problemId() == ProblemReasons.NotFound) {
1143
		this.tagBits |= TagBits.HierarchyHasProblems; // propagate type inconsistency
1306
		this.tagBits |= TagBits.HierarchyHasProblems; // propagate type inconsistency
1307
	} else {
1308
		// make super-type resolving recursive for propagating typeBits downwards
1309
		boolean wasToleratingMissingTypeProcessingAnnotations = this.environment.mayTolerateMissingType;
1310
		this.environment.mayTolerateMissingType = true; // https://bugs.eclipse.org/bugs/show_bug.cgi?id=360164
1311
		try {
1312
			this.superclass.superclass();
1313
			this.superclass.superInterfaces();
1314
		} finally {
1315
			this.environment.mayTolerateMissingType = wasToleratingMissingTypeProcessingAnnotations;
1316
		}
1317
	}
1318
	this.typeBits |= (this.superclass.typeBits & TypeIds.InheritableBits);
1319
	if ((this.typeBits & (TypeIds.BitAutoCloseable|TypeIds.BitCloseable)) != 0) // avoid the side-effects of hasTypeBit()! 
1320
		this.typeBits |= applyCloseableWhitelists();
1144
	return this.superclass;
1321
	return this.superclass;
1145
}
1322
}
1146
// NOTE: superInterfaces of binary types are resolved when needed
1323
// NOTE: superInterfaces of binary types are resolved when needed
Lines 1150-1157 Link Here
1150
1327
1151
	for (int i = this.superInterfaces.length; --i >= 0;) {
1328
	for (int i = this.superInterfaces.length; --i >= 0;) {
1152
		this.superInterfaces[i] = (ReferenceBinding) resolveType(this.superInterfaces[i], this.environment, true /* raw conversion */);
1329
		this.superInterfaces[i] = (ReferenceBinding) resolveType(this.superInterfaces[i], this.environment, true /* raw conversion */);
1153
		if (this.superInterfaces[i].problemId() == ProblemReasons.NotFound)
1330
		if (this.superInterfaces[i].problemId() == ProblemReasons.NotFound) {
1154
			this.tagBits |= TagBits.HierarchyHasProblems; // propagate type inconsistency
1331
			this.tagBits |= TagBits.HierarchyHasProblems; // propagate type inconsistency
1332
		} else {
1333
			// make super-type resolving recursive for propagating typeBits downwards
1334
			boolean wasToleratingMissingTypeProcessingAnnotations = this.environment.mayTolerateMissingType;
1335
			this.environment.mayTolerateMissingType = true; // https://bugs.eclipse.org/bugs/show_bug.cgi?id=360164
1336
			try {
1337
				this.superInterfaces[i].superclass();
1338
				this.superInterfaces[i].superInterfaces();
1339
			} finally {
1340
				this.environment.mayTolerateMissingType = wasToleratingMissingTypeProcessingAnnotations;
1341
			}	
1342
		}
1343
		this.typeBits |= (this.superInterfaces[i].typeBits & TypeIds.InheritableBits);
1155
	}
1344
	}
1156
	this.tagBits &= ~TagBits.HasUnresolvedSuperinterfaces;
1345
	this.tagBits &= ~TagBits.HasUnresolvedSuperinterfaces;
1157
	return this.superInterfaces;
1346
	return this.superInterfaces;
(-)a/org.eclipse.jdt.core/compiler/org/eclipse/jdt/internal/compiler/lookup/Binding.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
11
 *								bug 365531 - [compiler][null] investigate alternative strategy for internally encoding nullness defaults
10
 *******************************************************************************/
12
 *******************************************************************************/
11
package org.eclipse.jdt.internal.compiler.lookup;
13
package org.eclipse.jdt.internal.compiler.lookup;
12
14
Lines 48-53 Link Here
48
	public static final MethodBinding[] UNINITIALIZED_METHODS = new MethodBinding[0];
50
	public static final MethodBinding[] UNINITIALIZED_METHODS = new MethodBinding[0];
49
	public static final ReferenceBinding[] UNINITIALIZED_REFERENCE_TYPES = new ReferenceBinding[0];
51
	public static final ReferenceBinding[] UNINITIALIZED_REFERENCE_TYPES = new ReferenceBinding[0];
50
52
53
	// Nullness defaults:
54
	public static final int NO_NULL_DEFAULT = 0;
55
	public static final int NULL_UNSPECIFIED_BY_DEFAULT = 1;
56
	public static final int NONNULL_BY_DEFAULT = 2;
57
51
	/*
58
	/*
52
	* Answer the receiver's binding type from Binding.BindingID.
59
	* Answer the receiver's binding type from Binding.BindingID.
53
	*/
60
	*/
(-)a/org.eclipse.jdt.core/compiler/org/eclipse/jdt/internal/compiler/lookup/BlockScope.java (-1 / +162 lines)
Lines 1-5 Link Here
1
/*******************************************************************************
1
/*******************************************************************************
2
 * Copyright (c) 2000, 2011 IBM Corporation and others.
2
 * Copyright (c) 2000, 2012 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-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 - Contributions for
11
 *     							bug 349326 - [1.7] new warning for missing try-with-resources
12
 *								bug 359334 - Analysis for resource leak warnings does not consider exceptions as method exit points
13
 *								bug 358903 - Filter practically unimportant resource leak warnings
14
 *								bug 368546 - [compiler][resource] Avoid remaining false positives found when compiling the Eclipse SDK
15
 *								bug 370639 - [compiler][resource] restore the default for resource leak warnings
10
 *******************************************************************************/
16
 *******************************************************************************/
11
package org.eclipse.jdt.internal.compiler.lookup;
17
package org.eclipse.jdt.internal.compiler.lookup;
18
19
import java.util.ArrayList;
20
import java.util.HashSet;
21
import java.util.List;
22
import java.util.Set;
12
23
13
import org.eclipse.jdt.core.compiler.CharOperation;
24
import org.eclipse.jdt.core.compiler.CharOperation;
14
import org.eclipse.jdt.internal.compiler.ast.*;
25
import org.eclipse.jdt.internal.compiler.ast.*;
15
import org.eclipse.jdt.internal.compiler.classfmt.ClassFileConstants;
26
import org.eclipse.jdt.internal.compiler.classfmt.ClassFileConstants;
16
import org.eclipse.jdt.internal.compiler.codegen.CodeStream;
27
import org.eclipse.jdt.internal.compiler.codegen.CodeStream;
28
import org.eclipse.jdt.internal.compiler.flow.FlowContext;
29
import org.eclipse.jdt.internal.compiler.flow.FlowInfo;
17
import org.eclipse.jdt.internal.compiler.impl.Constant;
30
import org.eclipse.jdt.internal.compiler.impl.Constant;
18
import org.eclipse.jdt.internal.compiler.problem.ProblemReporter;
31
import org.eclipse.jdt.internal.compiler.problem.ProblemReporter;
19
32
Lines 957-960 Link Here
957
		}
970
		}
958
	}
971
	}
959
}
972
}
973
974
private List trackingVariables; // can be null if no resources are tracked
975
/** Used only during analyseCode and only for checking if a resource was closed in a finallyBlock. */
976
public FlowInfo finallyInfo;
977
/**
978
 * Register a tracking variable and compute its id.
979
 */
980
public int registerTrackingVariable(FakedTrackingVariable fakedTrackingVariable) {
981
	if (this.trackingVariables == null)
982
		this.trackingVariables = new ArrayList(3);
983
	this.trackingVariables.add(fakedTrackingVariable);
984
	MethodScope outerMethodScope = outerMostMethodScope();
985
	return outerMethodScope.analysisIndex++;
986
}
987
/** When are no longer interested in this tracking variable - remove it. */
988
public void removeTrackingVar(FakedTrackingVariable trackingVariable) {
989
	if (trackingVariable.innerTracker != null) {
990
		removeTrackingVar(trackingVariable.innerTracker);
991
		trackingVariable.innerTracker = null;
992
	}
993
	if (this.trackingVariables != null)
994
		if (this.trackingVariables.remove(trackingVariable))
995
			return;
996
	if (this.parent instanceof BlockScope)
997
		((BlockScope)this.parent).removeTrackingVar(trackingVariable);
998
}
999
/** Unregister a wrapper resource without affecting its inner. */
1000
public void pruneWrapperTrackingVar(FakedTrackingVariable trackingVariable) {
1001
	this.trackingVariables.remove(trackingVariable);
1002
}
1003
/**
1004
 * At the end of a block check the closing-status of all tracked closeables that are declared in this block.
1005
 * Also invoked when entering unreachable code.
1006
 */
1007
public void checkUnclosedCloseables(FlowInfo flowInfo, FlowContext flowContext, ASTNode location, BlockScope locationScope) {
1008
	if (!compilerOptions().analyseResourceLeaks) return;
1009
	if (this.trackingVariables == null) {
1010
		// at a method return we also consider enclosing scopes
1011
		if (location != null && this.parent instanceof BlockScope)
1012
			((BlockScope) this.parent).checkUnclosedCloseables(flowInfo, flowContext, location, locationScope);
1013
		return;
1014
	}
1015
	if (location != null && flowInfo.reachMode() != 0) return;
1016
1017
	FakedTrackingVariable returnVar = (location instanceof ReturnStatement) ?
1018
			FakedTrackingVariable.getCloseTrackingVariable(((ReturnStatement)location).expression) : null;
1019
1020
	Set varSet = new HashSet(this.trackingVariables);
1021
	FakedTrackingVariable trackingVar;
1022
	// pick one outer-most variable from the set at a time
1023
	while ((trackingVar = FakedTrackingVariable.pickVarForReporting(varSet, this, location != null)) != null) {
1024
1025
		if (returnVar != null && trackingVar.isResourceBeingReturned(returnVar)) {
1026
			continue;
1027
		}
1028
1029
		if (location != null && trackingVar.hasDefinitelyNoResource(flowInfo)) {
1030
			continue; // reporting against a specific location, there is no resource at this flow, don't complain
1031
		}
1032
1033
		if (location != null && flowContext != null && flowContext.recordExitAgainstResource(this, flowInfo, trackingVar, location)) {
1034
			continue; // handled by the flow context
1035
		}
1036
1037
		// compute the most specific null status for this resource,
1038
		int status = trackingVar.findMostSpecificStatus(flowInfo, this, locationScope);
1039
		
1040
		if (status == FlowInfo.NULL) {
1041
			// definitely unclosed: highest priority
1042
			reportResourceLeak(trackingVar, location, status);
1043
			continue;
1044
		}
1045
		if (location == null) // at end of block and not definitely unclosed
1046
		{
1047
			// problems at specific locations: medium priority
1048
			if (trackingVar.reportRecordedErrors(this, status)) // ... report previously recorded errors
1049
				continue;
1050
		} 
1051
		if (status == FlowInfo.POTENTIALLY_NULL) {
1052
			// potentially unclosed: lower priority
1053
			reportResourceLeak(trackingVar, location, status);
1054
		} else if (status == FlowInfo.NON_NULL) {
1055
			// properly closed but not managed by t-w-r: lowest priority 
1056
			if (environment().globalOptions.complianceLevel >= ClassFileConstants.JDK1_7)
1057
				trackingVar.reportExplicitClosing(problemReporter());
1058
		}
1059
	}
1060
	if (location == null) {
1061
		// when leaving this block dispose off all tracking variables:
1062
		for (int i=0; i<this.localIndex; i++)
1063
			this.locals[i].closeTracker = null;		
1064
		this.trackingVariables = null;
1065
	} else {
1066
		int size = this.trackingVariables.size();
1067
		for (int i=0; i<size; i++) {
1068
			FakedTrackingVariable tracker = (FakedTrackingVariable) this.trackingVariables.get(0);
1069
			tracker.resetReportingBits();
1070
		}
1071
	}
1072
}
1073
1074
private void reportResourceLeak(FakedTrackingVariable trackingVar, ASTNode location, int nullStatus) {
1075
	if (location != null)
1076
		trackingVar.recordErrorLocation(location, nullStatus);
1077
	else
1078
		trackingVar.reportError(problemReporter(), null, nullStatus);
1079
}
1080
1081
/** 
1082
 * If one branch of an if-else closes any AutoCloseable resource, and if the same
1083
 * resource is known to be null on the other branch mark it as closed, too,
1084
 * so that merging both branches indicates that the resource is always closed.
1085
 * Example:
1086
 *	FileReader fr1 = null;
1087
 *	try {\n" +
1088
 *      fr1 = new FileReader(someFile);" + 
1089
 *		fr1.read(buf);\n" + 
1090
 *	} finally {\n" + 
1091
 *		if (fr1 != null)\n" +
1092
 *           try {\n" +
1093
 *               fr1.close();\n" +
1094
 *           } catch (IOException e) {
1095
 *              // do nothing 
1096
 *           }
1097
 *      // after this if statement fr1 is definitely not leaked 
1098
 *	}
1099
 */
1100
public void correlateTrackingVarsIfElse(FlowInfo thenFlowInfo, FlowInfo elseFlowInfo) {
1101
	if (this.trackingVariables != null) {
1102
		for (int i=0; i<this.trackingVariables.size(); i++) {
1103
			FakedTrackingVariable trackingVar = (FakedTrackingVariable) this.trackingVariables.get(i);
1104
			if (trackingVar.originalBinding == null)
1105
				continue;
1106
			if (   thenFlowInfo.isDefinitelyNonNull(trackingVar.binding)			// closed in then branch
1107
				&& elseFlowInfo.isDefinitelyNull(trackingVar.originalBinding))		// null in else branch
1108
			{
1109
				elseFlowInfo.markAsDefinitelyNonNull(trackingVar.binding);			// -> always closed
1110
			}
1111
			else if (   elseFlowInfo.isDefinitelyNonNull(trackingVar.binding)		// closed in else branch
1112
					 && thenFlowInfo.isDefinitelyNull(trackingVar.originalBinding))	// null in then branch
1113
			{
1114
				thenFlowInfo.markAsDefinitelyNonNull(trackingVar.binding);			// -> always closed
1115
			}
1116
		}
1117
	}
1118
	if (this.parent instanceof BlockScope)
1119
		((BlockScope) this.parent).correlateTrackingVarsIfElse(thenFlowInfo, elseFlowInfo);
1120
}
960
}
1121
}
(-)a/org.eclipse.jdt.core/compiler/org/eclipse/jdt/internal/compiler/lookup/ClassScope.java (-1 / +8 lines)
Lines 1-5 Link Here
1
/*******************************************************************************
1
/*******************************************************************************
2
 * Copyright (c) 2000, 2011 IBM Corporation and others.
2
 * Copyright (c) 2000, 2012 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 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
15
 *     						Bug 358903 - Filter practically unimportant resource leak warnings
14
 *******************************************************************************/
16
 *******************************************************************************/
15
package org.eclipse.jdt.internal.compiler.lookup;
17
package org.eclipse.jdt.internal.compiler.lookup;
16
18
Lines 908-913 Link Here
908
			} else {
910
			} else {
909
				// only want to reach here when no errors are reported
911
				// only want to reach here when no errors are reported
910
				sourceType.superclass = superclass;
912
				sourceType.superclass = superclass;
913
				sourceType.typeBits |= (superclass.typeBits & TypeIds.InheritableBits);
914
				// further analysis against white lists for the unlikely case we are compiling java.io.*:
915
				if ((sourceType.typeBits & (TypeIds.BitAutoCloseable|TypeIds.BitCloseable)) != 0)
916
					sourceType.typeBits |= sourceType.applyCloseableWhitelists();
911
				return true;
917
				return true;
912
			}
918
			}
913
		}
919
		}
Lines 1023-1028 Link Here
1023
				noProblems &= superInterfaceRef.resolvedType.isValidBinding();
1029
				noProblems &= superInterfaceRef.resolvedType.isValidBinding();
1024
			}
1030
			}
1025
			// only want to reach here when no errors are reported
1031
			// only want to reach here when no errors are reported
1032
			sourceType.typeBits |= (superInterface.typeBits & TypeIds.InheritableBits);
1026
			interfaceBindings[count++] = superInterface;
1033
			interfaceBindings[count++] = superInterface;
1027
		}
1034
		}
1028
		// hold onto all correctly resolved superinterfaces
1035
		// hold onto all correctly resolved superinterfaces
(-)a/org.eclipse.jdt.core/compiler/org/eclipse/jdt/internal/compiler/lookup/CompilationUnitScope.java (-76 / +151 lines)
Lines 25-30 Link Here
25
	public char[][] currentPackageName;
25
	public char[][] currentPackageName;
26
	public PackageBinding fPackage;
26
	public PackageBinding fPackage;
27
	public ImportBinding[] imports;
27
	public ImportBinding[] imports;
28
	public int importPtr;
28
	public HashtableOfObject typeOrPackageCache; // used in Scope.getTypeOrPackage()
29
	public HashtableOfObject typeOrPackageCache; // used in Scope.getTypeOrPackage()
29
30
30
	public SourceTypeBinding[] topLevelTypes;
31
	public SourceTypeBinding[] topLevelTypes;
Lines 37-42 Link Here
37
38
38
	HashtableOfType constantPoolNameUsage;
39
	HashtableOfType constantPoolNameUsage;
39
	private int captureID = 1;
40
	private int captureID = 1;
41
	
42
	private ImportBinding[] tempImports;	// to keep a record of resolved imports while traversing all in faultInImports()
40
	
43
	
41
public CompilationUnitScope(CompilationUnitDeclaration unit, LookupEnvironment environment) {
44
public CompilationUnitScope(CompilationUnitDeclaration unit, LookupEnvironment environment) {
42
	super(COMPILATION_UNIT_SCOPE, null);
45
	super(COMPILATION_UNIT_SCOPE, null);
Lines 328-337 Link Here
328
			break;
331
			break;
329
		}
332
		}
330
	}
333
	}
331
	ImportBinding[] resolvedImports = new ImportBinding[numberOfImports];
334
	this.tempImports = new ImportBinding[numberOfImports];
332
	resolvedImports[0] = getDefaultImports()[0];
335
	this.tempImports[0] = getDefaultImports()[0];
333
	int index = 1;
336
	this.importPtr = 1;
334
337
	
335
	// keep static imports with normal imports until there is a reason to split them up
338
	// keep static imports with normal imports until there is a reason to split them up
336
	// on demand imports continue to be packages & types. need to check on demand type imports for fields/methods
339
	// on demand imports continue to be packages & types. need to check on demand type imports for fields/methods
337
	// single imports change from being just types to types or fields
340
	// single imports change from being just types to types or fields
Lines 340-347 Link Here
340
		char[][] compoundName = importReference.tokens;
343
		char[][] compoundName = importReference.tokens;
341
344
342
		// skip duplicates or imports of the current package
345
		// skip duplicates or imports of the current package
343
		for (int j = 0; j < index; j++) {
346
		for (int j = 0; j < this.importPtr; j++) {
344
			ImportBinding resolved = resolvedImports[j];
347
			ImportBinding resolved = this.tempImports[j];
345
			if (resolved.onDemand == ((importReference.bits & ASTNode.OnDemand) != 0) && resolved.isStatic() == importReference.isStatic()) {
348
			if (resolved.onDemand == ((importReference.bits & ASTNode.OnDemand) != 0) && resolved.isStatic() == importReference.isStatic()) {
346
				if (CharOperation.equals(compoundName, resolved.compoundName)) {
349
				if (CharOperation.equals(compoundName, resolved.compoundName)) {
347
					problemReporter().unusedImport(importReference); // since skipped, must be reported now
350
					problemReporter().unusedImport(importReference); // since skipped, must be reported now
Lines 364-370 Link Here
364
				problemReporter().cannotImportPackage(importReference);
367
				problemReporter().cannotImportPackage(importReference);
365
				continue nextImport;
368
				continue nextImport;
366
			}
369
			}
367
			resolvedImports[index++] = new ImportBinding(compoundName, true, importBinding, importReference);
370
			recordImportBinding(new ImportBinding(compoundName, true, importBinding, importReference));
368
		} else {
371
		} else {
369
			Binding importBinding = findSingleImport(compoundName, Binding.TYPE | Binding.FIELD | Binding.METHOD, importReference.isStatic());
372
			Binding importBinding = findSingleImport(compoundName, Binding.TYPE | Binding.FIELD | Binding.METHOD, importReference.isStatic());
370
			if (!importBinding.isValidBinding()) {
373
			if (!importBinding.isValidBinding()) {
Lines 379-459 Link Here
379
				problemReporter().cannotImportPackage(importReference);
382
				problemReporter().cannotImportPackage(importReference);
380
				continue nextImport;
383
				continue nextImport;
381
			}
384
			}
382
			ReferenceBinding conflictingType = null;
385
			// all the code here which checks for valid bindings have been moved to the method 
383
			if (importBinding instanceof MethodBinding) {
386
			// checkAndRecordImportBinding() since bug 361327
384
				conflictingType = (ReferenceBinding) getType(compoundName, compoundName.length);
387
			if(checkAndRecordImportBinding(importBinding, typesBySimpleNames, importReference, compoundName) == -1)
385
				if (!conflictingType.isValidBinding() || (importReference.isStatic() && !conflictingType.isStatic()))
388
				continue nextImport;
386
					conflictingType = null;
389
			if (importReference.isStatic()) {
387
			}
390
				// look for more static bindings being imported by single static import(bug 361327).
388
			// collisions between an imported static field & a type should be checked according to spec... but currently not by javac
391
				// findSingleImport() finds fields first, followed by method and then type
389
			if (importBinding instanceof ReferenceBinding || conflictingType != null) {
392
				// So if a type is found, no fields and methods are available anyway
390
				ReferenceBinding referenceBinding = conflictingType == null ? (ReferenceBinding) importBinding : conflictingType;
393
				// similarly when method is found, type may be available but no field available for sure
391
				ReferenceBinding typeToCheck = referenceBinding.problemId() == ProblemReasons.Ambiguous
394
				if (importBinding.kind() == Binding.FIELD) {
392
					? ((ProblemReferenceBinding) referenceBinding).closestMatch
395
					checkMoreStaticBindings(compoundName, typesBySimpleNames, Binding.TYPE | Binding.METHOD, importReference);		
393
					: referenceBinding;
396
				} else if (importBinding.kind() == Binding.METHOD) {
394
				if (importReference.isTypeUseDeprecated(typeToCheck, this))
397
					checkMoreStaticBindings(compoundName, typesBySimpleNames, Binding.TYPE, importReference);
395
					problemReporter().deprecatedType(typeToCheck, importReference);
396
397
				ReferenceBinding existingType = typesBySimpleNames.get(compoundName[compoundName.length - 1]);
398
				if (existingType != null) {
399
					// duplicate test above should have caught this case, but make sure
400
					if (existingType == referenceBinding) {
401
						// https://bugs.eclipse.org/bugs/show_bug.cgi?id=302865
402
						// Check all resolved imports to see if this import qualifies as a duplicate
403
						for (int j = 0; j < index; j++) {
404
							ImportBinding resolved = resolvedImports[j];
405
							if (resolved instanceof ImportConflictBinding) {
406
								ImportConflictBinding importConflictBinding = (ImportConflictBinding) resolved;
407
								if (importConflictBinding.conflictingTypeBinding == referenceBinding) {
408
									if (!importReference.isStatic()) {
409
										// resolved is implicitly static
410
										problemReporter().duplicateImport(importReference);
411
										resolvedImports[index++] = new ImportBinding(compoundName, false, importBinding, importReference);
412
									}
413
								}
414
							} else if (resolved.resolvedImport == referenceBinding) {
415
								if (importReference.isStatic() != resolved.isStatic()) {
416
									problemReporter().duplicateImport(importReference);
417
									resolvedImports[index++] = new ImportBinding(compoundName, false, importBinding, importReference);
418
								}
419
							}
420
						}
421
						continue nextImport;
422
					}
423
					// either the type collides with a top level type or another imported type
424
					for (int j = 0, length = this.topLevelTypes.length; j < length; j++) {
425
						if (CharOperation.equals(this.topLevelTypes[j].sourceName, existingType.sourceName)) {
426
							problemReporter().conflictingImport(importReference);
427
							continue nextImport;
428
						}
429
					}
430
					problemReporter().duplicateImport(importReference);
431
					continue nextImport;
432
				}
433
				typesBySimpleNames.put(compoundName[compoundName.length - 1], referenceBinding);
434
			} else if (importBinding instanceof FieldBinding) {
435
				for (int j = 0; j < index; j++) {
436
					ImportBinding resolved = resolvedImports[j];
437
					// find other static fields with the same name
438
					if (resolved.isStatic() && resolved.resolvedImport instanceof FieldBinding && importBinding != resolved.resolvedImport) {
439
						if (CharOperation.equals(compoundName[compoundName.length - 1], resolved.compoundName[resolved.compoundName.length - 1])) {
440
							problemReporter().duplicateImport(importReference);
441
							continue nextImport;
442
						}
443
					}
444
				}
398
				}
445
			}
399
			}
446
			resolvedImports[index++] = conflictingType == null
447
				? new ImportBinding(compoundName, false, importBinding, importReference)
448
				: new ImportConflictBinding(compoundName, importBinding, conflictingType, importReference);
449
		}
400
		}
450
	}
401
	}
451
402
452
	// shrink resolvedImports... only happens if an error was reported
403
	// shrink resolvedImports... only happens if an error was reported
453
	if (resolvedImports.length > index)
404
	if (this.tempImports.length > this.importPtr)
454
		System.arraycopy(resolvedImports, 0, resolvedImports = new ImportBinding[index], 0, index);
405
		System.arraycopy(this.tempImports, 0, this.tempImports = new ImportBinding[this.importPtr], 0, this.importPtr);
455
	this.imports = resolvedImports;
406
	this.imports = this.tempImports;
456
457
	int length = this.imports.length;
407
	int length = this.imports.length;
458
	this.typeOrPackageCache = new HashtableOfObject(length);
408
	this.typeOrPackageCache = new HashtableOfObject(length);
459
	for (int i = 0; i < length; i++) {
409
	for (int i = 0; i < length; i++) {
Lines 840-843 Link Here
840
	for (int i = 0, length = this.topLevelTypes.length; i < length; i++)
790
	for (int i = 0, length = this.topLevelTypes.length; i < length; i++)
841
		this.topLevelTypes[i].verifyMethods(verifier);
791
		this.topLevelTypes[i].verifyMethods(verifier);
842
}
792
}
793
private void recordImportBinding(ImportBinding bindingToAdd) {
794
	if (this.tempImports.length == this.importPtr) {
795
		System.arraycopy(this.tempImports, 0, (this.tempImports = new ImportBinding[this.importPtr + 1]), 0, this.importPtr);
796
	}
797
	this.tempImports[this.importPtr++] = bindingToAdd;
798
}
799
/**
800
 * Checks additional bindings (methods or types) imported from a single static import. 
801
 * Method is tried first, followed by type. If found, records them.
802
 * If in the process, import is flagged as duplicate, -1 is returned.
803
 * @param compoundName
804
 * @param typesBySimpleNames
805
 * @param mask
806
 * @param importReference
807
 */
808
private void checkMoreStaticBindings(
809
		char[][] compoundName, 
810
		HashtableOfType typesBySimpleNames, 
811
		int mask,
812
		ImportReference importReference) {
813
	Binding importBinding = findSingleStaticImport(compoundName, mask);
814
	if (!importBinding.isValidBinding()) {
815
		// only continue if the same kind's ambiguous binding is returned
816
		// may have found an ambiguous type when looking for field or method. Don't continue in that case
817
		if (importBinding.problemId() == ProblemReasons.Ambiguous) {
818
			// keep it unless a duplicate can be found below
819
			checkAndRecordImportBinding(importBinding, typesBySimpleNames, importReference, compoundName);
820
		}
821
	} else {
822
		checkAndRecordImportBinding(importBinding, typesBySimpleNames, importReference, compoundName);
823
	}
824
	if (((mask & Binding.METHOD) != 0) && (importBinding.kind() == Binding.METHOD)) {
825
		// found method
826
		// type is left to be looked for
827
		// reset METHOD bit to enable lookup for only type
828
		mask &= ~Binding.METHOD;
829
		// now search for a type binding
830
		checkMoreStaticBindings(compoundName, typesBySimpleNames, mask, importReference);
831
	}
832
}
833
/**
834
 * Checks for duplicates. If all ok, records the importBinding
835
 * returns -1 when this import is flagged as duplicate.
836
 * @param importBinding
837
 * @param typesBySimpleNames
838
 * @param importReference
839
 * @param compoundName
840
 * @return -1 when this import is flagged as duplicate, importPtr otherwise.
841
 */
842
private int checkAndRecordImportBinding(
843
		Binding importBinding, 
844
		HashtableOfType typesBySimpleNames, 
845
		ImportReference importReference,
846
		char[][] compoundName) {
847
	ReferenceBinding conflictingType = null;
848
	if (importBinding instanceof MethodBinding) {
849
		conflictingType = (ReferenceBinding) getType(compoundName, compoundName.length);
850
		if (!conflictingType.isValidBinding() || (importReference.isStatic() && !conflictingType.isStatic()))
851
			conflictingType = null;
852
	}
853
	// collisions between an imported static field & a type should be checked according to spec... but currently not by javac
854
	if (importBinding instanceof ReferenceBinding || conflictingType != null) {
855
		ReferenceBinding referenceBinding = conflictingType == null ? (ReferenceBinding) importBinding : conflictingType;
856
		ReferenceBinding typeToCheck = referenceBinding.problemId() == ProblemReasons.Ambiguous
857
			? ((ProblemReferenceBinding) referenceBinding).closestMatch
858
			: referenceBinding;
859
		if (importReference.isTypeUseDeprecated(typeToCheck, this))
860
			problemReporter().deprecatedType(typeToCheck, importReference);
861
862
		ReferenceBinding existingType = typesBySimpleNames.get(compoundName[compoundName.length - 1]);
863
		if (existingType != null) {
864
			// duplicate test above should have caught this case, but make sure
865
			if (existingType == referenceBinding) {
866
				// https://bugs.eclipse.org/bugs/show_bug.cgi?id=302865
867
				// Check all resolved imports to see if this import qualifies as a duplicate
868
				for (int j = 0; j < this.importPtr; j++) {
869
					ImportBinding resolved = this.tempImports[j];
870
					if (resolved instanceof ImportConflictBinding) {
871
						ImportConflictBinding importConflictBinding = (ImportConflictBinding) resolved;
872
						if (importConflictBinding.conflictingTypeBinding == referenceBinding) {
873
							if (!importReference.isStatic()) {
874
								// resolved is implicitly static
875
								problemReporter().duplicateImport(importReference);
876
								recordImportBinding(new ImportBinding(compoundName, false, importBinding, importReference));
877
							}
878
						}
879
					} else if (resolved.resolvedImport == referenceBinding) {
880
						if (importReference.isStatic() != resolved.isStatic()) {
881
							problemReporter().duplicateImport(importReference);
882
							recordImportBinding(new ImportBinding(compoundName, false, importBinding, importReference));
883
						}
884
					}
885
				}
886
				return -1;
887
			}
888
			// either the type collides with a top level type or another imported type
889
			for (int j = 0, length = this.topLevelTypes.length; j < length; j++) {
890
				if (CharOperation.equals(this.topLevelTypes[j].sourceName, existingType.sourceName)) {
891
					problemReporter().conflictingImport(importReference);
892
					return -1;
893
				}
894
			}
895
			problemReporter().duplicateImport(importReference);
896
			return -1;
897
		}
898
		typesBySimpleNames.put(compoundName[compoundName.length - 1], referenceBinding);
899
	} else if (importBinding instanceof FieldBinding) {
900
		for (int j = 0; j < this.importPtr; j++) {
901
			ImportBinding resolved = this.tempImports[j];
902
			// find other static fields with the same name
903
			if (resolved.isStatic() && resolved.resolvedImport instanceof FieldBinding && importBinding != resolved.resolvedImport) {
904
				if (CharOperation.equals(compoundName[compoundName.length - 1], resolved.compoundName[resolved.compoundName.length - 1])) {
905
					problemReporter().duplicateImport(importReference);
906
					return -1;
907
				}
908
			}
909
		}
910
	}
911
	if (conflictingType == null) {
912
		recordImportBinding(new ImportBinding(compoundName, false, importBinding, importReference));
913
	} else {
914
		recordImportBinding(new ImportConflictBinding(compoundName, importBinding, conflictingType, importReference));
915
	}
916
	return this.importPtr;
917
}
843
}
918
}
(-)a/org.eclipse.jdt.core/compiler/org/eclipse/jdt/internal/compiler/lookup/LocalTypeBinding.java (-1 / +14 lines)
Lines 1-5 Link Here
1
/*******************************************************************************
1
/*******************************************************************************
2
 * Copyright (c) 2000, 2010 IBM Corporation and others.
2
 * Copyright (c) 2000, 2012 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-18 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 365662 - [compiler][null] warn on contradictory and redundant null annotations
10
 *******************************************************************************/
11
 *******************************************************************************/
11
package org.eclipse.jdt.internal.compiler.lookup;
12
package org.eclipse.jdt.internal.compiler.lookup;
12
13
13
import org.eclipse.jdt.core.compiler.CharOperation;
14
import org.eclipse.jdt.core.compiler.CharOperation;
14
import org.eclipse.jdt.internal.compiler.ast.ASTNode;
15
import org.eclipse.jdt.internal.compiler.ast.ASTNode;
15
import org.eclipse.jdt.internal.compiler.ast.AbstractMethodDeclaration;
16
import org.eclipse.jdt.internal.compiler.ast.AbstractMethodDeclaration;
17
import org.eclipse.jdt.internal.compiler.ast.Annotation;
16
import org.eclipse.jdt.internal.compiler.ast.CaseStatement;
18
import org.eclipse.jdt.internal.compiler.ast.CaseStatement;
17
import org.eclipse.jdt.internal.compiler.ast.TypeDeclaration;
19
import org.eclipse.jdt.internal.compiler.ast.TypeDeclaration;
18
import org.eclipse.jdt.internal.compiler.ast.TypeReference;
20
import org.eclipse.jdt.internal.compiler.ast.TypeReference;
Lines 85-90 Link Here
85
	return this.superclass; // default answer
87
	return this.superclass; // default answer
86
}
88
}
87
89
90
protected void checkRedundantNullnessDefaultRecurse(ASTNode location, Annotation[] annotations, long annotationTagBits) {
91
	long outerDefault = this.enclosingMethod != null ? this.enclosingMethod.tagBits & ((TagBits.AnnotationNonNullByDefault|TagBits.AnnotationNullUnspecifiedByDefault)) : 0;
92
	if (outerDefault != 0) {
93
		if (outerDefault == annotationTagBits) {
94
			this.scope.problemReporter().nullDefaultAnnotationIsRedundant(location, annotations, this.enclosingMethod);
95
		}
96
		return;
97
	}
98
	super.checkRedundantNullnessDefaultRecurse(location, annotations, annotationTagBits);
99
}
100
88
public char[] computeUniqueKey(boolean isLeaf) {
101
public char[] computeUniqueKey(boolean isLeaf) {
89
	char[] outerKey = outermostEnclosingType().computeUniqueKey(isLeaf);
102
	char[] outerKey = outermostEnclosingType().computeUniqueKey(isLeaf);
90
	int semicolon = CharOperation.lastIndexOf(';', outerKey);
103
	int semicolon = CharOperation.lastIndexOf(';', outerKey);
(-)a/org.eclipse.jdt.core/compiler/org/eclipse/jdt/internal/compiler/lookup/LocalVariableBinding.java (-7 / +15 lines)
Lines 4-13 Link Here
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
6
 * http://www.eclipse.org/legal/epl-v10.html
6
 * http://www.eclipse.org/legal/epl-v10.html
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
13
 *								bug 186342 - [compiler][null] Using annotations for null checking
11
 *******************************************************************************/
14
 *******************************************************************************/
12
package org.eclipse.jdt.internal.compiler.lookup;
15
package org.eclipse.jdt.internal.compiler.lookup;
13
16
Lines 15-20 Link Here
15
import org.eclipse.jdt.internal.compiler.ast.ASTNode;
18
import org.eclipse.jdt.internal.compiler.ast.ASTNode;
16
import org.eclipse.jdt.internal.compiler.ast.AbstractMethodDeclaration;
19
import org.eclipse.jdt.internal.compiler.ast.AbstractMethodDeclaration;
17
import org.eclipse.jdt.internal.compiler.ast.Annotation;
20
import org.eclipse.jdt.internal.compiler.ast.Annotation;
21
import org.eclipse.jdt.internal.compiler.ast.FakedTrackingVariable;
18
import org.eclipse.jdt.internal.compiler.ast.LocalDeclaration;
22
import org.eclipse.jdt.internal.compiler.ast.LocalDeclaration;
19
import org.eclipse.jdt.internal.compiler.ast.TypeDeclaration;
23
import org.eclipse.jdt.internal.compiler.ast.TypeDeclaration;
20
import org.eclipse.jdt.internal.compiler.impl.Constant;
24
import org.eclipse.jdt.internal.compiler.impl.Constant;
Lines 34-39 Link Here
34
38
35
	public int[] initializationPCs;
39
	public int[] initializationPCs;
36
	public int initializationCount = 0;
40
	public int initializationCount = 0;
41
42
	public FakedTrackingVariable closeTracker; // track closing of instances of type AutoCloseable, maybe null
37
43
38
	// for synthetic local variables
44
	// for synthetic local variables
39
	// if declaration slot is not positionned, the variable will not be listed in attribute
45
	// if declaration slot is not positionned, the variable will not be listed in attribute
Lines 153-159 Link Here
153
					annotations = new AnnotationBinding[length];
159
					annotations = new AnnotationBinding[length];
154
					for (int i = 0; i < length; i++)
160
					for (int i = 0; i < length; i++)
155
						annotations[i] = new AnnotationBinding(annotationNodes[i]);
161
						annotations[i] = new AnnotationBinding(annotationNodes[i]);
156
					setAnnotations(annotations);
162
					setAnnotations(annotations, this.declaringScope);
157
				}
163
				}
158
			}
164
			}
159
		}
165
		}
Lines 207-216 Link Here
207
		this.initializationCount++;
213
		this.initializationCount++;
208
	}
214
	}
209
215
210
	public void setAnnotations(AnnotationBinding[] annotations) {
216
	public void setAnnotations(AnnotationBinding[] annotations, Scope scope) {
211
		if (this.declaringScope == null) return;
217
		// note: we don's use this.declaringScope because we might be called before Scope.addLocalVariable(this)
212
218
		//       which is where this.declaringScope is set.
213
		SourceTypeBinding sourceType = this.declaringScope.enclosingSourceType();
219
		if (scope == null)
220
			return;
221
		SourceTypeBinding sourceType = scope.enclosingSourceType();
214
		if (sourceType != null)
222
		if (sourceType != null)
215
			sourceType.storeAnnotations(this, annotations);
223
			sourceType.storeAnnotations(this, annotations);
216
	}
224
	}
(-)a/org.eclipse.jdt.core/compiler/org/eclipse/jdt/internal/compiler/lookup/LookupEnvironment.java (-3 / +31 lines)
Lines 1-5 Link Here
1
/*******************************************************************************
1
/*******************************************************************************
2
 * Copyright (c) 2000, 2011 IBM Corporation and others.
2
 * Copyright (c) 2000, 2012 IBM Corporation and others.
3
 * All rights reserved. This program and the accompanying materials
3
 * All rights reserved. This program and the accompanying materials
4
 * are made available under the terms of the Eclipse Public License v1.0
4
 * are made available under the terms of the Eclipse Public License v1.0
5
 * which accompanies this distribution, and is available at
5
 * which accompanies this distribution, and is available at
Lines 7-13 Link Here
7
 *
7
 *
8
 * Contributors:
8
 * Contributors:
9
 *     IBM Corporation - initial API and implementation
9
 *     IBM Corporation - initial API and implementation
10
 *     Stephan Herrmann - contribution for bug 337868 - [compiler][model] incomplete support for package-info.java when using SearchableEnvironment
10
 *     Stephan Herrmann - contributions for
11
 *     							bug 337868 - [compiler][model] incomplete support for package-info.java when using SearchableEnvironment
12
 *								bug 186342 - [compiler][null] Using annotations for null checking
13
 *								bug 365531 - [compiler][null] investigate alternative strategy for internally encoding nullness defaults
11
 *******************************************************************************/
14
 *******************************************************************************/
12
package org.eclipse.jdt.internal.compiler.lookup;
15
package org.eclipse.jdt.internal.compiler.lookup;
13
16
Lines 74-79 Link Here
74
	private ArrayList missingTypes;
77
	private ArrayList missingTypes;
75
	Set typesBeingConnected;
78
	Set typesBeingConnected;
76
	public boolean isProcessingAnnotations = false;
79
	public boolean isProcessingAnnotations = false;
80
	public boolean mayTolerateMissingType = false;
81
82
	PackageBinding nullableAnnotationPackage;			// the package supposed to contain the Nullable annotation type
83
	PackageBinding nonnullAnnotationPackage;			// the package supposed to contain the NonNull annotation type
84
	PackageBinding nonnullByDefaultAnnotationPackage;	// the package supposed to contain the NonNullByDefault annotation type
77
85
78
	final static int BUILD_FIELDS_AND_METHODS = 4;
86
	final static int BUILD_FIELDS_AND_METHODS = 4;
79
	final static int BUILD_TYPE_HIERARCHY = 1;
87
	final static int BUILD_TYPE_HIERARCHY = 1;
Lines 82-87 Link Here
82
90
83
	static final ProblemPackageBinding TheNotFoundPackage = new ProblemPackageBinding(CharOperation.NO_CHAR, NotFound);
91
	static final ProblemPackageBinding TheNotFoundPackage = new ProblemPackageBinding(CharOperation.NO_CHAR, NotFound);
84
	static final ProblemReferenceBinding TheNotFoundType = new ProblemReferenceBinding(CharOperation.NO_CHAR_CHAR, null, NotFound);
92
	static final ProblemReferenceBinding TheNotFoundType = new ProblemReferenceBinding(CharOperation.NO_CHAR_CHAR, null, NotFound);
93
85
94
86
public LookupEnvironment(ITypeRequestor typeRequestor, CompilerOptions globalOptions, ProblemReporter problemReporter, INameEnvironment nameEnvironment) {
95
public LookupEnvironment(ITypeRequestor typeRequestor, CompilerOptions globalOptions, ProblemReporter problemReporter, INameEnvironment nameEnvironment) {
87
	this.typeRequestor = typeRequestor;
96
	this.typeRequestor = typeRequestor;
Lines 1072-1077 Link Here
1072
	return packageBinding.getType0(compoundName[compoundName.length - 1]);
1081
	return packageBinding.getType0(compoundName[compoundName.length - 1]);
1073
}
1082
}
1074
1083
1084
public char[][] getNullableAnnotationName() {
1085
	return this.globalOptions.nullableAnnotationName;
1086
}
1087
1088
public char[][] getNonNullAnnotationName() {
1089
	return this.globalOptions.nonNullAnnotationName;
1090
}
1091
1092
public char[][] getNonNullByDefaultAnnotationName() {
1093
	return this.globalOptions.nonNullByDefaultAnnotationName;
1094
}
1095
1075
/* Answer the top level package named name if it exists in the cache.
1096
/* Answer the top level package named name if it exists in the cache.
1076
* Answer theNotFoundPackage if it could not be resolved the first time
1097
* Answer theNotFoundPackage if it could not be resolved the first time
1077
* it was looked up, otherwise answer null.
1098
* it was looked up, otherwise answer null.
Lines 1194-1200 Link Here
1194
		packageBinding.addType(binding);
1215
		packageBinding.addType(binding);
1195
	} else if (binding == TheNotFoundType) {
1216
	} else if (binding == TheNotFoundType) {
1196
		// report the missing class file first
1217
		// report the missing class file first
1197
		this.problemReporter.isClassPathCorrect(compoundName, this.unitBeingCompleted, this.missingClassFileLocation);
1218
		if (!wasMissingType) {
1219
			/* Since missing types have been already been complained against while producing binaries, there is no class path 
1220
			 * misconfiguration now that did not also exist in some equivalent form while producing the class files which encode 
1221
			 * these missing types. So no need to bark again. Note that wasMissingType == true signals a type referenced in a .class 
1222
			 * file which could not be found when the binary was produced. See https://bugs.eclipse.org/bugs/show_bug.cgi?id=364450 */
1223
			this.problemReporter.isClassPathCorrect(compoundName, this.unitBeingCompleted, this.missingClassFileLocation);
1224
		}
1198
		// create a proxy for the missing BinaryType
1225
		// create a proxy for the missing BinaryType
1199
		binding = createMissingType(null, compoundName);
1226
		binding = createMissingType(null, compoundName);
1200
	} else if (!isParameterized) {
1227
	} else if (!isParameterized) {
Lines 1453-1458 Link Here
1453
	this.unitBeingCompleted = null; // in case AbortException occurred
1480
	this.unitBeingCompleted = null; // in case AbortException occurred
1454
1481
1455
	this.classFilePool.reset();
1482
	this.classFilePool.reset();
1483
1456
	// name environment has a longer life cycle, and must be reset in
1484
	// name environment has a longer life cycle, and must be reset in
1457
	// the code which created it.
1485
	// the code which created it.
1458
}
1486
}
(-)a/org.eclipse.jdt.core/compiler/org/eclipse/jdt/internal/compiler/lookup/MethodBinding.java (-2 / +52 lines)
Lines 1-12 Link Here
1
/*******************************************************************************
1
/*******************************************************************************
2
 * Copyright (c) 2000, 2011 IBM Corporation and others.
2
 * Copyright (c) 2000, 2012 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
6
 * http://www.eclipse.org/legal/epl-v10.html
6
 * http://www.eclipse.org/legal/epl-v10.html
7
 * 
7
 *
8
 * Contributors:
8
 * Contributors:
9
 *     IBM Corporation - initial API and implementation
9
 *     IBM Corporation - initial API and implementation
10
 *     Stephan Herrmann - Contributions for
11
 *								bug 186342 - [compiler][null] Using annotations for null checking
12
 *								bug 367203 - [compiler][null] detect assigning null to nonnull argument
13
 *								bug 365519 - editorial cleanup after bug 186342 and bug 365387
14
 *								bug 365662 - [compiler][null] warn on contradictory and redundant null annotations
15
 *								bug 365531 - [compiler][null] investigate alternative strategy for internally encoding nullness defaults
10
 *******************************************************************************/
16
 *******************************************************************************/
11
package org.eclipse.jdt.internal.compiler.lookup;
17
package org.eclipse.jdt.internal.compiler.lookup;
12
18
Lines 33-38 Link Here
33
	public TypeVariableBinding[] typeVariables = Binding.NO_TYPE_VARIABLES;
39
	public TypeVariableBinding[] typeVariables = Binding.NO_TYPE_VARIABLES;
34
	char[] signature;
40
	char[] signature;
35
	public long tagBits;
41
	public long tagBits;
42
43
	/** Store nullness information from annotation (incl. applicable default). */
44
	public Boolean[] parameterNonNullness;  // TRUE means @NonNull declared, FALSE means @Nullable declared, null means nothing declared
36
45
37
protected MethodBinding() {
46
protected MethodBinding() {
38
	// for creating problem or synthetic method
47
	// for creating problem or synthetic method
Lines 439-444 Link Here
439
	return this.selector;
448
	return this.selector;
440
}
449
}
441
450
451
/**
452
 * After method verifier has finished, fill in missing @NonNull specification from the applicable default.
453
 */
454
protected void fillInDefaultNonNullness() {
455
	if (this.parameterNonNullness == null)
456
		this.parameterNonNullness = new Boolean[this.parameters.length];
457
	AbstractMethodDeclaration sourceMethod = sourceMethod();
458
	boolean added = false;
459
	int length = this.parameterNonNullness.length;
460
	for (int i = 0; i < length; i++) {
461
		if (this.parameters[i].isBaseType())
462
			continue;
463
		if (this.parameterNonNullness[i] == null) {
464
			added = true;
465
			this.parameterNonNullness[i] = Boolean.TRUE;
466
			if (sourceMethod != null) {
467
				sourceMethod.arguments[i].binding.tagBits |= TagBits.AnnotationNonNull;
468
			}
469
		} else if (this.parameterNonNullness[i].booleanValue()) {
470
			sourceMethod.scope.problemReporter().nullAnnotationIsRedundant(sourceMethod, i);
471
		}
472
	}
473
	if (added)
474
		this.tagBits |= TagBits.HasParameterAnnotations;
475
	if (   this.returnType != null
476
		&& !this.returnType.isBaseType()
477
		&& (this.tagBits & (TagBits.AnnotationNonNull|TagBits.AnnotationNullable)) == 0)
478
	{
479
		this.tagBits |= TagBits.AnnotationNonNull;
480
	} else if ((this.tagBits & TagBits.AnnotationNonNull) != 0) {
481
		sourceMethod.scope.problemReporter().nullAnnotationIsRedundant(sourceMethod, -1/*signifies method return*/);
482
	}
483
}
484
442
public MethodBinding findOriginalInheritedMethod(MethodBinding inheritedMethod) {
485
public MethodBinding findOriginalInheritedMethod(MethodBinding inheritedMethod) {
443
	MethodBinding inheritedOriginal = inheritedMethod.original();
486
	MethodBinding inheritedOriginal = inheritedMethod.original();
444
	TypeBinding superType = this.declaringClass.findSuperTypeOriginatingFrom(inheritedOriginal.declaringClass);
487
	TypeBinding superType = this.declaringClass.findSuperTypeOriginatingFrom(inheritedOriginal.declaringClass);
Lines 524-529 Link Here
524
			AbstractMethodDeclaration methodDecl = typeDecl.declarationOf(originalMethod);
567
			AbstractMethodDeclaration methodDecl = typeDecl.declarationOf(originalMethod);
525
			if (methodDecl != null)
568
			if (methodDecl != null)
526
				ASTNode.resolveAnnotations(methodDecl.scope, methodDecl.annotations, originalMethod);
569
				ASTNode.resolveAnnotations(methodDecl.scope, methodDecl.annotations, originalMethod);
570
			long nullDefaultBits = this.tagBits & (TagBits.AnnotationNonNullByDefault|TagBits.AnnotationNullUnspecifiedByDefault);
571
			if (nullDefaultBits != 0 && this.declaringClass instanceof SourceTypeBinding) {
572
				SourceTypeBinding declaringSourceType = (SourceTypeBinding) this.declaringClass;
573
				if (declaringSourceType.checkRedundantNullnessDefaultOne(methodDecl, methodDecl.annotations, nullDefaultBits)) {
574
					declaringSourceType.checkRedundantNullnessDefaultRecurse(methodDecl, methodDecl.annotations, nullDefaultBits);
575
				}
576
			}
527
		}
577
		}
528
	}
578
	}
529
	return originalMethod.tagBits;
579
	return originalMethod.tagBits;
(-)a/org.eclipse.jdt.core/compiler/org/eclipse/jdt/internal/compiler/lookup/MethodScope.java (-1 / +2 lines)
Lines 1-5 Link Here
1
/*******************************************************************************
1
/*******************************************************************************
2
 * Copyright (c) 2000, 2011 IBM Corporation and others.
2
 * Copyright (c) 2000, 2012 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
(-)a/org.eclipse.jdt.core/compiler/org/eclipse/jdt/internal/compiler/lookup/MethodVerifier15.java (-4 / +109 lines)
Lines 1-5 Link Here
1
/*******************************************************************************
1
/*******************************************************************************
2
 * Copyright (c) 2000, 2011 IBM Corporation and others.
2
 * Copyright (c) 2000, 2012 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 - Contributions for
11
 *								bug 186342 - [compiler][null] Using annotations for null checking
12
 *								bug 365519 - editorial cleanup after bug 186342 and bug 365387
10
 *******************************************************************************/
13
 *******************************************************************************/
11
package org.eclipse.jdt.internal.compiler.lookup;
14
package org.eclipse.jdt.internal.compiler.lookup;
12
15
Lines 143-149 Link Here
143
}
146
}
144
void checkConcreteInheritedMethod(MethodBinding concreteMethod, MethodBinding[] abstractMethods) {
147
void checkConcreteInheritedMethod(MethodBinding concreteMethod, MethodBinding[] abstractMethods) {
145
	super.checkConcreteInheritedMethod(concreteMethod, abstractMethods);
148
	super.checkConcreteInheritedMethod(concreteMethod, abstractMethods);
146
149
	boolean analyseNullAnnotations = this.environment.globalOptions.isAnnotationBasedNullAnalysisEnabled;
147
	for (int i = 0, l = abstractMethods.length; i < l; i++) {
150
	for (int i = 0, l = abstractMethods.length; i < l; i++) {
148
		MethodBinding abstractMethod = abstractMethods[i];
151
		MethodBinding abstractMethod = abstractMethods[i];
149
		if (concreteMethod.isVarargs() != abstractMethod.isVarargs())
152
		if (concreteMethod.isVarargs() != abstractMethod.isVarargs())
Lines 164-169 Link Here
164
				|| this.type.superclass.erasure().findSuperTypeOriginatingFrom(originalInherited.declaringClass) == null)
167
				|| this.type.superclass.erasure().findSuperTypeOriginatingFrom(originalInherited.declaringClass) == null)
165
					this.type.addSyntheticBridgeMethod(originalInherited, concreteMethod.original());
168
					this.type.addSyntheticBridgeMethod(originalInherited, concreteMethod.original());
166
		}
169
		}
170
		if (analyseNullAnnotations && !concreteMethod.isStatic() && !abstractMethod.isStatic())
171
			checkNullSpecInheritance(concreteMethod, abstractMethod);
167
	}
172
	}
168
}
173
}
169
void checkForBridgeMethod(MethodBinding currentMethod, MethodBinding inheritedMethod, MethodBinding[] allInheritedMethods) {
174
void checkForBridgeMethod(MethodBinding currentMethod, MethodBinding inheritedMethod, MethodBinding[] allInheritedMethods) {
Lines 320-326 Link Here
320
	//		class Y { <T> void foo(T t) {} }
325
	//		class Y { <T> void foo(T t) {} }
321
	//		abstract class X extends Y implements I {}
326
	//		abstract class X extends Y implements I {}
322
327
323
	if (inheritedMethod.declaringClass.isInterface() || inheritedMethod.isStatic()) return;
328
	if (inheritedMethod.isStatic()) return;
329
	if (this.environment.globalOptions.complianceLevel < ClassFileConstants.JDK1_7 && inheritedMethod.declaringClass.isInterface())
330
		return;  // JDK7 checks for name clashes in interface inheritance, while JDK6 and below don't. See https://bugs.eclipse.org/bugs/show_bug.cgi?id=354229
324
331
325
	detectInheritedNameClash(inheritedMethod.original(), otherInheritedMethod.original());
332
	detectInheritedNameClash(inheritedMethod.original(), otherInheritedMethod.original());
326
}
333
}
Lines 358-363 Link Here
358
	}
365
	}
359
366
360
	return false;
367
	return false;
368
}
369
void checkAgainstInheritedMethods(MethodBinding currentMethod, MethodBinding[] methods, int length, MethodBinding[] allInheritedMethods)
370
{
371
	super.checkAgainstInheritedMethods(currentMethod, methods, length, allInheritedMethods);
372
	if (this.environment.globalOptions.isAnnotationBasedNullAnalysisEnabled) {
373
		for (int i = length; --i >= 0;)
374
			if (!currentMethod.isStatic() && !methods[i].isStatic())
375
				checkNullSpecInheritance(currentMethod, methods[i]);
376
	}
377
}
378
379
void checkNullSpecInheritance(MethodBinding currentMethod, MethodBinding inheritedMethod) {
380
	// precondition: caller has checked whether annotation-based null analysis is enabled.
381
	long inheritedBits = inheritedMethod.tagBits;
382
	long currentBits = currentMethod.tagBits;
383
	AbstractMethodDeclaration srcMethod = null;
384
	if (this.type.equals(currentMethod.declaringClass)) // is currentMethod from the current type?
385
		srcMethod = currentMethod.sourceMethod();
386
387
	// return type:
388
	if ((inheritedBits & TagBits.AnnotationNonNull) != 0) {
389
		long currentNullBits = currentBits & (TagBits.AnnotationNonNull|TagBits.AnnotationNullable);
390
		if (currentNullBits != TagBits.AnnotationNonNull) {
391
			if (srcMethod != null) {
392
				this.type.scope.problemReporter().illegalReturnRedefinition(srcMethod, inheritedMethod,
393
															this.environment.getNonNullAnnotationName());
394
			} else {
395
				this.type.scope.problemReporter().cannotImplementIncompatibleNullness(currentMethod, inheritedMethod);
396
				return;
397
			}
398
		}
399
	}
400
401
	// parameters:
402
	Argument[] currentArguments = srcMethod == null ? null : srcMethod.arguments;
403
	if (inheritedMethod.parameterNonNullness != null) {
404
		// inherited method has null-annotations, check compatibility:
405
406
		int length = inheritedMethod.parameterNonNullness.length;
407
		for (int i = 0; i < length; i++) {
408
			Argument currentArgument = currentArguments == null ? null : currentArguments[i];
409
410
			Boolean inheritedNonNullNess = inheritedMethod.parameterNonNullness[i];
411
			Boolean currentNonNullNess = (currentMethod.parameterNonNullness == null)
412
										? null : currentMethod.parameterNonNullness[i];
413
			if (inheritedNonNullNess != null) {				// super has a null annotation
414
				if (currentNonNullNess == null) {			// current parameter lacks null annotation
415
					boolean needNonNull = false;
416
					char[][] annotationName;
417
					if (inheritedNonNullNess == Boolean.TRUE) {
418
						needNonNull = true;
419
						annotationName = this.environment.getNonNullAnnotationName();
420
					} else {
421
						annotationName = this.environment.getNullableAnnotationName();
422
					}
423
					if (currentArgument != null) {
424
						this.type.scope.problemReporter().parameterLackingNullAnnotation(
425
								currentArgument,
426
								inheritedMethod.declaringClass,
427
								needNonNull,
428
								annotationName);
429
						continue;
430
					} else {
431
						this.type.scope.problemReporter().cannotImplementIncompatibleNullness(currentMethod, inheritedMethod);
432
						break;
433
					}
434
				}
435
			}
436
			if (inheritedNonNullNess != Boolean.TRUE) {		// super parameter is not restricted to @NonNull
437
				if (currentNonNullNess == Boolean.TRUE) { 	// current parameter is restricted to @NonNull
438
					if (currentArgument != null)
439
						this.type.scope.problemReporter().illegalRedefinitionToNonNullParameter(
440
														currentArgument,
441
														inheritedMethod.declaringClass,
442
														inheritedNonNullNess == null
443
														? null
444
														: this.environment.getNullableAnnotationName());
445
					else
446
						this.type.scope.problemReporter().cannotImplementIncompatibleNullness(currentMethod, inheritedMethod);
447
				}
448
			}
449
		}
450
	} else if (currentMethod.parameterNonNullness != null) {
451
		// super method has no annotations but current has
452
		for (int i = 0; i < currentMethod.parameterNonNullness.length; i++) {
453
			if (currentMethod.parameterNonNullness[i] == Boolean.TRUE) { // tightening from unconstrained to @NonNull
454
				if (currentArguments != null) {
455
					this.type.scope.problemReporter().illegalRedefinitionToNonNullParameter(
456
																	currentArguments[i],
457
																	inheritedMethod.declaringClass,
458
																	null);
459
				} else {
460
					this.type.scope.problemReporter().cannotImplementIncompatibleNullness(currentMethod, inheritedMethod);
461
					break;
462
				}
463
			}
464
		}
465
	}
361
}
466
}
362
467
363
void reportRawReferences() {
468
void reportRawReferences() {
Lines 932-938 Link Here
932
boolean isUnsafeReturnTypeOverride(MethodBinding currentMethod, MethodBinding inheritedMethod) {
1037
boolean isUnsafeReturnTypeOverride(MethodBinding currentMethod, MethodBinding inheritedMethod) {
933
	// called when currentMethod's return type is NOT compatible with inheritedMethod's return type
1038
	// called when currentMethod's return type is NOT compatible with inheritedMethod's return type
934
1039
935
	// JLS 3 §8.4.5: more are accepted, with an unchecked conversion
1040
	// JLS 3 �8.4.5: more are accepted, with an unchecked conversion
936
	if (currentMethod.returnType == inheritedMethod.returnType.erasure()) {
1041
	if (currentMethod.returnType == inheritedMethod.returnType.erasure()) {
937
		TypeBinding[] currentParams = currentMethod.parameters;
1042
		TypeBinding[] currentParams = currentMethod.parameters;
938
		TypeBinding[] inheritedParams = inheritedMethod.parameters;
1043
		TypeBinding[] inheritedParams = inheritedMethod.parameters;
(-)a/org.eclipse.jdt.core/compiler/org/eclipse/jdt/internal/compiler/lookup/MostSpecificExceptionMethodBinding.java (-1 / +3 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 186342 - [compiler][null] Using annotations for null checking
10
 *******************************************************************************/
11
 *******************************************************************************/
11
package org.eclipse.jdt.internal.compiler.lookup;
12
package org.eclipse.jdt.internal.compiler.lookup;
12
13
Lines 27-32 Link Here
27
				mostSpecificExceptions, 
28
				mostSpecificExceptions, 
28
				originalMethod.declaringClass);
29
				originalMethod.declaringClass);
29
		this.originalMethod = originalMethod;
30
		this.originalMethod = originalMethod;
31
		this.parameterNonNullness = originalMethod.parameterNonNullness;
30
	}
32
	}
31
	
33
	
32
	public MethodBinding original() {
34
	public MethodBinding original() {
(-)a/org.eclipse.jdt.core/compiler/org/eclipse/jdt/internal/compiler/lookup/NestedTypeBinding.java (-1 / +16 lines)
Lines 1-5 Link Here
1
/*******************************************************************************
1
/*******************************************************************************
2
 * Copyright (c) 2000, 2009 IBM Corporation and others.
2
 * Copyright (c) 2000, 2012 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-14 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 365662 - [compiler][null] warn on contradictory and redundant null annotations
10
 *******************************************************************************/
11
 *******************************************************************************/
11
package org.eclipse.jdt.internal.compiler.lookup;
12
package org.eclipse.jdt.internal.compiler.lookup;
13
14
import org.eclipse.jdt.internal.compiler.ast.ASTNode;
15
import org.eclipse.jdt.internal.compiler.ast.Annotation;
12
16
13
public class NestedTypeBinding extends SourceTypeBinding {
17
public class NestedTypeBinding extends SourceTypeBinding {
14
18
Lines 107-112 Link Here
107
	return synthLocal;
111
	return synthLocal;
108
}
112
}
109
113
114
protected void checkRedundantNullnessDefaultRecurse(ASTNode location, Annotation[] annotations, long annotationTagBits) {
115
	ReferenceBinding currentType = this.enclosingType;
116
	do {
117
		if (!((SourceTypeBinding)currentType).checkRedundantNullnessDefaultOne(location, annotations, annotationTagBits)) {
118
			return;
119
		}
120
		currentType = currentType.enclosingType();
121
	} while (currentType instanceof SourceTypeBinding);
122
	super.checkRedundantNullnessDefaultRecurse(location, annotations, annotationTagBits);
123
}
124
110
/* Answer the receiver's enclosing type... null if the receiver is a top level type.
125
/* Answer the receiver's enclosing type... null if the receiver is a top level type.
111
*/
126
*/
112
public ReferenceBinding enclosingType() {
127
public ReferenceBinding enclosingType() {
(-)a/org.eclipse.jdt.core/compiler/org/eclipse/jdt/internal/compiler/lookup/PackageBinding.java (-1 / +59 lines)
Lines 1-5 Link Here
1
/*******************************************************************************
1
/*******************************************************************************
2
 * Copyright (c) 2000, 2009 IBM Corporation and others.
2
 * Copyright (c) 2000, 2012 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 - Contributions for
11
 *								bug 186342 - [compiler][null] Using annotations for null checking
12
 *								bug 365519 - editorial cleanup after bug 186342 and bug 365387
13
 *								bug 365531 - [compiler][null] investigate alternative strategy for internally encoding nullness defaults
10
 *******************************************************************************/
14
 *******************************************************************************/
11
package org.eclipse.jdt.internal.compiler.lookup;
15
package org.eclipse.jdt.internal.compiler.lookup;
12
16
Lines 22-27 Link Here
22
	public LookupEnvironment environment;
26
	public LookupEnvironment environment;
23
	HashtableOfType knownTypes;
27
	HashtableOfType knownTypes;
24
	HashtableOfPackage knownPackages;
28
	HashtableOfPackage knownPackages;
29
30
	// code representing the default that has been defined for this package (using @NonNullByDefault)
31
	// one of Binding.{NO_NULL_DEFAULT,NULL_UNSPECIFIED_BY_DEFAULT,NONNULL_BY_DEFAULT}
32
	protected int defaultNullness = NO_NULL_DEFAULT;
33
25
protected PackageBinding() {
34
protected PackageBinding() {
26
	// for creating problem package
35
	// for creating problem package
27
}
36
}
Lines 36-41 Link Here
36
	this.environment = environment;
45
	this.environment = environment;
37
	this.knownTypes = null; // initialized if used... class counts can be very large 300-600
46
	this.knownTypes = null; // initialized if used... class counts can be very large 300-600
38
	this.knownPackages = new HashtableOfPackage(3); // sub-package counts are typically 0-3
47
	this.knownPackages = new HashtableOfPackage(3); // sub-package counts are typically 0-3
48
	if (compoundName != CharOperation.NO_CHAR_CHAR)
49
		checkIfNullAnnotationPackage();
39
}
50
}
40
51
41
public PackageBinding(LookupEnvironment environment) {
52
public PackageBinding(LookupEnvironment environment) {
Lines 58-63 Link Here
58
	if (this.knownTypes == null)
69
	if (this.knownTypes == null)
59
		this.knownTypes = new HashtableOfType(25);
70
		this.knownTypes = new HashtableOfType(25);
60
	this.knownTypes.put(element.compoundName[element.compoundName.length - 1], element);
71
	this.knownTypes.put(element.compoundName[element.compoundName.length - 1], element);
72
	if (this.environment.globalOptions.isAnnotationBasedNullAnalysisEnabled)
73
		if (element.isAnnotationType() || element instanceof UnresolvedReferenceBinding) // unresolved types don't yet have the modifiers set
74
			checkIfNullAnnotationType(element);
61
}
75
}
62
76
63
void clearMissingTagBit() {
77
void clearMissingTagBit() {
Lines 230-235 Link Here
230
	return ProblemReasons.NoError;
244
	return ProblemReasons.NoError;
231
}
245
}
232
246
247
248
void checkIfNullAnnotationPackage() {
249
	LookupEnvironment env = this.environment;
250
	if (env.globalOptions.isAnnotationBasedNullAnalysisEnabled) {
251
		if (isPackageOfQualifiedTypeName(this.compoundName, env.getNullableAnnotationName()))
252
			env.nullableAnnotationPackage = this;
253
		if (isPackageOfQualifiedTypeName(this.compoundName, env.getNonNullAnnotationName()))
254
			env.nonnullAnnotationPackage = this;
255
		if (isPackageOfQualifiedTypeName(this.compoundName, env.getNonNullByDefaultAnnotationName()))
256
			env.nonnullByDefaultAnnotationPackage = this;
257
	}
258
}
259
260
private boolean isPackageOfQualifiedTypeName(char[][] packageName, char[][] typeName) {
261
	int length;
262
	if (typeName == null || (length = packageName.length) != typeName.length -1)
263
		return false;
264
	for (int i=0; i<length; i++)
265
		if (!CharOperation.equals(packageName[i], typeName[i]))
266
			return false;
267
	return true;
268
}
269
270
void checkIfNullAnnotationType(ReferenceBinding type) {
271
	// check if type is one of the configured null annotation types
272
	// if so mark as a well known type using the corresponding typeID:
273
	if (this.environment.nullableAnnotationPackage == this
274
			&& CharOperation.equals(type.compoundName, this.environment.getNullableAnnotationName())) {
275
		type.id = TypeIds.T_ConfiguredAnnotationNullable;
276
		if (!(type instanceof UnresolvedReferenceBinding)) // unresolved will need to check back for the resolved type
277
			this.environment.nullableAnnotationPackage = null; // don't check again
278
	} else if (this.environment.nonnullAnnotationPackage == this
279
			&& CharOperation.equals(type.compoundName, this.environment.getNonNullAnnotationName())) {
280
		type.id = TypeIds.T_ConfiguredAnnotationNonNull;
281
		if (!(type instanceof UnresolvedReferenceBinding)) // unresolved will need to check back for the resolved type
282
			this.environment.nonnullAnnotationPackage = null; // don't check again
283
	} else if (this.environment.nonnullByDefaultAnnotationPackage == this
284
			&& CharOperation.equals(type.compoundName, this.environment.getNonNullByDefaultAnnotationName())) {
285
		type.id = TypeIds.T_ConfiguredAnnotationNonNullByDefault;
286
		if (!(type instanceof UnresolvedReferenceBinding)) // unresolved will need to check back for the resolved type
287
			this.environment.nonnullByDefaultAnnotationPackage = null; // don't check again
288
	}
289
}
290
233
public char[] readableName() /*java.lang*/ {
291
public char[] readableName() /*java.lang*/ {
234
	return CharOperation.concatWith(this.compoundName, '.');
292
	return CharOperation.concatWith(this.compoundName, '.');
235
}
293
}
(-)a/org.eclipse.jdt.core/compiler/org/eclipse/jdt/internal/compiler/lookup/ParameterizedGenericMethodBinding.java (+3 lines)
Lines 7-12 Link Here
7
 * 
7
 * 
8
 * Contributors:
8
 * Contributors:
9
 *     IBM Corporation - initial API and implementation
9
 *     IBM Corporation - initial API and implementation
10
 *     Stephan Herrmann - Contribution for bug 186342 - [compiler][null] Using annotations for null checking
10
 *******************************************************************************/
11
 *******************************************************************************/
11
package org.eclipse.jdt.internal.compiler.lookup;
12
package org.eclipse.jdt.internal.compiler.lookup;
12
13
Lines 301-306 Link Here
301
	    									? originalMethod.returnType // no substitution if original was static
302
	    									? originalMethod.returnType // no substitution if original was static
302
	    									: Scope.substitute(rawType, originalMethod.returnType));
303
	    									: Scope.substitute(rawType, originalMethod.returnType));
303
	    this.wasInferred = false; // not resulting from method invocation inferrence
304
	    this.wasInferred = false; // not resulting from method invocation inferrence
305
	    this.parameterNonNullness = originalMethod.parameterNonNullness;
304
	}
306
	}
305
307
306
    /**
308
    /**
Lines 342-347 Link Here
342
			}
344
			}
343
		}
345
		}
344
	    this.wasInferred = true;// resulting from method invocation inferrence
346
	    this.wasInferred = true;// resulting from method invocation inferrence
347
	    this.parameterNonNullness = originalMethod.parameterNonNullness;
345
	}
348
	}
346
349
347
	/*
350
	/*
(-)a/org.eclipse.jdt.core/compiler/org/eclipse/jdt/internal/compiler/lookup/ParameterizedMethodBinding.java (-1 / +4 lines)
Lines 1-5 Link Here
1
/*******************************************************************************
1
/*******************************************************************************
2
 * Copyright (c) 2000, 2010 IBM Corporation and others.
2
 * Copyright (c) 2000, 2011 IBM Corporation and others.
3
 * All rights reserved. This program and the accompanying materials
3
 * All rights reserved. This program and the accompanying materials
4
 * are made available under the terms of the Eclipse Public License v1.0
4
 * are made available under the terms of the Eclipse Public License v1.0
5
 * which accompanies this distribution, and is available at
5
 * which accompanies this distribution, and is available at
Lines 7-12 Link Here
7
 *
7
 *
8
 * Contributors:
8
 * Contributors:
9
 *     IBM Corporation - initial API and implementation
9
 *     IBM Corporation - initial API and implementation
10
 *     Stephan Herrmann - Contribution for bug 186342 - [compiler][null] Using annotations for null checking
10
 *******************************************************************************/
11
 *******************************************************************************/
11
package org.eclipse.jdt.internal.compiler.lookup;
12
package org.eclipse.jdt.internal.compiler.lookup;
12
13
Lines 38-43 Link Here
38
		 * is substituted by a raw type.
39
		 * is substituted by a raw type.
39
		 */
40
		 */
40
		this.tagBits = originalMethod.tagBits & ~TagBits.HasMissingType;
41
		this.tagBits = originalMethod.tagBits & ~TagBits.HasMissingType;
42
		this.parameterNonNullness = originalMethod.parameterNonNullness;
41
43
42
		final TypeVariableBinding[] originalVariables = originalMethod.typeVariables;
44
		final TypeVariableBinding[] originalVariables = originalMethod.typeVariables;
43
		Substitution substitution = null;
45
		Substitution substitution = null;
Lines 150-155 Link Here
150
		 * is substituted by a raw type.
152
		 * is substituted by a raw type.
151
		 */
153
		 */
152
		this.tagBits = originalMethod.tagBits & ~TagBits.HasMissingType;
154
		this.tagBits = originalMethod.tagBits & ~TagBits.HasMissingType;
155
		this.parameterNonNullness = originalMethod.parameterNonNullness;
153
156
154
		final TypeVariableBinding[] originalVariables = originalMethod.typeVariables;
157
		final TypeVariableBinding[] originalVariables = originalMethod.typeVariables;
155
		Substitution substitution = null;
158
		Substitution substitution = null;
(-)a/org.eclipse.jdt.core/compiler/org/eclipse/jdt/internal/compiler/lookup/ParameterizedTypeBinding.java (-2 / +10 lines)
Lines 1-5 Link Here
1
/*******************************************************************************
1
/*******************************************************************************
2
 * Copyright (c) 2005, 2011 IBM Corporation and others.
2
 * Copyright (c) 2005, 2012 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 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
	 */
Lines 667-673 Link Here
667
						}
675
						}
668
						break;
676
						break;
669
					case Binding.INTERSECTION_TYPE :
677
					case Binding.INTERSECTION_TYPE :
670
						this.tagBits |= TagBits.HasDirectWildcard;
678
						this.tagBits |= TagBits.HasDirectWildcard | TagBits.IsBoundParameterizedType; // Surely NOT X<?,?>, see https://bugs.eclipse.org/bugs/show_bug.cgi?id=366131
671
						break;
679
						break;
672
					default :
680
					default :
673
						this.tagBits |= TagBits.IsBoundParameterizedType;
681
						this.tagBits |= TagBits.IsBoundParameterizedType;
(-)a/org.eclipse.jdt.core/compiler/org/eclipse/jdt/internal/compiler/lookup/ProblemReasons.java (+1 lines)
Lines 27-30 Link Here
27
	final int TypeArgumentsForRawGenericMethod = 13; // for generic method
27
	final int TypeArgumentsForRawGenericMethod = 13; // for generic method
28
	final int InvalidTypeForStaticImport = 14;
28
	final int InvalidTypeForStaticImport = 14;
29
	final int InvalidTypeForAutoManagedResource = 15;
29
	final int InvalidTypeForAutoManagedResource = 15;
30
	final int VarargsElementTypeNotVisible = 16;
30
}
31
}
(-)a/org.eclipse.jdt.core/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.
(-)a/org.eclipse.jdt.core/compiler/org/eclipse/jdt/internal/compiler/lookup/ReferenceBinding.java (-19 / +71 lines)
Lines 1-12 Link Here
1
/*******************************************************************************
1
/*******************************************************************************
2
 * Copyright (c) 2000, 2011 IBM Corporation and others.
2
 * Copyright (c) 2000, 2012 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
6
 * http://www.eclipse.org/legal/epl-v10.html
6
 * http://www.eclipse.org/legal/epl-v10.html
7
 * 
7
 *
8
 * Contributors:
8
 * Contributors:
9
 *     IBM Corporation - initial API and implementation
9
 *     IBM Corporation - initial API and implementation
10
 *     Stephan Herrmann - Contributions for
11
 *								bug 349326 - [1.7] new warning for missing try-with-resources
12
 *								bug 186342 - [compiler][null] Using annotations for null checking
13
 *								bug 365519 - editorial cleanup after bug 186342 and bug 365387
14
 *								bug 358903 - Filter practically unimportant resource leak warnings
15
 *								bug 365531 - [compiler][null] investigate alternative strategy for internally encoding nullness defaults
10
 *******************************************************************************/
16
 *******************************************************************************/
11
package org.eclipse.jdt.internal.compiler.lookup;
17
package org.eclipse.jdt.internal.compiler.lookup;
12
18
Lines 41-47 Link Here
41
47
42
	private SimpleLookupTable compatibleCache;
48
	private SimpleLookupTable compatibleCache;
43
49
44
	public static final ReferenceBinding LUB_GENERIC = new ReferenceBinding() { /* used for lub computation */};
50
	int typeBits; // additional bits characterizing this type
51
52
	public static final ReferenceBinding LUB_GENERIC = new ReferenceBinding() { /* used for lub computation */
53
		public boolean hasTypeBit(int bit) { return false; }
54
	};
45
55
46
	private static final Comparator FIELD_COMPARATOR = new Comparator() {
56
	private static final Comparator FIELD_COMPARATOR = new Comparator() {
47
		public int compare(Object o1, Object o2) {
57
		public int compare(Object o1, Object o2) {
Lines 361-372 Link Here
361
}
371
}
362
372
363
public void computeId() {
373
public void computeId() {
374
	// note that more (configurable) ids are assigned from PackageBinding#checkIfNullAnnotationType() 
375
364
	// try to avoid multiple checks against a package/type name
376
	// try to avoid multiple checks against a package/type name
365
	switch (this.compoundName.length) {
377
	switch (this.compoundName.length) {
366
378
367
		case 3 :
379
		case 3 :
368
			if (!CharOperation.equals(TypeConstants.JAVA, this.compoundName[0])
380
			if (!CharOperation.equals(TypeConstants.JAVA, this.compoundName[0]))
369
					&& !CharOperation.equals(TypeConstants.JAVAX, this.compoundName[0]))
370
				return;
381
				return;
371
			
382
			
372
			char[] packageName = this.compoundName[1];
383
			char[] packageName = this.compoundName[1];
Lines 374-397 Link Here
374
			char[] typeName = this.compoundName[2];
385
			char[] typeName = this.compoundName[2];
375
			if (typeName.length == 0) return; // just to be safe
386
			if (typeName.length == 0) return; // just to be safe
376
			// remaining types MUST be in java.*.*
387
			// remaining types MUST be in java.*.*
377
			if (CharOperation.equals(TypeConstants.JAVAX, this.compoundName[0])) {
378
				if (CharOperation.equals(TypeConstants.ANNOTATION, this.compoundName[1])) {
379
					switch (typeName[0]) {
380
						case 'P' :
381
							if (CharOperation.equals(typeName, TypeConstants.JAVAX_ANNOTATION_POSTCONSTRUCT[2]))
382
								this.id = TypeIds.T_JavaxAnnotationPostConstruct;
383
							if (CharOperation.equals(typeName, TypeConstants.JAVAX_ANNOTATION_PREDESTROY[2]))
384
								this.id = TypeIds.T_JavaxAnnotationPreDestroy;
385
							return;
386
					}
387
				}
388
				return;
389
			}
390
			if (!CharOperation.equals(TypeConstants.LANG, this.compoundName[1])) {
388
			if (!CharOperation.equals(TypeConstants.LANG, this.compoundName[1])) {
391
				switch (packageName[0]) {
389
				switch (packageName[0]) {
392
					case 'i' :
390
					case 'i' :
393
						if (CharOperation.equals(packageName, TypeConstants.IO)) {
391
						if (CharOperation.equals(packageName, TypeConstants.IO)) {
394
							switch (typeName[0]) {
392
							switch (typeName[0]) {
393
								case 'C' :
394
									if (CharOperation.equals(typeName, TypeConstants.JAVA_IO_CLOSEABLE[2]))
395
										this.typeBits |= TypeIds.BitCloseable; // don't assign id, only typeBit (for analysis of resource leaks) 
396
									return;
395
								case 'E' :
397
								case 'E' :
396
									if (CharOperation.equals(typeName, TypeConstants.JAVA_IO_EXTERNALIZABLE[2]))
398
									if (CharOperation.equals(typeName, TypeConstants.JAVA_IO_EXTERNALIZABLE[2]))
397
										this.id = TypeIds.T_JavaIoExternalizable;
399
										this.id = TypeIds.T_JavaIoExternalizable;
Lines 438-445 Link Here
438
				case 'A' :
440
				case 'A' :
439
					switch(typeName.length) {
441
					switch(typeName.length) {
440
						case 13 :
442
						case 13 :
441
							if (CharOperation.equals(typeName, TypeConstants.JAVA_LANG_AUTOCLOSEABLE[2]))
443
							if (CharOperation.equals(typeName, TypeConstants.JAVA_LANG_AUTOCLOSEABLE[2])) {
442
								this.id = TypeIds.T_JavaLangAutoCloseable;
444
								this.id = TypeIds.T_JavaLangAutoCloseable;
445
								this.typeBits |= TypeIds.BitAutoCloseable; 
446
							}
443
							return;
447
							return;
444
						case 14:
448
						case 14:
445
							if (CharOperation.equals(typeName, TypeConstants.JAVA_LANG_ASSERTIONERROR[2]))
449
							if (CharOperation.equals(typeName, TypeConstants.JAVA_LANG_ASSERTIONERROR[2]))
Lines 937-942 Link Here
937
public final boolean hasRestrictedAccess() {
941
public final boolean hasRestrictedAccess() {
938
	return (this.modifiers & ExtraCompilerModifiers.AccRestrictedAccess) != 0;
942
	return (this.modifiers & ExtraCompilerModifiers.AccRestrictedAccess) != 0;
939
}
943
}
944
/** Answer an additional bit characterizing this type, like {@link TypeIds#BitAutoCloseable}. */
945
abstract public boolean hasTypeBit(int bit);
940
946
941
/** Answer true if the receiver implements anInterface or is identical to anInterface.
947
/** Answer true if the receiver implements anInterface or is identical to anInterface.
942
* If searchHierarchy is true, then also search the receiver's superclasses.
948
* If searchHierarchy is true, then also search the receiver's superclasses.
Lines 1446-1449 Link Here
1446
public FieldBinding[] unResolvedFields() {
1452
public FieldBinding[] unResolvedFields() {
1447
	return Binding.NO_FIELDS;
1453
	return Binding.NO_FIELDS;
1448
}
1454
}
1455
1456
/*
1457
 * If a type - known to be a Closeable - is mentioned in one of our white lists
1458
 * answer the typeBit for the white list (BitWrapperCloseable or BitResourceFreeCloseable).
1459
 */
1460
protected int applyCloseableWhitelists() {
1461
	switch (this.compoundName.length) {
1462
		case 3:
1463
			if (CharOperation.equals(TypeConstants.JAVA, this.compoundName[0])) {
1464
				if (CharOperation.equals(TypeConstants.IO, this.compoundName[1])) {
1465
					char[] simpleName = this.compoundName[2];
1466
					int l = TypeConstants.JAVA_IO_WRAPPER_CLOSEABLES.length;
1467
					for (int i = 0; i < l; i++) {
1468
						if (CharOperation.equals(simpleName, TypeConstants.JAVA_IO_WRAPPER_CLOSEABLES[i]))
1469
							return TypeIds.BitWrapperCloseable;
1470
					}
1471
					l = TypeConstants.JAVA_IO_RESOURCE_FREE_CLOSEABLES.length;
1472
					for (int i = 0; i < l; i++) {
1473
						if (CharOperation.equals(simpleName, TypeConstants.JAVA_IO_RESOURCE_FREE_CLOSEABLES[i]))
1474
							return TypeIds.BitResourceFreeCloseable;
1475
					}
1476
				}
1477
			}
1478
			break;
1479
		case 4:
1480
			if (CharOperation.equals(TypeConstants.JAVA, this.compoundName[0])) {
1481
				if (CharOperation.equals(TypeConstants.UTIL, this.compoundName[1])) {
1482
					if (CharOperation.equals(TypeConstants.ZIP, this.compoundName[2])) {
1483
						char[] simpleName = this.compoundName[3];
1484
						int l = TypeConstants.JAVA_UTIL_ZIP_WRAPPER_CLOSEABLES.length;
1485
						for (int i = 0; i < l; i++) {
1486
							if (CharOperation.equals(simpleName, TypeConstants.JAVA_UTIL_ZIP_WRAPPER_CLOSEABLES[i]))
1487
								return TypeIds.BitWrapperCloseable;
1488
						}
1489
					}
1490
				}
1491
			}
1492
			break;
1493
	}
1494
	int l = TypeConstants.OTHER_WRAPPER_CLOSEABLES.length;
1495
	for (int i = 0; i < l; i++) {
1496
		if (CharOperation.equals(this.compoundName, TypeConstants.OTHER_WRAPPER_CLOSEABLES[i]))
1497
			return TypeIds.BitWrapperCloseable;
1498
	}	
1499
	return 0;
1500
}
1449
}
1501
}
(-)a/org.eclipse.jdt.core/compiler/org/eclipse/jdt/internal/compiler/lookup/Scope.java (-20 / +149 lines)
Lines 7-12 Link Here
7
 *
7
 *
8
 * Contributors:
8
 * Contributors:
9
 *     IBM Corporation - initial API and implementation
9
 *     IBM Corporation - initial API and implementation
10
 *     Stephan Herrmann - Contribution for bug 186342 [compiler][null] Using annotations for null checking
10
 *******************************************************************************/
11
 *******************************************************************************/
11
package org.eclipse.jdt.internal.compiler.lookup;
12
package org.eclipse.jdt.internal.compiler.lookup;
12
13
Lines 527-532 Link Here
527
	 * in case the method was originally compatible, then simply answer it back.
528
	 * in case the method was originally compatible, then simply answer it back.
528
	 */
529
	 */
529
	protected final MethodBinding computeCompatibleMethod(MethodBinding method, TypeBinding[] arguments, InvocationSite invocationSite) {
530
	protected final MethodBinding computeCompatibleMethod(MethodBinding method, TypeBinding[] arguments, InvocationSite invocationSite) {
531
		return computeCompatibleMethod(method, arguments, invocationSite, false);
532
	}	
533
	/**
534
	 * Internal use only
535
	 * Given a method, returns null if arguments cannot be converted to parameters.
536
	 * Will answer a substituted method in case the method was generic and type inference got triggered;
537
	 * in case the method was originally compatible, then simply answer it back.
538
	 */
539
	protected final MethodBinding computeCompatibleMethod(MethodBinding method, TypeBinding[] arguments, InvocationSite invocationSite, boolean tiebreakingVarargsMethods) {
530
		TypeBinding[] genericTypeArguments = invocationSite.genericTypeArguments();
540
		TypeBinding[] genericTypeArguments = invocationSite.genericTypeArguments();
531
		TypeBinding[] parameters = method.parameters;
541
		TypeBinding[] parameters = method.parameters;
532
		TypeVariableBinding[] typeVariables = method.typeVariables;
542
		TypeVariableBinding[] typeVariables = method.typeVariables;
Lines 571-584 Link Here
571
			}
581
			}
572
		}
582
		}
573
583
574
		if (parameterCompatibilityLevel(method, arguments) > NOT_COMPATIBLE) {
584
		int compatibilityLevel;
585
		if ((compatibilityLevel = parameterCompatibilityLevel(method, arguments, tiebreakingVarargsMethods)) > NOT_COMPATIBLE) {
586
			if (compatibilityLevel == VARARGS_COMPATIBLE) {
587
				TypeBinding varargsElementType = method.parameters[method.parameters.length - 1].leafComponentType();
588
				if (varargsElementType instanceof ReferenceBinding) {
589
					if (!((ReferenceBinding) varargsElementType).canBeSeenBy(this)) {
590
						return new ProblemMethodBinding(method, method.selector, genericTypeArguments, ProblemReasons.VarargsElementTypeNotVisible);
591
					}
592
				}
593
			}
575
			if ((method.tagBits & TagBits.AnnotationPolymorphicSignature) != 0) {
594
			if ((method.tagBits & TagBits.AnnotationPolymorphicSignature) != 0) {
576
				// generate polymorphic method
595
				// generate polymorphic method
577
				return this.environment().createPolymorphicMethod(method, arguments);
596
				return this.environment().createPolymorphicMethod(method, arguments);
578
			}
597
			}
579
			return method;
598
			return method;
580
		}
599
		}
581
		if (genericTypeArguments != null)
600
		// if method is generic and type arguments have been supplied, only then answer a problem 
601
		// of ParameterizedMethodTypeMismatch, else a non-generic method was invoked using type arguments
602
		// in which case this problem category will be bogus
603
		if (genericTypeArguments != null && typeVariables != Binding.NO_TYPE_VARIABLES)
582
			return new ProblemMethodBinding(method, method.selector, arguments, ProblemReasons.ParameterizedMethodTypeMismatch);
604
			return new ProblemMethodBinding(method, method.selector, arguments, ProblemReasons.ParameterizedMethodTypeMismatch);
583
		return null; // incompatible
605
		return null; // incompatible
584
	}
606
	}
Lines 2389-2394 Link Here
2389
		return new ProblemReferenceBinding(compoundName, null /* no closest match since search for pkg*/, ProblemReasons.NotFound);
2411
		return new ProblemReferenceBinding(compoundName, null /* no closest match since search for pkg*/, ProblemReasons.NotFound);
2390
	}
2412
	}
2391
2413
2414
	/* Answer the package from the compoundName or null if it begins with a type.
2415
	* Intended to be used while resolving a package name only.
2416
	* 
2417
	* Internal use only
2418
	*/
2419
	public final Binding getOnlyPackage(char[][] compoundName) {
2420
 		compilationUnitScope().recordQualifiedReference(compoundName);
2421
		Binding binding = getTypeOrPackage(compoundName[0], Binding.PACKAGE, true);
2422
		if (binding == null || !binding.isValidBinding()) {
2423
			char[][] qName = new char[][] { compoundName[0] };
2424
			return new ProblemReferenceBinding(qName, null /* no closest match since search for pkg*/, ProblemReasons.NotFound);
2425
		}
2426
		if (!(binding instanceof PackageBinding)) {
2427
			return null; // compoundName does not start with a package
2428
		}
2429
2430
		int currentIndex = 1, length = compoundName.length;
2431
		PackageBinding packageBinding = (PackageBinding) binding;
2432
		while (currentIndex < length) {
2433
			binding = packageBinding.getPackage(compoundName[currentIndex++]);
2434
			if (binding == null) {
2435
				return new ProblemReferenceBinding(CharOperation.subarray(compoundName, 0, currentIndex), null /* no closest match since search for pkg*/, ProblemReasons.NotFound);
2436
			}
2437
			if (!binding.isValidBinding()) {
2438
				return new ProblemReferenceBinding(
2439
					CharOperation.subarray(compoundName, 0, currentIndex),
2440
					binding instanceof ReferenceBinding ? (ReferenceBinding)((ReferenceBinding)binding).closestMatch() : null,
2441
					binding.problemId());
2442
			}
2443
			packageBinding = (PackageBinding) binding;
2444
		}
2445
		return packageBinding;
2446
	}
2447
2392
	/* Answer the type binding that corresponds the given name, starting the lookup in the receiver.
2448
	/* Answer the type binding that corresponds the given name, starting the lookup in the receiver.
2393
	* The name provided is a simple source name (e.g., "Object" , "Point", ...)
2449
	* The name provided is a simple source name (e.g., "Object" , "Point", ...)
2394
	*/
2450
	*/
Lines 2678-2684 Link Here
2678
					}
2734
					}
2679
				}
2735
				}
2680
			}
2736
			}
2681
2737
			// walk single static imports. A type found here will shadow types with same name in other CU's, or types coming
2738
			// from on-demand imports. JLS 7.5.3
2739
			// https://bugs.eclipse.org/bugs/show_bug.cgi?id=318401
2740
			if (imports != null) {
2741
				ReferenceBinding type = null;
2742
				nextImport : for (int i = 0, length = imports.length; i < length; i++) {
2743
					ImportBinding importBinding = imports[i];
2744
					if (importBinding.isStatic()) {
2745
						ReferenceBinding temp = null;
2746
						if (CharOperation.equals(importBinding.compoundName[importBinding.compoundName.length - 1], name)) {
2747
							Binding resolvedImport = importBinding.resolvedImport;
2748
							if (resolvedImport == null) continue nextImport;
2749
							if (resolvedImport instanceof MethodBinding || resolvedImport instanceof FieldBinding) {
2750
								// check to see if there are also member types with the same name
2751
								// must find the importRef's type again since the method/field can be from an inherited type
2752
								// see StaticImportTest#test084 for more clarity
2753
								char[][] importName = importBinding.reference.tokens;
2754
								TypeBinding referencedType = getType(importName, importName.length - 1);
2755
								if (referencedType != null && referencedType instanceof ReferenceBinding) {
2756
									temp = findMemberType(name, (ReferenceBinding) referencedType);
2757
								}
2758
							}
2759
							if (temp != null && temp.isStatic() && temp != type) {
2760
								if (temp.isValidBinding()) {
2761
									if (!temp.canBeSeenBy(unitScope.fPackage)) {
2762
										// Answer error binding - type is not visible
2763
										foundType = new ProblemReferenceBinding(new char[][]{name}, type, ProblemReasons.NotVisible);
2764
									} else {
2765
										ImportReference importReference = importBinding.reference;
2766
										if (importReference != null) {
2767
											importReference.bits |= ASTNode.Used;
2768
										}
2769
										type = temp;
2770
									}
2771
								} else if (foundType == null) {
2772
									foundType = temp;
2773
								}
2774
							}
2775
						}
2776
					}
2777
				}
2778
				if (type != null) {
2779
					if (typeOrPackageCache != null)
2780
						typeOrPackageCache.put(name, type);
2781
					return type;
2782
				}
2783
			}
2682
			// check if the name is in the current package, skip it if its a sub-package
2784
			// check if the name is in the current package, skip it if its a sub-package
2683
			PackageBinding currentPackage = unitScope.fPackage;
2785
			PackageBinding currentPackage = unitScope.fPackage;
2684
			unitScope.recordReference(currentPackage.compoundName, name);
2786
			unitScope.recordReference(currentPackage.compoundName, name);
Lines 2878-2883 Link Here
2878
		return null;
2980
		return null;
2879
	}
2981
	}
2880
2982
2983
	// Tie break IS running to determine the most specific method binding.
2881
	protected boolean isAcceptableMethod(MethodBinding one, MethodBinding two) {
2984
	protected boolean isAcceptableMethod(MethodBinding one, MethodBinding two) {
2882
		TypeBinding[] oneParams = one.parameters;
2985
		TypeBinding[] oneParams = one.parameters;
2883
		TypeBinding[] twoParams = two.parameters;
2986
		TypeBinding[] twoParams = two.parameters;
Lines 2924-2931 Link Here
2924
					}
3027
					}
2925
				} else {
3028
				} else {
2926
					if (i == oneParamsLength - 1 && one.isVarargs() && two.isVarargs()) {
3029
					if (i == oneParamsLength - 1 && one.isVarargs() && two.isVarargs()) {
3030
						TypeBinding oType = ((ArrayBinding) oneParam).elementsType();
2927
						TypeBinding eType = ((ArrayBinding) twoParam).elementsType();
3031
						TypeBinding eType = ((ArrayBinding) twoParam).elementsType();
2928
						if (oneParam == eType || oneParam.isCompatibleWith(eType))
3032
						if (oType == eType || oType.isCompatibleWith(eType))
2929
							return true; // special case to choose between 2 varargs methods when the last arg is Object[]
3033
							return true; // special case to choose between 2 varargs methods when the last arg is Object[]
2930
					}
3034
					}
2931
					return false;
3035
					return false;
Lines 2935-2951 Link Here
2935
		}
3039
		}
2936
3040
2937
		if (one.isVarargs() && two.isVarargs()) {
3041
		if (one.isVarargs() && two.isVarargs()) {
2938
			if (oneParamsLength > twoParamsLength) {
2939
				// special case when autoboxing makes (int, int...) better than (Object...) but not (int...) or (Integer, int...)
2940
				if (((ArrayBinding) twoParams[twoParamsLength - 1]).elementsType().id != TypeIds.T_JavaLangObject)
2941
					return false;
2942
			}
2943
			// check that each parameter before the vararg parameters are compatible (no autoboxing allowed here)
3042
			// check that each parameter before the vararg parameters are compatible (no autoboxing allowed here)
2944
			for (int i = (oneParamsLength > twoParamsLength ? twoParamsLength : oneParamsLength) - 2; i >= 0; i--)
3043
			for (int i = (oneParamsLength > twoParamsLength ? twoParamsLength : oneParamsLength) - 2; i >= 0; i--)
2945
				if (oneParams[i] != twoParams[i] && !oneParams[i].isCompatibleWith(twoParams[i]))
3044
				if (oneParams[i] != twoParams[i] && !oneParams[i].isCompatibleWith(twoParams[i]))
2946
					return false;
3045
					return false;
2947
			if (parameterCompatibilityLevel(one, twoParams) == NOT_COMPATIBLE
3046
			if (parameterCompatibilityLevel(one, twoParams, true) == NOT_COMPATIBLE
2948
					&& parameterCompatibilityLevel(two, oneParams) == VARARGS_COMPATIBLE)
3047
					&& parameterCompatibilityLevel(two, oneParams, true) == VARARGS_COMPATIBLE)
2949
				return true;
3048
				return true;
2950
		}
3049
		}
2951
		return false;
3050
		return false;
Lines 2980-2985 Link Here
2980
	/* Answer true if the scope is nested inside a given method declaration
3079
	/* Answer true if the scope is nested inside a given method declaration
2981
	*/
3080
	*/
2982
	public final boolean isDefinedInMethod(MethodBinding method) {
3081
	public final boolean isDefinedInMethod(MethodBinding method) {
3082
		method = method.original(); // https://bugs.eclipse.org/bugs/show_bug.cgi?id=350738
2983
		Scope scope = this;
3083
		Scope scope = this;
2984
		do {
3084
		do {
2985
			if (scope instanceof MethodScope) {
3085
			if (scope instanceof MethodScope) {
Lines 3009-3015 Link Here
3009
		// test that the enclosingType is not part of the compilation unit
3109
		// test that the enclosingType is not part of the compilation unit
3010
		SourceTypeBinding[] topLevelTypes = ((CompilationUnitScope) unitScope).topLevelTypes;
3110
		SourceTypeBinding[] topLevelTypes = ((CompilationUnitScope) unitScope).topLevelTypes;
3011
		for (int i = topLevelTypes.length; --i >= 0;)
3111
		for (int i = topLevelTypes.length; --i >= 0;)
3012
			if (topLevelTypes[i] == enclosingType)
3112
			if (topLevelTypes[i] == enclosingType.original())
3013
				return true;
3113
				return true;
3014
		return false;
3114
		return false;
3015
	}
3115
	}
Lines 3744-3750 Link Here
3744
							methodToTest = pNext.originalMethod;
3844
							methodToTest = pNext.originalMethod;
3745
						}
3845
						}
3746
					}
3846
					}
3747
					MethodBinding acceptable = computeCompatibleMethod(methodToTest, tiebreakMethod.parameters, tieBreakInvocationSite);
3847
					MethodBinding acceptable = computeCompatibleMethod(methodToTest, tiebreakMethod.parameters, tieBreakInvocationSite, level == VARARGS_COMPATIBLE);
3748
					/* There are 4 choices to consider with current & next :
3848
					/* There are 4 choices to consider with current & next :
3749
					 foo(B) & foo(A) where B extends A
3849
					 foo(B) & foo(A) where B extends A
3750
					 1. the 2 methods are equal (both accept each others parameters) -> want to continue
3850
					 1. the 2 methods are equal (both accept each others parameters) -> want to continue
Lines 3916-3921 Link Here
3916
	}
4016
	}
3917
4017
3918
	public int parameterCompatibilityLevel(MethodBinding method, TypeBinding[] arguments) {
4018
	public int parameterCompatibilityLevel(MethodBinding method, TypeBinding[] arguments) {
4019
		return parameterCompatibilityLevel(method, arguments, false);
4020
	}	
4021
	public int parameterCompatibilityLevel(MethodBinding method, TypeBinding[] arguments, boolean tiebreakingVarargsMethods) {
3919
		TypeBinding[] parameters = method.parameters;
4022
		TypeBinding[] parameters = method.parameters;
3920
		int paramLength = parameters.length;
4023
		int paramLength = parameters.length;
3921
		int argLength = arguments.length;
4024
		int argLength = arguments.length;
Lines 3942-3952 Link Here
3942
				TypeBinding param = parameters[lastIndex]; // is an ArrayBinding by definition
4045
				TypeBinding param = parameters[lastIndex]; // is an ArrayBinding by definition
3943
				TypeBinding arg = arguments[lastIndex];
4046
				TypeBinding arg = arguments[lastIndex];
3944
				if (param != arg) {
4047
				if (param != arg) {
3945
					level = parameterCompatibilityLevel(arg, param, env);
4048
					level = parameterCompatibilityLevel(arg, param, env, tiebreakingVarargsMethods);
3946
					if (level == NOT_COMPATIBLE) {
4049
					if (level == NOT_COMPATIBLE) {
3947
						// expect X[], is it called with X
4050
						// expect X[], is it called with X
3948
						param = ((ArrayBinding) param).elementsType();
4051
						param = ((ArrayBinding) param).elementsType();
3949
						if (parameterCompatibilityLevel(arg, param, env) == NOT_COMPATIBLE)
4052
						if (tiebreakingVarargsMethods) {
4053
							arg = ((ArrayBinding) arg).elementsType();
4054
						}
4055
						if (parameterCompatibilityLevel(arg, param, env, tiebreakingVarargsMethods) == NOT_COMPATIBLE)
3950
							return NOT_COMPATIBLE;
4056
							return NOT_COMPATIBLE;
3951
						level = VARARGS_COMPATIBLE; // varargs support needed
4057
						level = VARARGS_COMPATIBLE; // varargs support needed
3952
					}
4058
					}
Lines 3955-3962 Link Here
3955
				if (paramLength < argLength) { // all remaining argument types must be compatible with the elementsType of varArgType
4061
				if (paramLength < argLength) { // all remaining argument types must be compatible with the elementsType of varArgType
3956
					TypeBinding param = ((ArrayBinding) parameters[lastIndex]).elementsType();
4062
					TypeBinding param = ((ArrayBinding) parameters[lastIndex]).elementsType();
3957
					for (int i = lastIndex; i < argLength; i++) {
4063
					for (int i = lastIndex; i < argLength; i++) {
3958
						TypeBinding arg = arguments[i];
4064
						TypeBinding arg = (tiebreakingVarargsMethods && (i == (argLength - 1))) ? ((ArrayBinding)arguments[i]).elementsType() : arguments[i];
3959
						if (param != arg && parameterCompatibilityLevel(arg, param, env) == NOT_COMPATIBLE)
4065
						if (param != arg && parameterCompatibilityLevel(arg, param, env, tiebreakingVarargsMethods) == NOT_COMPATIBLE)
3960
							return NOT_COMPATIBLE;
4066
							return NOT_COMPATIBLE;
3961
					}
4067
					}
3962
				}  else if (lastIndex != argLength) { // can call foo(int i, X ... x) with foo(1) but NOT foo();
4068
				}  else if (lastIndex != argLength) { // can call foo(int i, X ... x) with foo(1) but NOT foo();
Lines 3970-3978 Link Here
3970
		// now compare standard arguments from 0 to lastIndex
4076
		// now compare standard arguments from 0 to lastIndex
3971
		for (int i = 0; i < lastIndex; i++) {
4077
		for (int i = 0; i < lastIndex; i++) {
3972
			TypeBinding param = parameters[i];
4078
			TypeBinding param = parameters[i];
3973
			TypeBinding arg = arguments[i];
4079
			TypeBinding arg = (tiebreakingVarargsMethods && (i == (argLength - 1))) ? ((ArrayBinding)arguments[i]).elementsType() : arguments[i];
3974
			if (arg != param) {
4080
			if (arg != param) {
3975
				int newLevel = parameterCompatibilityLevel(arg, param, env);
4081
				int newLevel = parameterCompatibilityLevel(arg, param, env, tiebreakingVarargsMethods);
3976
				if (newLevel == NOT_COMPATIBLE)
4082
				if (newLevel == NOT_COMPATIBLE)
3977
					return NOT_COMPATIBLE;
4083
					return NOT_COMPATIBLE;
3978
				if (newLevel > level)
4084
				if (newLevel > level)
Lines 3982-3991 Link Here
3982
		return level;
4088
		return level;
3983
	}
4089
	}
3984
4090
3985
	private int parameterCompatibilityLevel(TypeBinding arg, TypeBinding param, LookupEnvironment env) {
4091
	private int parameterCompatibilityLevel(TypeBinding arg, TypeBinding param, LookupEnvironment env, boolean tieBreakingVarargsMethods) {
3986
		// only called if env.options.sourceLevel >= ClassFileConstants.JDK1_5
4092
		// only called if env.options.sourceLevel >= ClassFileConstants.JDK1_5
3987
		if (arg.isCompatibleWith(param))
4093
		if (arg.isCompatibleWith(param))
3988
			return COMPATIBLE;
4094
			return COMPATIBLE;
4095
		if (tieBreakingVarargsMethods) {
4096
			/* 15.12.2.5 Choosing the Most Specific Method, ... One variable arity member method named m is more specific than
4097
			   another variable arity member method of the same name if either ... Only subtypes relationship should be used.
4098
			   Actually this is true even for fixed arity methods, but in practice is not an issue since we run the algorithm
4099
			   multiple times for each compatibility level.
4100
			   https://bugs.eclipse.org/bugs/show_bug.cgi?id=346038, https://bugs.eclipse.org/bugs/show_bug.cgi?id=346039.
4101
			*/
4102
			return NOT_COMPATIBLE;
4103
		}
3989
		if (arg.isBaseType() != param.isBaseType()) {
4104
		if (arg.isBaseType() != param.isBaseType()) {
3990
			TypeBinding convertedType = env.computeBoxingType(arg);
4105
			TypeBinding convertedType = env.computeBoxingType(arg);
3991
			if (convertedType == param || convertedType.isCompatibleWith(param))
4106
			if (convertedType == param || convertedType.isCompatibleWith(param))
Lines 4176-4179 Link Here
4176
		}
4291
		}
4177
		return visibleIndex == 1 ? visible[0] : mostSpecificMethodBinding(visible, visibleIndex, argumentTypes, allocationSite, allocationType);
4292
		return visibleIndex == 1 ? visible[0] : mostSpecificMethodBinding(visible, visibleIndex, argumentTypes, allocationSite, allocationType);
4178
	}
4293
	}
4294
4295
	public void validateNullAnnotation(long tagBits, TypeReference typeRef, Annotation[] annotations) {
4296
		long nullAnnotationTagBit = tagBits & (TagBits.AnnotationNonNull|TagBits.AnnotationNullable);
4297
		if (nullAnnotationTagBit != 0) {
4298
			TypeBinding type = typeRef.resolvedType;
4299
			if (type != null && type.isBaseType()) {
4300
				char[][] annotationName = (nullAnnotationTagBit == TagBits.AnnotationNonNull)
4301
						? environment().getNonNullAnnotationName()
4302
						: environment().getNullableAnnotationName();
4303
				problemReporter().illegalAnnotationForBaseType(typeRef, annotations,
4304
						annotationName[annotationName.length-1], nullAnnotationTagBit);
4305
			}
4306
		}
4307
	}
4179
}
4308
}
(-)a/org.eclipse.jdt.core/compiler/org/eclipse/jdt/internal/compiler/lookup/SourceTypeBinding.java (-7 / +154 lines)
Lines 1-5 Link Here
1
/*******************************************************************************
1
/*******************************************************************************
2
 * Copyright (c) 2000, 2011 IBM Corporation and others.
2
 * Copyright (c) 2000, 2012 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 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
13
 *								bug 186342 - [compiler][null] Using annotations for null checking
14
 *								bug 365836 - [compiler][null] Incomplete propagation of null defaults.
15
 *								bug 365519 - editorial cleanup after bug 186342 and bug 365387
16
 *								bug 365662 - [compiler][null] warn on contradictory and redundant null annotations
17
 *								bug 365531 - [compiler][null] investigate alternative strategy for internally encoding nullness defaults
18
 *								bug 366063 - Compiler should not add synthetic @NonNull annotations
11
 *******************************************************************************/
19
 *******************************************************************************/
12
package org.eclipse.jdt.internal.compiler.lookup;
20
package org.eclipse.jdt.internal.compiler.lookup;
13
21
Lines 18-23 Link Here
18
import org.eclipse.jdt.internal.compiler.ast.ASTNode;
26
import org.eclipse.jdt.internal.compiler.ast.ASTNode;
19
import org.eclipse.jdt.internal.compiler.ast.AbstractMethodDeclaration;
27
import org.eclipse.jdt.internal.compiler.ast.AbstractMethodDeclaration;
20
import org.eclipse.jdt.internal.compiler.ast.AbstractVariableDeclaration;
28
import org.eclipse.jdt.internal.compiler.ast.AbstractVariableDeclaration;
29
import org.eclipse.jdt.internal.compiler.ast.Annotation;
21
import org.eclipse.jdt.internal.compiler.ast.Argument;
30
import org.eclipse.jdt.internal.compiler.ast.Argument;
22
import org.eclipse.jdt.internal.compiler.ast.FieldDeclaration;
31
import org.eclipse.jdt.internal.compiler.ast.FieldDeclaration;
23
import org.eclipse.jdt.internal.compiler.ast.MethodDeclaration;
32
import org.eclipse.jdt.internal.compiler.ast.MethodDeclaration;
Lines 52-57 Link Here
52
	char[] genericReferenceTypeSignature;
61
	char[] genericReferenceTypeSignature;
53
62
54
	private SimpleLookupTable storedAnnotations = null; // keys are this ReferenceBinding & its fields and methods, value is an AnnotationHolder
63
	private SimpleLookupTable storedAnnotations = null; // keys are this ReferenceBinding & its fields and methods, value is an AnnotationHolder
64
65
	private int defaultNullness;
66
	private int nullnessDefaultInitialized = 0; // 0: nothing; 1: type; 2: package
55
67
56
public SourceTypeBinding(char[][] compoundName, PackageBinding fPackage, ClassScope scope) {
68
public SourceTypeBinding(char[][] compoundName, PackageBinding fPackage, ClassScope scope) {
57
	this.compoundName = compoundName;
69
	this.compoundName = compoundName;
Lines 779-784 Link Here
779
		}
791
		}
780
		if ((this.tagBits & TagBits.AnnotationDeprecated) != 0)
792
		if ((this.tagBits & TagBits.AnnotationDeprecated) != 0)
781
			this.modifiers |= ClassFileConstants.AccDeprecated;
793
			this.modifiers |= ClassFileConstants.AccDeprecated;
794
		evaluateNullAnnotations(this.tagBits);
782
	}
795
	}
783
	return this.tagBits;
796
	return this.tagBits;
784
}
797
}
Lines 1063-1068 Link Here
1063
	return accessors[1];
1076
	return accessors[1];
1064
}
1077
}
1065
1078
1079
public boolean hasTypeBit(int bit) {
1080
	// source types initialize type bits during connectSuperclass/interfaces()
1081
	return (this.typeBits & bit) != 0;
1082
}
1083
1066
/**
1084
/**
1067
 * @see org.eclipse.jdt.internal.compiler.lookup.Binding#initializeDeprecatedAnnotationTagBits()
1085
 * @see org.eclipse.jdt.internal.compiler.lookup.Binding#initializeDeprecatedAnnotationTagBits()
1068
 */
1086
 */
Lines 1081-1086 Link Here
1081
			this.modifiers |= ClassFileConstants.AccDeprecated;
1099
			this.modifiers |= ClassFileConstants.AccDeprecated;
1082
		}
1100
		}
1083
	}
1101
	}
1102
	if (CharOperation.equals(this.sourceName, TypeConstants.PACKAGE_INFO_NAME))
1103
		getAnnotationTagBits(); // initialize
1084
}
1104
}
1085
1105
1086
// ensure the receiver knows its hierarchy & fields/methods so static imports can be resolved correctly
1106
// ensure the receiver knows its hierarchy & fields/methods so static imports can be resolved correctly
Lines 1233-1240 Link Here
1233
									int index = pLength;
1253
									int index = pLength;
1234
									// is erasure of signature of m2 same as signature of m1?
1254
									// is erasure of signature of m2 same as signature of m1?
1235
									for (; --index >= 0;) {
1255
									for (; --index >= 0;) {
1236
										if (params1[index] != params2[index].erasure())
1256
										if (params1[index] != params2[index].erasure()) {
1237
											break;
1257
											// If one of them is a raw type
1258
											if (params1[index] instanceof RawTypeBinding) {
1259
												if (params2[index].erasure() != ((RawTypeBinding)params1[index]).actualType()) {
1260
													break;
1261
												}
1262
											} else  {
1263
												break;
1264
											}
1265
										}
1238
										if (params1[index] == params2[index]) {
1266
										if (params1[index] == params2[index]) {
1239
											TypeBinding type = params1[index].leafComponentType();
1267
											TypeBinding type = params1[index].leafComponentType();
1240
											if (type instanceof SourceTypeBinding && type.typeVariables() != Binding.NO_TYPE_VARIABLES) {
1268
											if (type instanceof SourceTypeBinding && type.typeVariables() != Binding.NO_TYPE_VARIABLES) {
Lines 1246-1253 Link Here
1246
									if (index >= 0 && index < pLength) {
1274
									if (index >= 0 && index < pLength) {
1247
										// is erasure of signature of m1 same as signature of m2?
1275
										// is erasure of signature of m1 same as signature of m2?
1248
										for (index = pLength; --index >= 0;)
1276
										for (index = pLength; --index >= 0;)
1249
											if (params1[index].erasure() != params2[index])
1277
											if (params1[index].erasure() != params2[index]) {
1250
												break;
1278
												// If one of them is a raw type
1279
												if (params2[index] instanceof RawTypeBinding) {
1280
													if (params1[index].erasure() != ((RawTypeBinding)params2[index]).actualType()) {
1281
														break;
1282
													}
1283
												} else  {
1284
													break;
1285
												}
1286
											}
1251
										
1287
										
1252
									}
1288
									}
1253
									if (index >= 0) {
1289
									if (index >= 0) {
Lines 1494-1500 Link Here
1494
				if (leafType instanceof ReferenceBinding && (((ReferenceBinding) leafType).modifiers & ExtraCompilerModifiers.AccGenericSignature) != 0)
1530
				if (leafType instanceof ReferenceBinding && (((ReferenceBinding) leafType).modifiers & ExtraCompilerModifiers.AccGenericSignature) != 0)
1495
					method.modifiers |= ExtraCompilerModifiers.AccGenericSignature;
1531
					method.modifiers |= ExtraCompilerModifiers.AccGenericSignature;
1496
				newParameters[i] = parameterType;
1532
				newParameters[i] = parameterType;
1497
				arg.binding = new LocalVariableBinding(arg, parameterType, arg.modifiers, true);
1533
				arg.binding = new LocalVariableBinding(arg, parameterType, arg.modifiers, true /*isArgument*/);
1498
			}
1534
			}
1499
		}
1535
		}
1500
		// only assign parameters if no problems are found
1536
		// only assign parameters if no problems are found
Lines 1567-1578 Link Here
1567
				typeParameters[i].binding = null;
1603
				typeParameters[i].binding = null;
1568
		return null;
1604
		return null;
1569
	}
1605
	}
1606
	if (this.scope.compilerOptions().isAnnotationBasedNullAnalysisEnabled)
1607
		createArgumentBindings(method); // need annotations resolved already at this point
1570
	if (foundReturnTypeProblem)
1608
	if (foundReturnTypeProblem)
1571
		return method; // but its still unresolved with a null return type & is still connected to its method declaration
1609
		return method; // but its still unresolved with a null return type & is still connected to its method declaration
1572
1610
1573
	method.modifiers &= ~ExtraCompilerModifiers.AccUnresolved;
1611
	method.modifiers &= ~ExtraCompilerModifiers.AccUnresolved;
1574
	return method;
1612
	return method;
1575
}
1613
}
1614
private void createArgumentBindings(MethodBinding method) {
1615
	// ensure nullness defaults are initialized at all enclosing levels:
1616
	switch (this.nullnessDefaultInitialized) {
1617
	case 0:
1618
		getAnnotationTagBits(); // initialize
1619
		//$FALL-THROUGH$
1620
	case 1:
1621
		getPackage().isViewedAsDeprecated(); // initialize annotations
1622
		this.nullnessDefaultInitialized = 2;
1623
	}
1624
	AbstractMethodDeclaration methodDecl = method.sourceMethod();
1625
	if (methodDecl != null) {
1626
		if (method.parameters != Binding.NO_PARAMETERS)
1627
			methodDecl.createArgumentBindings();
1628
		if ((findNonNullDefault(methodDecl.scope, methodDecl.scope.environment()) == NONNULL_BY_DEFAULT)) {
1629
			method.fillInDefaultNonNullness();
1630
		}
1631
	}
1632
}
1633
private void evaluateNullAnnotations(long annotationTagBits) {
1634
	if (this.nullnessDefaultInitialized > 0 || !this.scope.compilerOptions().isAnnotationBasedNullAnalysisEnabled)
1635
		return;
1636
	this.nullnessDefaultInitialized = 1;
1637
	// transfer nullness info from tagBits to this.nullnessDefaultAnnotation
1638
	int newDefaultNullness = NO_NULL_DEFAULT;
1639
	if ((annotationTagBits & TagBits.AnnotationNullUnspecifiedByDefault) != 0)
1640
		newDefaultNullness = NULL_UNSPECIFIED_BY_DEFAULT;
1641
	else if ((annotationTagBits & TagBits.AnnotationNonNullByDefault) != 0)
1642
		newDefaultNullness = NONNULL_BY_DEFAULT;
1643
	if (newDefaultNullness != NO_NULL_DEFAULT) {
1644
		if (CharOperation.equals(this.sourceName, TypeConstants.PACKAGE_INFO_NAME)) {
1645
			getPackage().defaultNullness = newDefaultNullness;
1646
		} else {
1647
			this.defaultNullness = newDefaultNullness;
1648
			TypeDeclaration typeDecl = this.scope.referenceContext;
1649
			long nullDefaultBits = annotationTagBits & (TagBits.AnnotationNullUnspecifiedByDefault|TagBits.AnnotationNonNullByDefault);
1650
			checkRedundantNullnessDefaultRecurse(typeDecl, typeDecl.annotations, nullDefaultBits);
1651
		}
1652
	}
1653
}
1654
1655
protected void checkRedundantNullnessDefaultRecurse(ASTNode location, Annotation[] annotations, long annotationTagBits) {
1656
	if (this.fPackage.defaultNullness != NO_NULL_DEFAULT) {
1657
		if ((this.fPackage.defaultNullness == NONNULL_BY_DEFAULT
1658
				&& ((annotationTagBits & TagBits.AnnotationNonNullByDefault) != 0))) {
1659
			this.scope.problemReporter().nullDefaultAnnotationIsRedundant(location, annotations, this.fPackage);
1660
		}
1661
		return;
1662
	}
1663
}
1664
1665
// return: should caller continue searching?
1666
protected boolean checkRedundantNullnessDefaultOne(ASTNode location, Annotation[] annotations, long annotationTagBits) {
1667
	int thisDefault = this.defaultNullness;
1668
	if (thisDefault == NONNULL_BY_DEFAULT) {
1669
		if ((annotationTagBits & TagBits.AnnotationNonNullByDefault) != 0) {
1670
			this.scope.problemReporter().nullDefaultAnnotationIsRedundant(location, annotations, this);
1671
		}
1672
		return false; // different default means inner default is not redundant -> we're done
1673
	}
1674
	return true;
1675
}
1676
1677
/**
1678
 * Answer the nullness default applicable at the given method binding.
1679
 * Possible values: {@link Binding#NO_NULL_DEFAULT}, {@link Binding#NULL_UNSPECIFIED_BY_DEFAULT}, {@link Binding#NONNULL_BY_DEFAULT}.
1680
 * @param currentScope where to start search for lexically enclosing default
1681
 * @param environment gateway to options
1682
 */
1683
private int findNonNullDefault(Scope currentScope, LookupEnvironment environment) {
1684
	// find the applicable default inside->out:
1685
1686
	SourceTypeBinding currentType = null;
1687
	while (currentScope != null) {
1688
		switch (currentScope.kind) {
1689
			case Scope.METHOD_SCOPE:
1690
				AbstractMethodDeclaration referenceMethod = ((MethodScope)currentScope).referenceMethod();
1691
				if (referenceMethod != null && referenceMethod.binding != null) {
1692
					long methodTagBits = referenceMethod.binding.tagBits;
1693
					if ((methodTagBits & TagBits.AnnotationNonNullByDefault) != 0)
1694
						return NONNULL_BY_DEFAULT;
1695
					if ((methodTagBits & TagBits.AnnotationNullUnspecifiedByDefault) != 0)
1696
						return NULL_UNSPECIFIED_BY_DEFAULT;
1697
				}
1698
				break;
1699
			case Scope.CLASS_SCOPE:
1700
				currentType = ((ClassScope)currentScope).referenceContext.binding;
1701
				if (currentType != null) {
1702
					int foundDefaultNullness = currentType.defaultNullness;
1703
					if (foundDefaultNullness != NO_NULL_DEFAULT) {
1704
						return foundDefaultNullness;
1705
					}
1706
				}
1707
				break;
1708
		}
1709
		currentScope = currentScope.parent;
1710
	}
1711
1712
	// package
1713
	if (currentType != null) {
1714
		int foundDefaultNullness = currentType.getPackage().defaultNullness;
1715
		if (foundDefaultNullness != NO_NULL_DEFAULT) {
1716
			return foundDefaultNullness;
1717
		}
1718
	}
1719
1720
	return NO_NULL_DEFAULT;
1721
}
1722
1576
public AnnotationHolder retrieveAnnotationHolder(Binding binding, boolean forceInitialization) {
1723
public AnnotationHolder retrieveAnnotationHolder(Binding binding, boolean forceInitialization) {
1577
	if (forceInitialization)
1724
	if (forceInitialization)
1578
		binding.getAnnotationTagBits(); // ensure annotations are up to date
1725
		binding.getAnnotationTagBits(); // ensure annotations are up to date
(-)a/org.eclipse.jdt.core/compiler/org/eclipse/jdt/internal/compiler/lookup/TagBits.java (-9 / +16 lines)
Lines 1-5 Link Here
1
/*******************************************************************************
1
/*******************************************************************************
2
 * Copyright (c) 2000, 2011 IBM Corporation and others.
2
 * Copyright (c) 2000, 2012 IBM Corporation and others.
3
 * All rights reserved. This program and the accompanying materials
3
 * All rights reserved. This program and the accompanying materials
4
 * are made available under the terms of the Eclipse Public License v1.0
4
 * are made available under the terms of the Eclipse Public License v1.0
5
 * which accompanies this distribution, and is available at
5
 * which accompanies this distribution, and is available at
Lines 7-12 Link Here
7
 * 
7
 * 
8
 * Contributors:
8
 * Contributors:
9
 *     IBM Corporation - initial API and implementation
9
 *     IBM Corporation - initial API and implementation
10
 *     Stephan Herrmann - Contribution for bug 186342 - [compiler][null] Using annotations for null checking
10
 *******************************************************************************/
11
 *******************************************************************************/
11
package org.eclipse.jdt.internal.compiler.lookup;
12
package org.eclipse.jdt.internal.compiler.lookup;
12
13
Lines 128-137 Link Here
128
	long AnnotationSafeVarargs = ASTNode.Bit52L;
129
	long AnnotationSafeVarargs = ASTNode.Bit52L;
129
	/** @since 3.7 - java 7 MethodHandle.invokeExact(..)/invokeGeneric(..)*/
130
	/** @since 3.7 - java 7 MethodHandle.invokeExact(..)/invokeGeneric(..)*/
130
	long AnnotationPolymorphicSignature = ASTNode.Bit53L;
131
	long AnnotationPolymorphicSignature = ASTNode.Bit53L;
131
	/** @since 3.8 */
132
	/** @since 3.8 null annotation for MethodBinding or LocalVariableBinding (argument): */
132
	long AnnotationPreDestroy = ASTNode.Bit54L;
133
	long AnnotationNullable = ASTNode.Bit56L;
133
	/** @since 3.8 */
134
	/** @since 3.8 null annotation for MethodBinding or LocalVariableBinding (argument): */
134
	long AnnotationPostConstruct = ASTNode.Bit55L;
135
	long AnnotationNonNull = ASTNode.Bit57L;
136
	/** @since 3.8 null-default annotation for PackageBinding or TypeBinding or MethodBinding: */
137
	long AnnotationNonNullByDefault = ASTNode.Bit58L;
138
	/** @since 3.8 canceling null-default annotation for PackageBinding or TypeBinding or MethodBinding: */
139
	long AnnotationNullUnspecifiedByDefault = ASTNode.Bit59L;
135
140
136
	long AllStandardAnnotationsMask =
141
	long AllStandardAnnotationsMask =
137
				  AnnotationTargetMASK
142
				  AnnotationTargetMASK
Lines 143-153 Link Here
143
				| AnnotationSuppressWarnings
148
				| AnnotationSuppressWarnings
144
				| AnnotationSafeVarargs
149
				| AnnotationSafeVarargs
145
				| AnnotationPolymorphicSignature
150
				| AnnotationPolymorphicSignature
146
				| AnnotationPostConstruct
151
				| AnnotationNullable
147
				| AnnotationPreDestroy;
152
				| AnnotationNonNull
153
				| AnnotationNonNullByDefault
154
				| AnnotationNullUnspecifiedByDefault;
148
155
149
	long DefaultValueResolved = ASTNode.Bit56L;
156
	long DefaultValueResolved = ASTNode.Bit60L;
150
157
151
	// set when type contains non-private constructor(s)
158
	// set when type contains non-private constructor(s)
152
	long HasNonPrivateConstructor = ASTNode.Bit57L;
159
	long HasNonPrivateConstructor = ASTNode.Bit61L;
153
}
160
}
(-)a/org.eclipse.jdt.core/compiler/org/eclipse/jdt/internal/compiler/lookup/TypeConstants.java (-13 / +60 lines)
Lines 1-5 Link Here
1
/*******************************************************************************
1
/*******************************************************************************
2
 * Copyright (c) 2000, 2011 IBM Corporation and others.
2
 * Copyright (c) 2000, 2012 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 - Contributions for
11
 *								bug 349326 - [1.7] new warning for missing try-with-resources
12
 *								bug 358903 - Filter practically unimportant resource leak warnings
10
 *******************************************************************************/
13
 *******************************************************************************/
11
package org.eclipse.jdt.internal.compiler.lookup;
14
package org.eclipse.jdt.internal.compiler.lookup;
12
15
Lines 18-23 Link Here
18
	char[] LANG = "lang".toCharArray(); //$NON-NLS-1$
21
	char[] LANG = "lang".toCharArray(); //$NON-NLS-1$
19
	char[] IO = "io".toCharArray(); //$NON-NLS-1$
22
	char[] IO = "io".toCharArray(); //$NON-NLS-1$
20
	char[] UTIL = "util".toCharArray(); //$NON-NLS-1$
23
	char[] UTIL = "util".toCharArray(); //$NON-NLS-1$
24
	char[] ZIP = "zip".toCharArray(); //$NON-NLS-1$
21
	char[] ANNOTATION = "annotation".toCharArray(); //$NON-NLS-1$
25
	char[] ANNOTATION = "annotation".toCharArray(); //$NON-NLS-1$
22
	char[] REFLECT = "reflect".toCharArray(); //$NON-NLS-1$
26
	char[] REFLECT = "reflect".toCharArray(); //$NON-NLS-1$
23
	char[] LENGTH = "length".toCharArray(); //$NON-NLS-1$
27
	char[] LENGTH = "length".toCharArray(); //$NON-NLS-1$
Lines 123-128 Link Here
123
	char[][] JAVA_LANG_ANNOTATION_ELEMENTTYPE = {JAVA, LANG, ANNOTATION, "ElementType".toCharArray()}; //$NON-NLS-1$
127
	char[][] JAVA_LANG_ANNOTATION_ELEMENTTYPE = {JAVA, LANG, ANNOTATION, "ElementType".toCharArray()}; //$NON-NLS-1$
124
	char[][] JAVA_LANG_REFLECT_FIELD = new char[][] {JAVA, LANG, REFLECT, "Field".toCharArray()}; //$NON-NLS-1$
128
	char[][] JAVA_LANG_REFLECT_FIELD = new char[][] {JAVA, LANG, REFLECT, "Field".toCharArray()}; //$NON-NLS-1$
125
	char[][] JAVA_LANG_REFLECT_METHOD = new char[][] {JAVA, LANG, REFLECT, "Method".toCharArray()}; //$NON-NLS-1$
129
	char[][] JAVA_LANG_REFLECT_METHOD = new char[][] {JAVA, LANG, REFLECT, "Method".toCharArray()}; //$NON-NLS-1$
130
	char[][] JAVA_IO_CLOSEABLE = new char[][] { JAVA, IO, "Closeable".toCharArray()};//$NON-NLS-1$
126
	char[][] JAVA_IO_OBJECTSTREAMEXCEPTION = new char[][] { JAVA, IO, "ObjectStreamException".toCharArray()};//$NON-NLS-1$
131
	char[][] JAVA_IO_OBJECTSTREAMEXCEPTION = new char[][] { JAVA, IO, "ObjectStreamException".toCharArray()};//$NON-NLS-1$
127
	char[][] JAVA_IO_EXTERNALIZABLE = {JAVA, IO, "Externalizable".toCharArray()}; //$NON-NLS-1$
132
	char[][] JAVA_IO_EXTERNALIZABLE = {JAVA, IO, "Externalizable".toCharArray()}; //$NON-NLS-1$
128
	char[][] JAVA_IO_IOEXCEPTION = new char[][] { JAVA, IO, "IOException".toCharArray()};//$NON-NLS-1$
133
	char[][] JAVA_IO_IOEXCEPTION = new char[][] { JAVA, IO, "IOException".toCharArray()};//$NON-NLS-1$
Lines 151-156 Link Here
151
			"MethodHandle$PolymorphicSignature".toCharArray() //$NON-NLS-1$
156
			"MethodHandle$PolymorphicSignature".toCharArray() //$NON-NLS-1$
152
	};
157
	};
153
	char[][] JAVA_LANG_AUTOCLOSEABLE =  {JAVA, LANG, "AutoCloseable".toCharArray()}; //$NON-NLS-1$
158
	char[][] JAVA_LANG_AUTOCLOSEABLE =  {JAVA, LANG, "AutoCloseable".toCharArray()}; //$NON-NLS-1$
159
	char[] CLOSE = "close".toCharArray(); //$NON-NLS-1$
160
	// white lists of closeables:
161
	char[][] JAVA_IO_WRAPPER_CLOSEABLES = new char[][] {
162
		"BufferedInputStream".toCharArray(), //$NON-NLS-1$
163
		"BufferedOutputStream".toCharArray(), //$NON-NLS-1$
164
		"BufferedReader".toCharArray(), //$NON-NLS-1$
165
		"BufferedWriter".toCharArray(), //$NON-NLS-1$
166
		"InputStreamReader".toCharArray(), //$NON-NLS-1$
167
		"PrintWriter".toCharArray(),  //$NON-NLS-1$
168
		"LineNumberReader".toCharArray(), //$NON-NLS-1$
169
		"DataInputStream".toCharArray(), //$NON-NLS-1$
170
		"DataOutputStream".toCharArray(), //$NON-NLS-1$
171
		"ObjectInputStream".toCharArray(), //$NON-NLS-1$
172
		"ObjectOutputStream".toCharArray(), //$NON-NLS-1$
173
		"FilterInputStream".toCharArray(), //$NON-NLS-1$
174
		"FilterOutputStream".toCharArray(), //$NON-NLS-1$
175
		"DataInputStream".toCharArray(), //$NON-NLS-1$
176
		"DataOutputStream".toCharArray(), //$NON-NLS-1$
177
		"PushbackInputStream".toCharArray(), //$NON-NLS-1$
178
		"SequenceInputStream".toCharArray(), //$NON-NLS-1$
179
		"PrintStream".toCharArray(), //$NON-NLS-1$
180
		"PushbackReader".toCharArray(), //$NON-NLS-1$
181
		"OutputStreamWriter".toCharArray(), //$NON-NLS-1$
182
	};
183
	char[][] JAVA_UTIL_ZIP_WRAPPER_CLOSEABLES = new char[][] {
184
		"GZIPInputStream".toCharArray(), //$NON-NLS-1$
185
		"InflaterInputStream".toCharArray(), //$NON-NLS-1$
186
		"DeflaterInputStream".toCharArray(), //$NON-NLS-1$
187
		"CheckedInputStream".toCharArray(), //$NON-NLS-1$
188
		"ZipInputStream".toCharArray(), //$NON-NLS-1$
189
		"JarInputStream".toCharArray(), //$NON-NLS-1$
190
		"GZIPOutputStream".toCharArray(), //$NON-NLS-1$
191
		"InflaterOutputStream".toCharArray(), //$NON-NLS-1$
192
		"DeflaterOutputStream".toCharArray(), //$NON-NLS-1$
193
		"CheckedOutputStream".toCharArray(), //$NON-NLS-1$
194
		"ZipOutputStream".toCharArray(), //$NON-NLS-1$
195
		"JarOutputStream".toCharArray(), //$NON-NLS-1$
196
	};
197
	char[][][] OTHER_WRAPPER_CLOSEABLES = new char[][][] {
198
		{JAVA, "security".toCharArray(), "DigestInputStream".toCharArray()}, //$NON-NLS-1$ //$NON-NLS-2$
199
		{JAVA, "security".toCharArray(), "DigestOutputStream".toCharArray()}, //$NON-NLS-1$ //$NON-NLS-2$
200
		{JAVA, "beans".toCharArray(), "XMLEncoder".toCharArray()}, //$NON-NLS-1$ //$NON-NLS-2$
201
		{JAVA, "beans".toCharArray(), "XMLDecoder".toCharArray()}, //$NON-NLS-1$ //$NON-NLS-2$
202
		{JAVAX, "sound".toCharArray(), "sampled".toCharArray(), "AudioInputStream".toCharArray()}, //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
203
	};
204
	char[][] JAVA_IO_RESOURCE_FREE_CLOSEABLES = new char[][] {			
205
		"StringReader".toCharArray(), //$NON-NLS-1$
206
		"StringWriter".toCharArray(), //$NON-NLS-1$
207
		"ByteArrayInputStream".toCharArray(), //$NON-NLS-1$
208
		"ByteArrayOutputStream".toCharArray(), //$NON-NLS-1$
209
		"CharArrayReader".toCharArray(), //$NON-NLS-1$
210
		"CharArrayWriter".toCharArray(), //$NON-NLS-1$
211
		"StringBufferInputStream".toCharArray(), //$NON-NLS-1$
212
	};
154
213
155
	// Constraints for generic type argument inference
214
	// Constraints for generic type argument inference
156
	int CONSTRAINT_EQUAL = 0;		// Actual = Formal
215
	int CONSTRAINT_EQUAL = 0;		// Actual = Formal
Lines 174-191 Link Here
174
	char[] SYNTHETIC_ACCESS_METHOD_PREFIX =  "access$".toCharArray(); //$NON-NLS-1$
233
	char[] SYNTHETIC_ACCESS_METHOD_PREFIX =  "access$".toCharArray(); //$NON-NLS-1$
175
	char[] SYNTHETIC_ENUM_CONSTANT_INITIALIZATION_METHOD_PREFIX =  " enum constant initialization$".toCharArray(); //$NON-NLS-1$
234
	char[] SYNTHETIC_ENUM_CONSTANT_INITIALIZATION_METHOD_PREFIX =  " enum constant initialization$".toCharArray(); //$NON-NLS-1$
176
	char[] SYNTHETIC_STATIC_FACTORY =  "<factory>".toCharArray(); //$NON-NLS-1$
235
	char[] SYNTHETIC_STATIC_FACTORY =  "<factory>".toCharArray(); //$NON-NLS-1$
177
	char[][] JAVAX_ANNOTATION_POSTCONSTRUCT =
178
			new char[][] {
179
				JAVAX,
180
				ANNOTATION,
181
				"PostConstruct".toCharArray() //$NON-NLS-1$
182
			};
183
	char[][] JAVAX_ANNOTATION_PREDESTROY =
184
			new char[][] {
185
				JAVAX,
186
				ANNOTATION,
187
				"PreDestroy".toCharArray() //$NON-NLS-1$
188
			};
189
236
190
	// synthetic package-info name
237
	// synthetic package-info name
191
	public static final char[] PACKAGE_INFO_NAME = "package-info".toCharArray(); //$NON-NLS-1$
238
	public static final char[] PACKAGE_INFO_NAME = "package-info".toCharArray(); //$NON-NLS-1$
(-)a/org.eclipse.jdt.core/compiler/org/eclipse/jdt/internal/compiler/lookup/TypeIds.java (-6 / +42 lines)
Lines 1-5 Link Here
1
/*******************************************************************************
1
/*******************************************************************************
2
 * Copyright (c) 2000, 2011 IBM Corporation and others.
2
 * Copyright (c) 2000, 2012 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 - Contributions for
11
 *     							bug 349326 - [1.7] new warning for missing try-with-resources
12
 *     							bug 359362 - FUP of bug 349326: Resource leak on non-Closeable resource
13
 *								bug 186342 - [compiler][null] Using annotations for null checking
14
 *								bug 358903 - Filter practically unimportant resource leak warnings
10
 *******************************************************************************/
15
 *******************************************************************************/
11
package org.eclipse.jdt.internal.compiler.lookup;
16
package org.eclipse.jdt.internal.compiler.lookup;
12
17
Lines 96-106 Link Here
96
101
97
	// java 7 java.lang.AutoCloseable
102
	// java 7 java.lang.AutoCloseable
98
	final int T_JavaLangAutoCloseable = 62;
103
	final int T_JavaLangAutoCloseable = 62;
99
104
	
100
	// new in 3.8
105
	// new in 3.8 for null annotations:
101
	final int T_JavaxAnnotationPostConstruct = 63;
106
	final int T_ConfiguredAnnotationNullable = 65;
102
107
	final int T_ConfiguredAnnotationNonNull = 66;
103
	final int T_JavaxAnnotationPreDestroy = 64;
108
	final int T_ConfiguredAnnotationNonNullByDefault = 67;
104
109
105
	final int NoId = Integer.MAX_VALUE;
110
	final int NoId = Integer.MAX_VALUE;
106
111
Lines 182-185 Link Here
182
	final int Object2boolean = T_JavaLangObject + (T_boolean << 4);
187
	final int Object2boolean = T_JavaLangObject + (T_boolean << 4);
183
	final int BOXING = 0x200;
188
	final int BOXING = 0x200;
184
	final int UNBOXING = 0x400;
189
	final int UNBOXING = 0x400;
190
191
	/**
192
	 * Marks a type whose type bits have not yet been initialized.
193
	 * @see ReferenceBinding#hasTypeBit(int)
194
	 */
195
	final int BitUninitialized = 0x8000000;
196
	/** 
197
	 * Marks all sub-types of java.lang.AutoCloseable.
198
	 * @see ReferenceBinding#hasTypeBit(int)
199
	 */
200
	final int BitAutoCloseable = 1;
201
	/** 
202
	 * Marks all sub-types of java.io.Closeable.
203
	 * @see ReferenceBinding#hasTypeBit(int)
204
	 */
205
	final int BitCloseable = 2;
206
	/**
207
	 * Bit for members of a white list:
208
	 * Subtypes of Closeable that wrap another resource without directly holding any OS resources. 
209
	 */
210
	final int BitWrapperCloseable = 4;
211
	/**
212
	 * Bit for members of a white list:
213
	 * Subtypes of Closeable that do not hold an OS resource that needs to be released.
214
	 */
215
	final int BitResourceFreeCloseable = 8;
216
	
217
	/**
218
	 * Set of type bits that should be inherited by any sub types.
219
	 */
220
	final int InheritableBits = BitAutoCloseable | BitCloseable;
185
}
221
}
(-)a/org.eclipse.jdt.core/compiler/org/eclipse/jdt/internal/compiler/lookup/TypeVariableBinding.java (-2 / +21 lines)
Lines 1-5 Link Here
1
/*******************************************************************************
1
/*******************************************************************************
2
 * Copyright (c) 2000, 2010 IBM Corporation and others.
2
 * Copyright (c) 2000, 2012 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
13
 *     							bug 359362 - FUP of bug 349326: Resource leak on non-Closeable resource
14
 *								bug 358903 - Filter practically unimportant resource leak warnings
11
 *******************************************************************************/
15
 *******************************************************************************/
12
package org.eclipse.jdt.internal.compiler.lookup;
16
package org.eclipse.jdt.internal.compiler.lookup;
13
17
Lines 42-47 Link Here
42
		this.modifiers = ClassFileConstants.AccPublic | ExtraCompilerModifiers.AccGenericSignature; // treat type var as public
46
		this.modifiers = ClassFileConstants.AccPublic | ExtraCompilerModifiers.AccGenericSignature; // treat type var as public
43
		this.tagBits |= TagBits.HasTypeVariable;
47
		this.tagBits |= TagBits.HasTypeVariable;
44
		this.environment = environment;
48
		this.environment = environment;
49
		this.typeBits = TypeIds.BitUninitialized;
45
	}
50
	}
46
51
47
	/**
52
	/**
Lines 307-312 Link Here
307
		return true;
312
		return true;
308
	}
313
	}
309
314
315
	public boolean hasTypeBit(int bit) {
316
		if (this.typeBits == TypeIds.BitUninitialized) {
317
			// initialize from bounds
318
			this.typeBits = 0;
319
			if (this.superclass != null && this.superclass.hasTypeBit(~TypeIds.BitUninitialized))
320
				this.typeBits |= (this.superclass.typeBits & TypeIds.InheritableBits);
321
			if (this.superInterfaces != null)
322
				for (int i = 0, l = this.superInterfaces.length; i < l; i++)
323
					if (this.superInterfaces[i].hasTypeBit(~TypeIds.BitUninitialized))
324
						this.typeBits |= (this.superInterfaces[i].typeBits & TypeIds.InheritableBits);
325
		}
326
		return (this.typeBits & bit) != 0;
327
	}
328
310
	/**
329
	/**
311
	 * Returns true if the type variable is directly bound to a given type
330
	 * Returns true if the type variable is directly bound to a given type
312
	 */
331
	 */
(-)a/org.eclipse.jdt.core/compiler/org/eclipse/jdt/internal/compiler/lookup/UnresolvedReferenceBinding.java (-2 / +7 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) {
Lines 50-56 Link Here
50
		}
55
		}
51
		if (targetType == null || targetType == this) { // could not resolve any better, error was already reported against it
56
		if (targetType == null || targetType == this) { // could not resolve any better, error was already reported against it
52
			// report the missing class file first - only if not resolving a previously missing type
57
			// report the missing class file first - only if not resolving a previously missing type
53
			if ((this.tagBits & TagBits.HasMissingType) == 0) {
58
			if ((this.tagBits & TagBits.HasMissingType) == 0 && !environment.mayTolerateMissingType) {
54
				environment.problemReporter.isClassPathCorrect(
59
				environment.problemReporter.isClassPathCorrect(
55
					this.compoundName,
60
					this.compoundName,
56
					environment.unitBeingCompleted,
61
					environment.unitBeingCompleted,
(-)a/org.eclipse.jdt.core/compiler/org/eclipse/jdt/internal/compiler/lookup/WildcardBinding.java (-1 / +20 lines)
Lines 1-5 Link Here
1
/*******************************************************************************
1
/*******************************************************************************
2
 * Copyright (c) 2005, 2009 IBM Corporation and others.
2
 * Copyright (c) 2005, 2012 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
11
 *     							bug 349326 - [1.7] new warning for missing try-with-resources
12
 *     							bug 359362 - FUP of bug 349326: Resource leak on non-Closeable resource
13
 *								bug 358903 - Filter practically unimportant resource leak warnings
10
 *******************************************************************************/
14
 *******************************************************************************/
11
package org.eclipse.jdt.internal.compiler.lookup;
15
package org.eclipse.jdt.internal.compiler.lookup;
12
16
Lines 54-59 Link Here
54
		if (bound instanceof UnresolvedReferenceBinding)
58
		if (bound instanceof UnresolvedReferenceBinding)
55
			((UnresolvedReferenceBinding) bound).addWrapper(this, environment);
59
			((UnresolvedReferenceBinding) bound).addWrapper(this, environment);
56
		this.tagBits |=  TagBits.HasUnresolvedTypeVariables; // cleared in resolve()
60
		this.tagBits |=  TagBits.HasUnresolvedTypeVariables; // cleared in resolve()
61
		this.typeBits = TypeIds.BitUninitialized;
57
	}
62
	}
58
63
59
	public int kind() {
64
	public int kind() {
Lines 420-425 Link Here
420
		return this.genericType.hashCode();
425
		return this.genericType.hashCode();
421
	}
426
	}
422
427
428
	public boolean hasTypeBit(int bit) {
429
		if (this.typeBits == TypeIds.BitUninitialized) {
430
			// initialize from upper bounds
431
			this.typeBits = 0;
432
			if (this.superclass != null && this.superclass.hasTypeBit(~TypeIds.BitUninitialized))
433
				this.typeBits |= (this.superclass.typeBits & TypeIds.InheritableBits);
434
			if (this.superInterfaces != null)
435
				for (int i = 0, l = this.superInterfaces.length; i < l; i++)
436
					if (this.superInterfaces[i].hasTypeBit(~TypeIds.BitUninitialized))
437
						this.typeBits |= (this.superInterfaces[i].typeBits & TypeIds.InheritableBits);
438
		}
439
		return (this.typeBits & bit) != 0;
440
	}
441
423
	void initialize(ReferenceBinding someGenericType, TypeBinding someBound, TypeBinding[] someOtherBounds) {
442
	void initialize(ReferenceBinding someGenericType, TypeBinding someBound, TypeBinding[] someOtherBounds) {
424
		this.genericType = someGenericType;
443
		this.genericType = someGenericType;
425
		this.bound = someBound;
444
		this.bound = someBound;
(-)a/org.eclipse.jdt.core/compiler/org/eclipse/jdt/internal/compiler/parser/AbstractCommentParser.java (-6 / +8 lines)
Lines 1354-1362 Link Here
1354
			idx++;
1354
			idx++;
1355
			while (this.source[idx] == 'u')
1355
			while (this.source[idx] == 'u')
1356
				idx++;
1356
				idx++;
1357
			if (!(((c1 = ScannerHelper.getNumericValue(this.source[idx++])) > 15 || c1 < 0)
1357
			if (!(((c1 = ScannerHelper.getHexadecimalValue(this.source[idx++])) > 15 || c1 < 0)
1358
					|| ((c2 = ScannerHelper.getNumericValue(this.source[idx++])) > 15 || c2 < 0)
1358
					|| ((c2 = ScannerHelper.getHexadecimalValue(this.source[idx++])) > 15 || c2 < 0)
1359
					|| ((c3 = ScannerHelper.getNumericValue(this.source[idx++])) > 15 || c3 < 0) || ((c4 = ScannerHelper.getNumericValue(this.source[idx++])) > 15 || c4 < 0))) {
1359
					|| ((c3 = ScannerHelper.getHexadecimalValue(this.source[idx++])) > 15 || c3 < 0)
1360
					|| ((c4 = ScannerHelper.getHexadecimalValue(this.source[idx++])) > 15 || c4 < 0))) {
1360
				c = (char) (((c1 * 16 + c2) * 16 + c3) * 16 + c4);
1361
				c = (char) (((c1 * 16 + c2) * 16 + c3) * 16 + c4);
1361
			}
1362
			}
1362
		}
1363
		}
Lines 1473-1481 Link Here
1473
			this.index++;
1474
			this.index++;
1474
			while (this.source[this.index] == 'u')
1475
			while (this.source[this.index] == 'u')
1475
				this.index++;
1476
				this.index++;
1476
			if (!(((c1 = ScannerHelper.getNumericValue(this.source[this.index++])) > 15 || c1 < 0)
1477
			if (!(((c1 = ScannerHelper.getHexadecimalValue(this.source[this.index++])) > 15 || c1 < 0)
1477
					|| ((c2 = ScannerHelper.getNumericValue(this.source[this.index++])) > 15 || c2 < 0)
1478
					|| ((c2 = ScannerHelper.getHexadecimalValue(this.source[this.index++])) > 15 || c2 < 0)
1478
					|| ((c3 = ScannerHelper.getNumericValue(this.source[this.index++])) > 15 || c3 < 0) || ((c4 = ScannerHelper.getNumericValue(this.source[this.index++])) > 15 || c4 < 0))) {
1479
					|| ((c3 = ScannerHelper.getHexadecimalValue(this.source[this.index++])) > 15 || c3 < 0)
1480
					|| ((c4 = ScannerHelper.getHexadecimalValue(this.source[this.index++])) > 15 || c4 < 0))) {
1479
				c = (char) (((c1 * 16 + c2) * 16 + c3) * 16 + c4);
1481
				c = (char) (((c1 * 16 + c2) * 16 + c3) * 16 + c4);
1480
			} else {
1482
			} else {
1481
				// TODO (frederic) currently reset to previous position, perhaps signal a syntax error would be more appropriate
1483
				// TODO (frederic) currently reset to previous position, perhaps signal a syntax error would be more appropriate
(-)a/org.eclipse.jdt.core/compiler/org/eclipse/jdt/internal/compiler/parser/JavadocParser.java (-3 / +4 lines)
Lines 385-393 Link Here
385
			this.index++;
385
			this.index++;
386
			while (this.source[this.index] == 'u')
386
			while (this.source[this.index] == 'u')
387
				this.index++;
387
				this.index++;
388
			if (!(((c1 = ScannerHelper.getNumericValue(this.source[this.index++])) > 15 || c1 < 0)
388
			if (!(((c1 = ScannerHelper.getHexadecimalValue(this.source[this.index++])) > 15 || c1 < 0)
389
					|| ((c2 = ScannerHelper.getNumericValue(this.source[this.index++])) > 15 || c2 < 0)
389
					|| ((c2 = ScannerHelper.getHexadecimalValue(this.source[this.index++])) > 15 || c2 < 0)
390
					|| ((c3 = ScannerHelper.getNumericValue(this.source[this.index++])) > 15 || c3 < 0) || ((c4 = ScannerHelper.getNumericValue(this.source[this.index++])) > 15 || c4 < 0))) {
390
					|| ((c3 = ScannerHelper.getHexadecimalValue(this.source[this.index++])) > 15 || c3 < 0)
391
					|| ((c4 = ScannerHelper.getHexadecimalValue(this.source[this.index++])) > 15 || c4 < 0))) {
391
				first = (char) (((c1 * 16 + c2) * 16 + c3) * 16 + c4);
392
				first = (char) (((c1 * 16 + c2) * 16 + c3) * 16 + c4);
392
			} else {
393
			} else {
393
				this.index = pos;
394
				this.index = pos;
(-)a/org.eclipse.jdt.core/compiler/org/eclipse/jdt/internal/compiler/parser/Parser.java (-1753 / +1771 lines)
Lines 1-5 Link Here
1
/*******************************************************************************
1
/*******************************************************************************
2
 * Copyright (c) 2000, 2011 IBM Corporation and others.
2
 * Copyright (c) 2000, 2012 IBM Corporation and others.
3
 * All rights reserved. This program and the accompanying materials
3
 * All rights reserved. This program and the accompanying materials
4
 * are made available under the terms of the Eclipse Public License v1.0
4
 * are made available under the terms of the Eclipse Public License v1.0
5
 * which accompanies this distribution, and is available at
5
 * which accompanies this distribution, and is available at
Lines 8-13 Link Here
8
 * Contributors:
8
 * Contributors:
9
 *     IBM Corporation - initial API and implementation
9
 *     IBM Corporation - initial API and implementation
10
 *     Tom Tromey - patch for readTable(String) as described in http://bugs.eclipse.org/bugs/show_bug.cgi?id=32196
10
 *     Tom Tromey - patch for readTable(String) as described in http://bugs.eclipse.org/bugs/show_bug.cgi?id=32196
11
 *     Stephan Herrmann - Contribution for Bug 366003 - CCE in ASTNode.resolveAnnotations(ASTNode.java:639)
11
 *******************************************************************************/
12
 *******************************************************************************/
12
package org.eclipse.jdt.internal.compiler.parser;
13
package org.eclipse.jdt.internal.compiler.parser;
13
14
Lines 868-873 Link Here
868
// used for recovery
869
// used for recovery
869
protected int lastJavadocEnd;
870
protected int lastJavadocEnd;
870
public org.eclipse.jdt.internal.compiler.ReadManager readManager;
871
public org.eclipse.jdt.internal.compiler.ReadManager readManager;
872
private boolean shouldDeferRecovery = false; // https://bugs.eclipse.org/bugs/show_bug.cgi?id=291040
871
873
872
public Parser(ProblemReporter problemReporter, boolean optimizeStringLiterals) {
874
public Parser(ProblemReporter problemReporter, boolean optimizeStringLiterals) {
873
875
Lines 2262-2267 Link Here
2262
	// ClassBodyopt ::= $empty
2264
	// ClassBodyopt ::= $empty
2263
	pushOnAstStack(null);
2265
	pushOnAstStack(null);
2264
	this.endPosition = this.rParenPos;
2266
	this.endPosition = this.rParenPos;
2267
	this.shouldDeferRecovery = false;
2265
}
2268
}
2266
protected void consumeClassDeclaration() {
2269
protected void consumeClassDeclaration() {
2267
	// ClassDeclaration ::= ClassHeader ClassBody
2270
	// ClassDeclaration ::= ClassHeader ClassBody
Lines 2993-3005 Link Here
2993
				pos--;
2996
				pos--;
2994
			}
2997
			}
2995
			if (source[pos] == '\\' &&
2998
			if (source[pos] == '\\' &&
2996
					!((c1 = ScannerHelper.getNumericValue(source[this.endStatementPosition - 3])) > 15
2999
					!((c1 = ScannerHelper.getHexadecimalValue(source[this.endStatementPosition - 3])) > 15
2997
						|| c1 < 0
3000
						|| c1 < 0
2998
						|| (c2 = ScannerHelper.getNumericValue(source[this.endStatementPosition - 2])) > 15
3001
						|| (c2 = ScannerHelper.getHexadecimalValue(source[this.endStatementPosition - 2])) > 15
2999
						|| c2 < 0
3002
						|| c2 < 0
3000
						|| (c3 = ScannerHelper.getNumericValue(source[this.endStatementPosition - 1])) > 15
3003
						|| (c3 = ScannerHelper.getHexadecimalValue(source[this.endStatementPosition - 1])) > 15
3001
						|| c3 < 0
3004
						|| c3 < 0
3002
						|| (c4 = ScannerHelper.getNumericValue(source[this.endStatementPosition])) > 15
3005
						|| (c4 = ScannerHelper.getHexadecimalValue(source[this.endStatementPosition])) > 15
3003
						|| c4 < 0) &&
3006
						|| c4 < 0) &&
3004
					((char) (((c1 * 16 + c2) * 16 + c3) * 16 + c4)) == ';'){
3007
					((char) (((c1 * 16 + c2) * 16 + c3) * 16 + c4)) == ';'){
3005
				// we have a Unicode for the ';' (/u003B)
3008
				// we have a Unicode for the ';' (/u003B)
Lines 3104-3109 Link Here
3104
	iteratorForStatement.sourceEnd = localDeclaration.declarationSourceEnd;
3107
	iteratorForStatement.sourceEnd = localDeclaration.declarationSourceEnd;
3105
}
3108
}
3106
protected void consumeEnterAnonymousClassBody(boolean qualified) {
3109
protected void consumeEnterAnonymousClassBody(boolean qualified) {
3110
	this.shouldDeferRecovery = false;
3107
	// EnterAnonymousClassBody ::= $empty
3111
	// EnterAnonymousClassBody ::= $empty
3108
	TypeReference typeReference = getTypeReference(0);
3112
	TypeReference typeReference = getTypeReference(0);
3109
3113
Lines 3943-3948 Link Here
3943
			arg.annotations = new Annotation[length],
3947
			arg.annotations = new Annotation[length],
3944
			0,
3948
			0,
3945
			length);
3949
			length);
3950
		RecoveredType currentRecoveryType = this.currentRecoveryType();
3951
		if (currentRecoveryType != null)
3952
			currentRecoveryType.annotationsConsumed(arg.annotations);
3946
	}
3953
	}
3947
	pushOnAstStack(arg);
3954
	pushOnAstStack(arg);
3948
3955
Lines 5310-7057 Link Here
5310
	// PushRPAREN ::= ')'
5317
	// PushRPAREN ::= ')'
5311
	pushOnIntStack(this.rParenPos);
5318
	pushOnIntStack(this.rParenPos);
5312
}
5319
}
5313
// This method is part of an automatic generation : do NOT edit-modify
5320
// This method is part of an automatic generation : do NOT edit-modify
5314
protected void consumeRule(int act) {
5321
protected void consumeRule(int act) {
5315
  switch ( act ) {
5322
  switch ( act ) {
5316
    case 30 : if (DEBUG) { System.out.println("Type ::= PrimitiveType"); }  //$NON-NLS-1$
5323
    case 30 : if (DEBUG) { System.out.println("Type ::= PrimitiveType"); }  //$NON-NLS-1$
5317
		    consumePrimitiveType();  
5324
		    consumePrimitiveType();  
5318
			break;
5325
			break;
5319
 
5326
 
5320
    case 44 : if (DEBUG) { System.out.println("ReferenceType ::= ClassOrInterfaceType"); }  //$NON-NLS-1$
5327
    case 44 : if (DEBUG) { System.out.println("ReferenceType ::= ClassOrInterfaceType"); }  //$NON-NLS-1$
5321
		    consumeReferenceType();  
5328
		    consumeReferenceType();  
5322
			break;
5329
			break;
5323
 
5330
 
5324
    case 48 : if (DEBUG) { System.out.println("ClassOrInterface ::= Name"); }  //$NON-NLS-1$
5331
    case 48 : if (DEBUG) { System.out.println("ClassOrInterface ::= Name"); }  //$NON-NLS-1$
5325
		    consumeClassOrInterfaceName();  
5332
		    consumeClassOrInterfaceName();  
5326
			break;
5333
			break;
5327
 
5334
 
5328
    case 49 : if (DEBUG) { System.out.println("ClassOrInterface ::= GenericType DOT Name"); }  //$NON-NLS-1$
5335
    case 49 : if (DEBUG) { System.out.println("ClassOrInterface ::= GenericType DOT Name"); }  //$NON-NLS-1$
5329
		    consumeClassOrInterface();  
5336
		    consumeClassOrInterface();  
5330
			break;
5337
			break;
5331
 
5338
 
5332
    case 50 : if (DEBUG) { System.out.println("GenericType ::= ClassOrInterface TypeArguments"); }  //$NON-NLS-1$
5339
    case 50 : if (DEBUG) { System.out.println("GenericType ::= ClassOrInterface TypeArguments"); }  //$NON-NLS-1$
5333
		    consumeGenericType();  
5340
		    consumeGenericType();  
5334
			break;
5341
			break;
5335
 
5342
 
5336
    case 51 : if (DEBUG) { System.out.println("GenericType ::= ClassOrInterface LESS GREATER"); }  //$NON-NLS-1$
5343
    case 51 : if (DEBUG) { System.out.println("GenericType ::= ClassOrInterface LESS GREATER"); }  //$NON-NLS-1$
5337
		    consumeGenericTypeWithDiamond();  
5344
		    consumeGenericTypeWithDiamond();  
5338
			break;
5345
			break;
5339
 
5346
 
5340
    case 52 : if (DEBUG) { System.out.println("ArrayTypeWithTypeArgumentsName ::= GenericType DOT Name"); }  //$NON-NLS-1$
5347
    case 52 : if (DEBUG) { System.out.println("ArrayTypeWithTypeArgumentsName ::= GenericType DOT Name"); }  //$NON-NLS-1$
5341
		    consumeArrayTypeWithTypeArgumentsName();  
5348
		    consumeArrayTypeWithTypeArgumentsName();  
5342
			break;
5349
			break;
5343
 
5350
 
5344
    case 53 : if (DEBUG) { System.out.println("ArrayType ::= PrimitiveType Dims"); }  //$NON-NLS-1$
5351
    case 53 : if (DEBUG) { System.out.println("ArrayType ::= PrimitiveType Dims"); }  //$NON-NLS-1$
5345
		    consumePrimitiveArrayType();  
5352
		    consumePrimitiveArrayType();  
5346
			break;
5353
			break;
5347
 
5354
 
5348
    case 54 : if (DEBUG) { System.out.println("ArrayType ::= Name Dims"); }  //$NON-NLS-1$
5355
    case 54 : if (DEBUG) { System.out.println("ArrayType ::= Name Dims"); }  //$NON-NLS-1$
5349
		    consumeNameArrayType();  
5356
		    consumeNameArrayType();  
5350
			break;
5357
			break;
5351
 
5358
 
5352
    case 55 : if (DEBUG) { System.out.println("ArrayType ::= ArrayTypeWithTypeArgumentsName Dims"); }  //$NON-NLS-1$
5359
    case 55 : if (DEBUG) { System.out.println("ArrayType ::= ArrayTypeWithTypeArgumentsName Dims"); }  //$NON-NLS-1$
5353
		    consumeGenericTypeNameArrayType();  
5360
		    consumeGenericTypeNameArrayType();  
5354
			break;
5361
			break;
5355
 
5362
 
5356
    case 56 : if (DEBUG) { System.out.println("ArrayType ::= GenericType Dims"); }  //$NON-NLS-1$
5363
    case 56 : if (DEBUG) { System.out.println("ArrayType ::= GenericType Dims"); }  //$NON-NLS-1$
5357
		    consumeGenericTypeArrayType();  
5364
		    consumeGenericTypeArrayType();  
5358
			break;
5365
			break;
5359
 
5366
 
5360
    case 61 : if (DEBUG) { System.out.println("QualifiedName ::= Name DOT SimpleName"); }  //$NON-NLS-1$
5367
    case 61 : if (DEBUG) { System.out.println("QualifiedName ::= Name DOT SimpleName"); }  //$NON-NLS-1$
5361
		    consumeQualifiedName();  
5368
		    consumeQualifiedName();  
5362
			break;
5369
			break;
5363
 
5370
 
5364
    case 62 : if (DEBUG) { System.out.println("CompilationUnit ::= EnterCompilationUnit..."); }  //$NON-NLS-1$
5371
    case 62 : if (DEBUG) { System.out.println("CompilationUnit ::= EnterCompilationUnit..."); }  //$NON-NLS-1$
5365
		    consumeCompilationUnit();  
5372
		    consumeCompilationUnit();  
5366
			break;
5373
			break;
5367
 
5374
 
5368
    case 63 : if (DEBUG) { System.out.println("InternalCompilationUnit ::= PackageDeclaration"); }  //$NON-NLS-1$
5375
    case 63 : if (DEBUG) { System.out.println("InternalCompilationUnit ::= PackageDeclaration"); }  //$NON-NLS-1$
5369
		    consumeInternalCompilationUnit();  
5376
		    consumeInternalCompilationUnit();  
5370
			break;
5377
			break;
5371
 
5378
 
5372
    case 64 : if (DEBUG) { System.out.println("InternalCompilationUnit ::= PackageDeclaration..."); }  //$NON-NLS-1$
5379
    case 64 : if (DEBUG) { System.out.println("InternalCompilationUnit ::= PackageDeclaration..."); }  //$NON-NLS-1$
5373
		    consumeInternalCompilationUnit();  
5380
		    consumeInternalCompilationUnit();  
5374
			break;
5381
			break;
5375
 
5382
 
5376
    case 65 : if (DEBUG) { System.out.println("InternalCompilationUnit ::= PackageDeclaration..."); }  //$NON-NLS-1$
5383
    case 65 : if (DEBUG) { System.out.println("InternalCompilationUnit ::= PackageDeclaration..."); }  //$NON-NLS-1$
5377
		    consumeInternalCompilationUnitWithTypes();  
5384
		    consumeInternalCompilationUnitWithTypes();  
5378
			break;
5385
			break;
5379
 
5386
 
5380
    case 66 : if (DEBUG) { System.out.println("InternalCompilationUnit ::= PackageDeclaration..."); }  //$NON-NLS-1$
5387
    case 66 : if (DEBUG) { System.out.println("InternalCompilationUnit ::= PackageDeclaration..."); }  //$NON-NLS-1$
5381
		    consumeInternalCompilationUnitWithTypes();  
5388
		    consumeInternalCompilationUnitWithTypes();  
5382
			break;
5389
			break;
5383
 
5390
 
5384
    case 67 : if (DEBUG) { System.out.println("InternalCompilationUnit ::= ImportDeclarations..."); }  //$NON-NLS-1$
5391
    case 67 : if (DEBUG) { System.out.println("InternalCompilationUnit ::= ImportDeclarations..."); }  //$NON-NLS-1$
5385
		    consumeInternalCompilationUnit();  
5392
		    consumeInternalCompilationUnit();  
5386
			break;
5393
			break;
5387
 
5394
 
5388
    case 68 : if (DEBUG) { System.out.println("InternalCompilationUnit ::= TypeDeclarations"); }  //$NON-NLS-1$
5395
    case 68 : if (DEBUG) { System.out.println("InternalCompilationUnit ::= TypeDeclarations"); }  //$NON-NLS-1$
5389
		    consumeInternalCompilationUnitWithTypes();  
5396
		    consumeInternalCompilationUnitWithTypes();  
5390
			break;
5397
			break;
5391
 
5398
 
5392
    case 69 : if (DEBUG) { System.out.println("InternalCompilationUnit ::= ImportDeclarations..."); }  //$NON-NLS-1$
5399
    case 69 : if (DEBUG) { System.out.println("InternalCompilationUnit ::= ImportDeclarations..."); }  //$NON-NLS-1$
5393
		    consumeInternalCompilationUnitWithTypes();  
5400
		    consumeInternalCompilationUnitWithTypes();  
5394
			break;
5401
			break;
5395
 
5402
 
5396
    case 70 : if (DEBUG) { System.out.println("InternalCompilationUnit ::="); }  //$NON-NLS-1$
5403
    case 70 : if (DEBUG) { System.out.println("InternalCompilationUnit ::="); }  //$NON-NLS-1$
5397
		    consumeEmptyInternalCompilationUnit();  
5404
		    consumeEmptyInternalCompilationUnit();  
5398
			break;
5405
			break;
5399
 
5406
 
5400
    case 71 : if (DEBUG) { System.out.println("ReduceImports ::="); }  //$NON-NLS-1$
5407
    case 71 : if (DEBUG) { System.out.println("ReduceImports ::="); }  //$NON-NLS-1$
5401
		    consumeReduceImports();  
5408
		    consumeReduceImports();  
5402
			break;
5409
			break;
5403
 
5410
 
5404
    case 72 : if (DEBUG) { System.out.println("EnterCompilationUnit ::="); }  //$NON-NLS-1$
5411
    case 72 : if (DEBUG) { System.out.println("EnterCompilationUnit ::="); }  //$NON-NLS-1$
5405
		    consumeEnterCompilationUnit();  
5412
		    consumeEnterCompilationUnit();  
5406
			break;
5413
			break;
5407
 
5414
 
5408
    case 88 : if (DEBUG) { System.out.println("CatchHeader ::= catch LPAREN CatchFormalParameter RPAREN"); }  //$NON-NLS-1$
5415
    case 88 : if (DEBUG) { System.out.println("CatchHeader ::= catch LPAREN CatchFormalParameter RPAREN"); }  //$NON-NLS-1$
5409
		    consumeCatchHeader();  
5416
		    consumeCatchHeader();  
5410
			break;
5417
			break;
5411
 
5418
 
5412
    case 90 : if (DEBUG) { System.out.println("ImportDeclarations ::= ImportDeclarations..."); }  //$NON-NLS-1$
5419
    case 90 : if (DEBUG) { System.out.println("ImportDeclarations ::= ImportDeclarations..."); }  //$NON-NLS-1$
5413
		    consumeImportDeclarations();  
5420
		    consumeImportDeclarations();  
5414
			break;
5421
			break;
5415
 
5422
 
5416
    case 92 : if (DEBUG) { System.out.println("TypeDeclarations ::= TypeDeclarations TypeDeclaration"); }  //$NON-NLS-1$
5423
    case 92 : if (DEBUG) { System.out.println("TypeDeclarations ::= TypeDeclarations TypeDeclaration"); }  //$NON-NLS-1$
5417
		    consumeTypeDeclarations();  
5424
		    consumeTypeDeclarations();  
5418
			break;
5425
			break;
5419
 
5426
 
5420
    case 93 : if (DEBUG) { System.out.println("PackageDeclaration ::= PackageDeclarationName SEMICOLON"); }  //$NON-NLS-1$
5427
    case 93 : if (DEBUG) { System.out.println("PackageDeclaration ::= PackageDeclarationName SEMICOLON"); }  //$NON-NLS-1$
5421
		    consumePackageDeclaration();  
5428
		    consumePackageDeclaration();  
5422
			break;
5429
			break;
5423
 
5430
 
5424
    case 94 : if (DEBUG) { System.out.println("PackageDeclarationName ::= Modifiers package..."); }  //$NON-NLS-1$
5431
    case 94 : if (DEBUG) { System.out.println("PackageDeclarationName ::= Modifiers package..."); }  //$NON-NLS-1$
5425
		    consumePackageDeclarationNameWithModifiers();  
5432
		    consumePackageDeclarationNameWithModifiers();  
5426
			break;
5433
			break;
5427
 
5434
 
5428
    case 95 : if (DEBUG) { System.out.println("PackageDeclarationName ::= PackageComment package Name"); }  //$NON-NLS-1$
5435
    case 95 : if (DEBUG) { System.out.println("PackageDeclarationName ::= PackageComment package Name"); }  //$NON-NLS-1$
5429
		    consumePackageDeclarationName();  
5436
		    consumePackageDeclarationName();  
5430
			break;
5437
			break;
5431
 
5438
 
5432
    case 96 : if (DEBUG) { System.out.println("PackageComment ::="); }  //$NON-NLS-1$
5439
    case 96 : if (DEBUG) { System.out.println("PackageComment ::="); }  //$NON-NLS-1$
5433
		    consumePackageComment();  
5440
		    consumePackageComment();  
5434
			break;
5441
			break;
5435
 
5442
 
5436
    case 101 : if (DEBUG) { System.out.println("SingleTypeImportDeclaration ::=..."); }  //$NON-NLS-1$
5443
    case 101 : if (DEBUG) { System.out.println("SingleTypeImportDeclaration ::=..."); }  //$NON-NLS-1$
5437
		    consumeImportDeclaration();  
5444
		    consumeImportDeclaration();  
5438
			break;
5445
			break;
5439
 
5446
 
5440
    case 102 : if (DEBUG) { System.out.println("SingleTypeImportDeclarationName ::= import Name"); }  //$NON-NLS-1$
5447
    case 102 : if (DEBUG) { System.out.println("SingleTypeImportDeclarationName ::= import Name"); }  //$NON-NLS-1$
5441
		    consumeSingleTypeImportDeclarationName();  
5448
		    consumeSingleTypeImportDeclarationName();  
5442
			break;
5449
			break;
5443
 
5450
 
5444
    case 103 : if (DEBUG) { System.out.println("TypeImportOnDemandDeclaration ::=..."); }  //$NON-NLS-1$
5451
    case 103 : if (DEBUG) { System.out.println("TypeImportOnDemandDeclaration ::=..."); }  //$NON-NLS-1$
5445
		    consumeImportDeclaration();  
5452
		    consumeImportDeclaration();  
5446
			break;
5453
			break;
5447
 
5454
 
5448
    case 104 : if (DEBUG) { System.out.println("TypeImportOnDemandDeclarationName ::= import Name DOT..."); }  //$NON-NLS-1$
5455
    case 104 : if (DEBUG) { System.out.println("TypeImportOnDemandDeclarationName ::= import Name DOT..."); }  //$NON-NLS-1$
5449
		    consumeTypeImportOnDemandDeclarationName();  
5456
		    consumeTypeImportOnDemandDeclarationName();  
5450
			break;
5457
			break;
5451
 
5458
 
5452
     case 107 : if (DEBUG) { System.out.println("TypeDeclaration ::= SEMICOLON"); }  //$NON-NLS-1$
5459
     case 107 : if (DEBUG) { System.out.println("TypeDeclaration ::= SEMICOLON"); }  //$NON-NLS-1$
5453
		    consumeEmptyTypeDeclaration();  
5460
		    consumeEmptyTypeDeclaration();  
5454
			break;
5461
			break;
5455
 
5462
 
5456
    case 111 : if (DEBUG) { System.out.println("Modifiers ::= Modifiers Modifier"); }  //$NON-NLS-1$
5463
    case 111 : if (DEBUG) { System.out.println("Modifiers ::= Modifiers Modifier"); }  //$NON-NLS-1$
5457
		    consumeModifiers2();  
5464
		    consumeModifiers2();  
5458
			break;
5465
			break;
5459
 
5466
 
5460
    case 123 : if (DEBUG) { System.out.println("Modifier ::= Annotation"); }  //$NON-NLS-1$
5467
    case 123 : if (DEBUG) { System.out.println("Modifier ::= Annotation"); }  //$NON-NLS-1$
5461
		    consumeAnnotationAsModifier();  
5468
		    consumeAnnotationAsModifier();  
5462
			break;
5469
			break;
5463
 
5470
 
5464
    case 124 : if (DEBUG) { System.out.println("ClassDeclaration ::= ClassHeader ClassBody"); }  //$NON-NLS-1$
5471
    case 124 : if (DEBUG) { System.out.println("ClassDeclaration ::= ClassHeader ClassBody"); }  //$NON-NLS-1$
5465
		    consumeClassDeclaration();  
5472
		    consumeClassDeclaration();  
5466
			break;
5473
			break;
5467
 
5474
 
5468
    case 125 : if (DEBUG) { System.out.println("ClassHeader ::= ClassHeaderName ClassHeaderExtendsopt..."); }  //$NON-NLS-1$
5475
    case 125 : if (DEBUG) { System.out.println("ClassHeader ::= ClassHeaderName ClassHeaderExtendsopt..."); }  //$NON-NLS-1$
5469
		    consumeClassHeader();  
5476
		    consumeClassHeader();  
5470
			break;
5477
			break;
5471
 
5478
 
5472
    case 126 : if (DEBUG) { System.out.println("ClassHeaderName ::= ClassHeaderName1 TypeParameters"); }  //$NON-NLS-1$
5479
    case 126 : if (DEBUG) { System.out.println("ClassHeaderName ::= ClassHeaderName1 TypeParameters"); }  //$NON-NLS-1$
5473
		    consumeTypeHeaderNameWithTypeParameters();  
5480
		    consumeTypeHeaderNameWithTypeParameters();  
5474
			break;
5481
			break;
5475
 
5482
 
5476
    case 128 : if (DEBUG) { System.out.println("ClassHeaderName1 ::= Modifiersopt class Identifier"); }  //$NON-NLS-1$
5483
    case 128 : if (DEBUG) { System.out.println("ClassHeaderName1 ::= Modifiersopt class Identifier"); }  //$NON-NLS-1$
5477
		    consumeClassHeaderName1();  
5484
		    consumeClassHeaderName1();  
5478
			break;
5485
			break;
5479
 
5486
 
5480
    case 129 : if (DEBUG) { System.out.println("ClassHeaderExtends ::= extends ClassType"); }  //$NON-NLS-1$
5487
    case 129 : if (DEBUG) { System.out.println("ClassHeaderExtends ::= extends ClassType"); }  //$NON-NLS-1$
5481
		    consumeClassHeaderExtends();  
5488
		    consumeClassHeaderExtends();  
5482
			break;
5489
			break;
5483
 
5490
 
5484
    case 130 : if (DEBUG) { System.out.println("ClassHeaderImplements ::= implements InterfaceTypeList"); }  //$NON-NLS-1$
5491
    case 130 : if (DEBUG) { System.out.println("ClassHeaderImplements ::= implements InterfaceTypeList"); }  //$NON-NLS-1$
5485
		    consumeClassHeaderImplements();  
5492
		    consumeClassHeaderImplements();  
5486
			break;
5493
			break;
5487
 
5494
 
5488
    case 132 : if (DEBUG) { System.out.println("InterfaceTypeList ::= InterfaceTypeList COMMA..."); }  //$NON-NLS-1$
5495
    case 132 : if (DEBUG) { System.out.println("InterfaceTypeList ::= InterfaceTypeList COMMA..."); }  //$NON-NLS-1$
5489
		    consumeInterfaceTypeList();  
5496
		    consumeInterfaceTypeList();  
5490
			break;
5497
			break;
5491
 
5498
 
5492
    case 133 : if (DEBUG) { System.out.println("InterfaceType ::= ClassOrInterfaceType"); }  //$NON-NLS-1$
5499
    case 133 : if (DEBUG) { System.out.println("InterfaceType ::= ClassOrInterfaceType"); }  //$NON-NLS-1$
5493
		    consumeInterfaceType();  
5500
		    consumeInterfaceType();  
5494
			break;
5501
			break;
5495
 
5502
 
5496
    case 136 : if (DEBUG) { System.out.println("ClassBodyDeclarations ::= ClassBodyDeclarations..."); }  //$NON-NLS-1$
5503
    case 136 : if (DEBUG) { System.out.println("ClassBodyDeclarations ::= ClassBodyDeclarations..."); }  //$NON-NLS-1$
5497
		    consumeClassBodyDeclarations();  
5504
		    consumeClassBodyDeclarations();  
5498
			break;
5505
			break;
5499
 
5506
 
5500
    case 140 : if (DEBUG) { System.out.println("ClassBodyDeclaration ::= Diet NestedMethod..."); }  //$NON-NLS-1$
5507
    case 140 : if (DEBUG) { System.out.println("ClassBodyDeclaration ::= Diet NestedMethod..."); }  //$NON-NLS-1$
5501
		    consumeClassBodyDeclaration();  
5508
		    consumeClassBodyDeclaration();  
5502
			break;
5509
			break;
5503
 
5510
 
5504
    case 141 : if (DEBUG) { System.out.println("Diet ::="); }  //$NON-NLS-1$
5511
    case 141 : if (DEBUG) { System.out.println("Diet ::="); }  //$NON-NLS-1$
5505
		    consumeDiet();  
5512
		    consumeDiet();  
5506
			break;
5513
			break;
5507
5514
5508
    case 142 : if (DEBUG) { System.out.println("Initializer ::= Diet NestedMethod CreateInitializer..."); }  //$NON-NLS-1$
5515
    case 142 : if (DEBUG) { System.out.println("Initializer ::= Diet NestedMethod CreateInitializer..."); }  //$NON-NLS-1$
5509
		    consumeClassBodyDeclaration();  
5516
		    consumeClassBodyDeclaration();  
5510
			break;
5517
			break;
5511
 
5518
 
5512
    case 143 : if (DEBUG) { System.out.println("CreateInitializer ::="); }  //$NON-NLS-1$
5519
    case 143 : if (DEBUG) { System.out.println("CreateInitializer ::="); }  //$NON-NLS-1$
5513
		    consumeCreateInitializer();  
5520
		    consumeCreateInitializer();  
5514
			break;
5521
			break;
5515
5522
5516
    case 150 : if (DEBUG) { System.out.println("ClassMemberDeclaration ::= SEMICOLON"); }  //$NON-NLS-1$
5523
    case 150 : if (DEBUG) { System.out.println("ClassMemberDeclaration ::= SEMICOLON"); }  //$NON-NLS-1$
5517
		    consumeEmptyTypeDeclaration();  
5524
		    consumeEmptyTypeDeclaration();  
5518
			break;
5525
			break;
5519
5526
5520
    case 153 : if (DEBUG) { System.out.println("FieldDeclaration ::= Modifiersopt Type..."); }  //$NON-NLS-1$
5527
    case 153 : if (DEBUG) { System.out.println("FieldDeclaration ::= Modifiersopt Type..."); }  //$NON-NLS-1$
5521
		    consumeFieldDeclaration();  
5528
		    consumeFieldDeclaration();  
5522
			break;
5529
			break;
5523
 
5530
 
5524
    case 155 : if (DEBUG) { System.out.println("VariableDeclarators ::= VariableDeclarators COMMA..."); }  //$NON-NLS-1$
5531
    case 155 : if (DEBUG) { System.out.println("VariableDeclarators ::= VariableDeclarators COMMA..."); }  //$NON-NLS-1$
5525
		    consumeVariableDeclarators();  
5532
		    consumeVariableDeclarators();  
5526
			break;
5533
			break;
5527
 
5534
 
5528
    case 158 : if (DEBUG) { System.out.println("EnterVariable ::="); }  //$NON-NLS-1$
5535
    case 158 : if (DEBUG) { System.out.println("EnterVariable ::="); }  //$NON-NLS-1$
5529
		    consumeEnterVariable();  
5536
		    consumeEnterVariable();  
5530
			break;
5537
			break;
5531
 
5538
 
5532
    case 159 : if (DEBUG) { System.out.println("ExitVariableWithInitialization ::="); }  //$NON-NLS-1$
5539
    case 159 : if (DEBUG) { System.out.println("ExitVariableWithInitialization ::="); }  //$NON-NLS-1$
5533
		    consumeExitVariableWithInitialization();  
5540
		    consumeExitVariableWithInitialization();  
5534
			break;
5541
			break;
5535
 
5542
 
5536
    case 160 : if (DEBUG) { System.out.println("ExitVariableWithoutInitialization ::="); }  //$NON-NLS-1$
5543
    case 160 : if (DEBUG) { System.out.println("ExitVariableWithoutInitialization ::="); }  //$NON-NLS-1$
5537
		    consumeExitVariableWithoutInitialization();  
5544
		    consumeExitVariableWithoutInitialization();  
5538
			break;
5545
			break;
5539
 
5546
 
5540
    case 161 : if (DEBUG) { System.out.println("ForceNoDiet ::="); }  //$NON-NLS-1$
5547
    case 161 : if (DEBUG) { System.out.println("ForceNoDiet ::="); }  //$NON-NLS-1$
5541
		    consumeForceNoDiet();  
5548
		    consumeForceNoDiet();  
5542
			break;
5549
			break;
5543
 
5550
 
5544
    case 162 : if (DEBUG) { System.out.println("RestoreDiet ::="); }  //$NON-NLS-1$
5551
    case 162 : if (DEBUG) { System.out.println("RestoreDiet ::="); }  //$NON-NLS-1$
5545
		    consumeRestoreDiet();  
5552
		    consumeRestoreDiet();  
5546
			break;
5553
			break;
5547
 
5554
 
5548
    case 167 : if (DEBUG) { System.out.println("MethodDeclaration ::= MethodHeader MethodBody"); }  //$NON-NLS-1$
5555
    case 167 : if (DEBUG) { System.out.println("MethodDeclaration ::= MethodHeader MethodBody"); }  //$NON-NLS-1$
5549
		    // set to true to consume a method with a body
5556
		    // set to true to consume a method with a body
5550
 consumeMethodDeclaration(true);  
5557
 consumeMethodDeclaration(true);  
5551
			break;
5558
			break;
5552
 
5559
 
5553
    case 168 : if (DEBUG) { System.out.println("AbstractMethodDeclaration ::= MethodHeader SEMICOLON"); }  //$NON-NLS-1$
5560
    case 168 : if (DEBUG) { System.out.println("AbstractMethodDeclaration ::= MethodHeader SEMICOLON"); }  //$NON-NLS-1$
5554
		    // set to false to consume a method without body
5561
		    // set to false to consume a method without body
5555
 consumeMethodDeclaration(false);  
5562
 consumeMethodDeclaration(false);  
5556
			break;
5563
			break;
5557
 
5564
 
5558
    case 169 : if (DEBUG) { System.out.println("MethodHeader ::= MethodHeaderName FormalParameterListopt"); }  //$NON-NLS-1$
5565
    case 169 : if (DEBUG) { System.out.println("MethodHeader ::= MethodHeaderName FormalParameterListopt"); }  //$NON-NLS-1$
5559
		    consumeMethodHeader();  
5566
		    consumeMethodHeader();  
5560
			break;
5567
			break;
5561
 
5568
 
5562
    case 170 : if (DEBUG) { System.out.println("MethodHeaderName ::= Modifiersopt TypeParameters Type..."); }  //$NON-NLS-1$
5569
    case 170 : if (DEBUG) { System.out.println("MethodHeaderName ::= Modifiersopt TypeParameters Type..."); }  //$NON-NLS-1$
5563
		    consumeMethodHeaderNameWithTypeParameters(false);  
5570
		    consumeMethodHeaderNameWithTypeParameters(false);  
5564
			break;
5571
			break;
5565
 
5572
 
5566
    case 171 : if (DEBUG) { System.out.println("MethodHeaderName ::= Modifiersopt Type Identifier LPAREN"); }  //$NON-NLS-1$
5573
    case 171 : if (DEBUG) { System.out.println("MethodHeaderName ::= Modifiersopt Type Identifier LPAREN"); }  //$NON-NLS-1$
5567
		    consumeMethodHeaderName(false);  
5574
		    consumeMethodHeaderName(false);  
5568
			break;
5575
			break;
5569
 
5576
 
5570
    case 172 : if (DEBUG) { System.out.println("MethodHeaderRightParen ::= RPAREN"); }  //$NON-NLS-1$
5577
    case 172 : if (DEBUG) { System.out.println("MethodHeaderRightParen ::= RPAREN"); }  //$NON-NLS-1$
5571
		    consumeMethodHeaderRightParen();  
5578
		    consumeMethodHeaderRightParen();  
5572
			break;
5579
			break;
5573
 
5580
 
5574
    case 173 : if (DEBUG) { System.out.println("MethodHeaderExtendedDims ::= Dimsopt"); }  //$NON-NLS-1$
5581
    case 173 : if (DEBUG) { System.out.println("MethodHeaderExtendedDims ::= Dimsopt"); }  //$NON-NLS-1$
5575
		    consumeMethodHeaderExtendedDims();  
5582
		    consumeMethodHeaderExtendedDims();  
5576
			break;
5583
			break;
5577
 
5584
 
5578
    case 174 : if (DEBUG) { System.out.println("MethodHeaderThrowsClause ::= throws ClassTypeList"); }  //$NON-NLS-1$
5585
    case 174 : if (DEBUG) { System.out.println("MethodHeaderThrowsClause ::= throws ClassTypeList"); }  //$NON-NLS-1$
5579
		    consumeMethodHeaderThrowsClause();  
5586
		    consumeMethodHeaderThrowsClause();  
5580
			break;
5587
			break;
5581
 
5588
 
5582
    case 175 : if (DEBUG) { System.out.println("ConstructorHeader ::= ConstructorHeaderName..."); }  //$NON-NLS-1$
5589
    case 175 : if (DEBUG) { System.out.println("ConstructorHeader ::= ConstructorHeaderName..."); }  //$NON-NLS-1$
5583
		    consumeConstructorHeader();  
5590
		    consumeConstructorHeader();  
5584
			break;
5591
			break;
5585
 
5592
 
5586
    case 176 : if (DEBUG) { System.out.println("ConstructorHeaderName ::= Modifiersopt TypeParameters..."); }  //$NON-NLS-1$
5593
    case 176 : if (DEBUG) { System.out.println("ConstructorHeaderName ::= Modifiersopt TypeParameters..."); }  //$NON-NLS-1$
5587
		    consumeConstructorHeaderNameWithTypeParameters();  
5594
		    consumeConstructorHeaderNameWithTypeParameters();  
5588
			break;
5595
			break;
5589
 
5596
 
5590
    case 177 : if (DEBUG) { System.out.println("ConstructorHeaderName ::= Modifiersopt Identifier LPAREN"); }  //$NON-NLS-1$
5597
    case 177 : if (DEBUG) { System.out.println("ConstructorHeaderName ::= Modifiersopt Identifier LPAREN"); }  //$NON-NLS-1$
5591
		    consumeConstructorHeaderName();  
5598
		    consumeConstructorHeaderName();  
5592
			break;
5599
			break;
5593
 
5600
 
5594
    case 179 : if (DEBUG) { System.out.println("FormalParameterList ::= FormalParameterList COMMA..."); }  //$NON-NLS-1$
5601
    case 179 : if (DEBUG) { System.out.println("FormalParameterList ::= FormalParameterList COMMA..."); }  //$NON-NLS-1$
5595
		    consumeFormalParameterList();  
5602
		    consumeFormalParameterList();  
5596
			break;
5603
			break;
5597
 
5604
 
5598
    case 180 : if (DEBUG) { System.out.println("FormalParameter ::= Modifiersopt Type..."); }  //$NON-NLS-1$
5605
    case 180 : if (DEBUG) { System.out.println("FormalParameter ::= Modifiersopt Type..."); }  //$NON-NLS-1$
5599
		    consumeFormalParameter(false);  
5606
		    consumeFormalParameter(false);  
5600
			break;
5607
			break;
5601
 
5608
 
5602
    case 181 : if (DEBUG) { System.out.println("FormalParameter ::= Modifiersopt Type ELLIPSIS..."); }  //$NON-NLS-1$
5609
    case 181 : if (DEBUG) { System.out.println("FormalParameter ::= Modifiersopt Type ELLIPSIS..."); }  //$NON-NLS-1$
5603
		    consumeFormalParameter(true);  
5610
		    consumeFormalParameter(true);  
5604
			break;
5611
			break;
5605
 
5612
 
5606
    case 182 : if (DEBUG) { System.out.println("CatchFormalParameter ::= Modifiersopt CatchType..."); }  //$NON-NLS-1$
5613
    case 182 : if (DEBUG) { System.out.println("CatchFormalParameter ::= Modifiersopt CatchType..."); }  //$NON-NLS-1$
5607
		    consumeCatchFormalParameter();  
5614
		    consumeCatchFormalParameter();  
5608
			break;
5615
			break;
5609
 
5616
 
5610
    case 183 : if (DEBUG) { System.out.println("CatchType ::= UnionType"); }  //$NON-NLS-1$
5617
    case 183 : if (DEBUG) { System.out.println("CatchType ::= UnionType"); }  //$NON-NLS-1$
5611
		    consumeCatchType();  
5618
		    consumeCatchType();  
5612
			break;
5619
			break;
5613
 
5620
 
5614
    case 184 : if (DEBUG) { System.out.println("UnionType ::= Type"); }  //$NON-NLS-1$
5621
    case 184 : if (DEBUG) { System.out.println("UnionType ::= Type"); }  //$NON-NLS-1$
5615
		    consumeUnionTypeAsClassType();  
5622
		    consumeUnionTypeAsClassType();  
5616
			break;
5623
			break;
5617
 
5624
 
5618
    case 185 : if (DEBUG) { System.out.println("UnionType ::= UnionType OR Type"); }  //$NON-NLS-1$
5625
    case 185 : if (DEBUG) { System.out.println("UnionType ::= UnionType OR Type"); }  //$NON-NLS-1$
5619
		    consumeUnionType();  
5626
		    consumeUnionType();  
5620
			break;
5627
			break;
5621
 
5628
 
5622
    case 187 : if (DEBUG) { System.out.println("ClassTypeList ::= ClassTypeList COMMA ClassTypeElt"); }  //$NON-NLS-1$
5629
    case 187 : if (DEBUG) { System.out.println("ClassTypeList ::= ClassTypeList COMMA ClassTypeElt"); }  //$NON-NLS-1$
5623
		    consumeClassTypeList();  
5630
		    consumeClassTypeList();  
5624
			break;
5631
			break;
5625
 
5632
 
5626
    case 188 : if (DEBUG) { System.out.println("ClassTypeElt ::= ClassType"); }  //$NON-NLS-1$
5633
    case 188 : if (DEBUG) { System.out.println("ClassTypeElt ::= ClassType"); }  //$NON-NLS-1$
5627
		    consumeClassTypeElt();  
5634
		    consumeClassTypeElt();  
5628
			break;
5635
			break;
5629
 
5636
 
5630
    case 189 : if (DEBUG) { System.out.println("MethodBody ::= NestedMethod LBRACE BlockStatementsopt..."); }  //$NON-NLS-1$
5637
    case 189 : if (DEBUG) { System.out.println("MethodBody ::= NestedMethod LBRACE BlockStatementsopt..."); }  //$NON-NLS-1$
5631
		    consumeMethodBody();  
5638
		    consumeMethodBody();  
5632
			break;
5639
			break;
5633
 
5640
 
5634
    case 190 : if (DEBUG) { System.out.println("NestedMethod ::="); }  //$NON-NLS-1$
5641
    case 190 : if (DEBUG) { System.out.println("NestedMethod ::="); }  //$NON-NLS-1$
5635
		    consumeNestedMethod();  
5642
		    consumeNestedMethod();  
5636
			break;
5643
			break;
5637
 
5644
 
5638
    case 191 : if (DEBUG) { System.out.println("StaticInitializer ::= StaticOnly Block"); }  //$NON-NLS-1$
5645
    case 191 : if (DEBUG) { System.out.println("StaticInitializer ::= StaticOnly Block"); }  //$NON-NLS-1$
5639
		    consumeStaticInitializer();  
5646
		    consumeStaticInitializer();  
5640
			break;
5647
			break;
5641
5648
5642
    case 192 : if (DEBUG) { System.out.println("StaticOnly ::= static"); }  //$NON-NLS-1$
5649
    case 192 : if (DEBUG) { System.out.println("StaticOnly ::= static"); }  //$NON-NLS-1$
5643
		    consumeStaticOnly();  
5650
		    consumeStaticOnly();  
5644
			break;
5651
			break;
5645
 
5652
 
5646
    case 193 : if (DEBUG) { System.out.println("ConstructorDeclaration ::= ConstructorHeader MethodBody"); }  //$NON-NLS-1$
5653
    case 193 : if (DEBUG) { System.out.println("ConstructorDeclaration ::= ConstructorHeader MethodBody"); }  //$NON-NLS-1$
5647
		    consumeConstructorDeclaration() ;  
5654
		    consumeConstructorDeclaration() ;  
5648
			break;
5655
			break;
5649
 
5656
 
5650
    case 194 : if (DEBUG) { System.out.println("ConstructorDeclaration ::= ConstructorHeader SEMICOLON"); }  //$NON-NLS-1$
5657
    case 194 : if (DEBUG) { System.out.println("ConstructorDeclaration ::= ConstructorHeader SEMICOLON"); }  //$NON-NLS-1$
5651
		    consumeInvalidConstructorDeclaration() ;  
5658
		    consumeInvalidConstructorDeclaration() ;  
5652
			break;
5659
			break;
5653
 
5660
 
5654
    case 195 : if (DEBUG) { System.out.println("ExplicitConstructorInvocation ::= this LPAREN..."); }  //$NON-NLS-1$
5661
    case 195 : if (DEBUG) { System.out.println("ExplicitConstructorInvocation ::= this LPAREN..."); }  //$NON-NLS-1$
5655
		    consumeExplicitConstructorInvocation(0, THIS_CALL);  
5662
		    consumeExplicitConstructorInvocation(0, THIS_CALL);  
5656
			break;
5663
			break;
5657
 
5664
 
5658
    case 196 : if (DEBUG) { System.out.println("ExplicitConstructorInvocation ::= OnlyTypeArguments this"); }  //$NON-NLS-1$
5665
    case 196 : if (DEBUG) { System.out.println("ExplicitConstructorInvocation ::= OnlyTypeArguments this"); }  //$NON-NLS-1$
5659
		    consumeExplicitConstructorInvocationWithTypeArguments(0,THIS_CALL);  
5666
		    consumeExplicitConstructorInvocationWithTypeArguments(0,THIS_CALL);  
5660
			break;
5667
			break;
5661
 
5668
 
5662
    case 197 : if (DEBUG) { System.out.println("ExplicitConstructorInvocation ::= super LPAREN..."); }  //$NON-NLS-1$
5669
    case 197 : if (DEBUG) { System.out.println("ExplicitConstructorInvocation ::= super LPAREN..."); }  //$NON-NLS-1$
5663
		    consumeExplicitConstructorInvocation(0,SUPER_CALL);  
5670
		    consumeExplicitConstructorInvocation(0,SUPER_CALL);  
5664
			break;
5671
			break;
5665
 
5672
 
5666
    case 198 : if (DEBUG) { System.out.println("ExplicitConstructorInvocation ::= OnlyTypeArguments..."); }  //$NON-NLS-1$
5673
    case 198 : if (DEBUG) { System.out.println("ExplicitConstructorInvocation ::= OnlyTypeArguments..."); }  //$NON-NLS-1$
5667
		    consumeExplicitConstructorInvocationWithTypeArguments(0,SUPER_CALL);  
5674
		    consumeExplicitConstructorInvocationWithTypeArguments(0,SUPER_CALL);  
5668
			break;
5675
			break;
5669
 
5676
 
5670
    case 199 : if (DEBUG) { System.out.println("ExplicitConstructorInvocation ::= Primary DOT super..."); }  //$NON-NLS-1$
5677
    case 199 : if (DEBUG) { System.out.println("ExplicitConstructorInvocation ::= Primary DOT super..."); }  //$NON-NLS-1$
5671
		    consumeExplicitConstructorInvocation(1, SUPER_CALL);  
5678
		    consumeExplicitConstructorInvocation(1, SUPER_CALL);  
5672
			break;
5679
			break;
5673
 
5680
 
5674
    case 200 : if (DEBUG) { System.out.println("ExplicitConstructorInvocation ::= Primary DOT..."); }  //$NON-NLS-1$
5681
    case 200 : if (DEBUG) { System.out.println("ExplicitConstructorInvocation ::= Primary DOT..."); }  //$NON-NLS-1$
5675
		    consumeExplicitConstructorInvocationWithTypeArguments(1, SUPER_CALL);  
5682
		    consumeExplicitConstructorInvocationWithTypeArguments(1, SUPER_CALL);  
5676
			break;
5683
			break;
5677
 
5684
 
5678
    case 201 : if (DEBUG) { System.out.println("ExplicitConstructorInvocation ::= Name DOT super LPAREN"); }  //$NON-NLS-1$
5685
    case 201 : if (DEBUG) { System.out.println("ExplicitConstructorInvocation ::= Name DOT super LPAREN"); }  //$NON-NLS-1$
5679
		    consumeExplicitConstructorInvocation(2, SUPER_CALL);  
5686
		    consumeExplicitConstructorInvocation(2, SUPER_CALL);  
5680
			break;
5687
			break;
5681
 
5688
 
5682
    case 202 : if (DEBUG) { System.out.println("ExplicitConstructorInvocation ::= Name DOT..."); }  //$NON-NLS-1$
5689
    case 202 : if (DEBUG) { System.out.println("ExplicitConstructorInvocation ::= Name DOT..."); }  //$NON-NLS-1$
5683
		    consumeExplicitConstructorInvocationWithTypeArguments(2, SUPER_CALL);  
5690
		    consumeExplicitConstructorInvocationWithTypeArguments(2, SUPER_CALL);  
5684
			break;
5691
			break;
5685
 
5692
 
5686
    case 203 : if (DEBUG) { System.out.println("ExplicitConstructorInvocation ::= Primary DOT this..."); }  //$NON-NLS-1$
5693
    case 203 : if (DEBUG) { System.out.println("ExplicitConstructorInvocation ::= Primary DOT this..."); }  //$NON-NLS-1$
5687
		    consumeExplicitConstructorInvocation(1, THIS_CALL);  
5694
		    consumeExplicitConstructorInvocation(1, THIS_CALL);  
5688
			break;
5695
			break;
5689
 
5696
 
5690
    case 204 : if (DEBUG) { System.out.println("ExplicitConstructorInvocation ::= Primary DOT..."); }  //$NON-NLS-1$
5697
    case 204 : if (DEBUG) { System.out.println("ExplicitConstructorInvocation ::= Primary DOT..."); }  //$NON-NLS-1$
5691
		    consumeExplicitConstructorInvocationWithTypeArguments(1, THIS_CALL);  
5698
		    consumeExplicitConstructorInvocationWithTypeArguments(1, THIS_CALL);  
5692
			break;
5699
			break;
5693
 
5700
 
5694
    case 205 : if (DEBUG) { System.out.println("ExplicitConstructorInvocation ::= Name DOT this LPAREN"); }  //$NON-NLS-1$
5701
    case 205 : if (DEBUG) { System.out.println("ExplicitConstructorInvocation ::= Name DOT this LPAREN"); }  //$NON-NLS-1$
5695
		    consumeExplicitConstructorInvocation(2, THIS_CALL);  
5702
		    consumeExplicitConstructorInvocation(2, THIS_CALL);  
5696
			break;
5703
			break;
5697
 
5704
 
5698
    case 206 : if (DEBUG) { System.out.println("ExplicitConstructorInvocation ::= Name DOT..."); }  //$NON-NLS-1$
5705
    case 206 : if (DEBUG) { System.out.println("ExplicitConstructorInvocation ::= Name DOT..."); }  //$NON-NLS-1$
5699
		    consumeExplicitConstructorInvocationWithTypeArguments(2, THIS_CALL);  
5706
		    consumeExplicitConstructorInvocationWithTypeArguments(2, THIS_CALL);  
5700
			break;
5707
			break;
5701
 
5708
 
5702
    case 207 : if (DEBUG) { System.out.println("InterfaceDeclaration ::= InterfaceHeader InterfaceBody"); }  //$NON-NLS-1$
5709
    case 207 : if (DEBUG) { System.out.println("InterfaceDeclaration ::= InterfaceHeader InterfaceBody"); }  //$NON-NLS-1$
5703
		    consumeInterfaceDeclaration();  
5710
		    consumeInterfaceDeclaration();  
5704
			break;
5711
			break;
5705
 
5712
 
5706
    case 208 : if (DEBUG) { System.out.println("InterfaceHeader ::= InterfaceHeaderName..."); }  //$NON-NLS-1$
5713
    case 208 : if (DEBUG) { System.out.println("InterfaceHeader ::= InterfaceHeaderName..."); }  //$NON-NLS-1$
5707
		    consumeInterfaceHeader();  
5714
		    consumeInterfaceHeader();  
5708
			break;
5715
			break;
5709
 
5716
 
5710
    case 209 : if (DEBUG) { System.out.println("InterfaceHeaderName ::= InterfaceHeaderName1..."); }  //$NON-NLS-1$
5717
    case 209 : if (DEBUG) { System.out.println("InterfaceHeaderName ::= InterfaceHeaderName1..."); }  //$NON-NLS-1$
5711
		    consumeTypeHeaderNameWithTypeParameters();  
5718
		    consumeTypeHeaderNameWithTypeParameters();  
5712
			break;
5719
			break;
5713
 
5720
 
5714
    case 211 : if (DEBUG) { System.out.println("InterfaceHeaderName1 ::= Modifiersopt interface..."); }  //$NON-NLS-1$
5721
    case 211 : if (DEBUG) { System.out.println("InterfaceHeaderName1 ::= Modifiersopt interface..."); }  //$NON-NLS-1$
5715
		    consumeInterfaceHeaderName1();  
5722
		    consumeInterfaceHeaderName1();  
5716
			break;
5723
			break;
5717
 
5724
 
5718
    case 212 : if (DEBUG) { System.out.println("InterfaceHeaderExtends ::= extends InterfaceTypeList"); }  //$NON-NLS-1$
5725
    case 212 : if (DEBUG) { System.out.println("InterfaceHeaderExtends ::= extends InterfaceTypeList"); }  //$NON-NLS-1$
5719
		    consumeInterfaceHeaderExtends();  
5726
		    consumeInterfaceHeaderExtends();  
5720
			break;
5727
			break;
5721
 
5728
 
5722
    case 215 : if (DEBUG) { System.out.println("InterfaceMemberDeclarations ::=..."); }  //$NON-NLS-1$
5729
    case 215 : if (DEBUG) { System.out.println("InterfaceMemberDeclarations ::=..."); }  //$NON-NLS-1$
5723
		    consumeInterfaceMemberDeclarations();  
5730
		    consumeInterfaceMemberDeclarations();  
5724
			break;
5731
			break;
5725
 
5732
 
5726
    case 216 : if (DEBUG) { System.out.println("InterfaceMemberDeclaration ::= SEMICOLON"); }  //$NON-NLS-1$
5733
    case 216 : if (DEBUG) { System.out.println("InterfaceMemberDeclaration ::= SEMICOLON"); }  //$NON-NLS-1$
5727
		    consumeEmptyTypeDeclaration();  
5734
		    consumeEmptyTypeDeclaration();  
5728
			break;
5735
			break;
5729
 
5736
 
5730
    case 218 : if (DEBUG) { System.out.println("InterfaceMemberDeclaration ::= MethodHeader MethodBody"); }  //$NON-NLS-1$
5737
    case 218 : if (DEBUG) { System.out.println("InterfaceMemberDeclaration ::= MethodHeader MethodBody"); }  //$NON-NLS-1$
5731
		    consumeInvalidMethodDeclaration();  
5738
		    consumeInvalidMethodDeclaration();  
5732
			break;
5739
			break;
5733
 
5740
 
5734
    case 219 : if (DEBUG) { System.out.println("InvalidConstructorDeclaration ::= ConstructorHeader..."); }  //$NON-NLS-1$
5741
    case 219 : if (DEBUG) { System.out.println("InvalidConstructorDeclaration ::= ConstructorHeader..."); }  //$NON-NLS-1$
5735
		    consumeInvalidConstructorDeclaration(true);  
5742
		    consumeInvalidConstructorDeclaration(true);  
5736
			break;
5743
			break;
5737
 
5744
 
5738
    case 220 : if (DEBUG) { System.out.println("InvalidConstructorDeclaration ::= ConstructorHeader..."); }  //$NON-NLS-1$
5745
    case 220 : if (DEBUG) { System.out.println("InvalidConstructorDeclaration ::= ConstructorHeader..."); }  //$NON-NLS-1$
5739
		    consumeInvalidConstructorDeclaration(false);  
5746
		    consumeInvalidConstructorDeclaration(false);  
5740
			break;
5747
			break;
5741
 
5748
 
5742
    case 231 : if (DEBUG) { System.out.println("PushLeftBrace ::="); }  //$NON-NLS-1$
5749
    case 231 : if (DEBUG) { System.out.println("PushLeftBrace ::="); }  //$NON-NLS-1$
5743
		    consumePushLeftBrace();  
5750
		    consumePushLeftBrace();  
5744
			break;
5751
			break;
5745
 
5752
 
5746
    case 232 : if (DEBUG) { System.out.println("ArrayInitializer ::= LBRACE PushLeftBrace ,opt RBRACE"); }  //$NON-NLS-1$
5753
    case 232 : if (DEBUG) { System.out.println("ArrayInitializer ::= LBRACE PushLeftBrace ,opt RBRACE"); }  //$NON-NLS-1$
5747
		    consumeEmptyArrayInitializer();  
5754
		    consumeEmptyArrayInitializer();  
5748
			break;
5755
			break;
5749
 
5756
 
5750
    case 233 : if (DEBUG) { System.out.println("ArrayInitializer ::= LBRACE PushLeftBrace..."); }  //$NON-NLS-1$
5757
    case 233 : if (DEBUG) { System.out.println("ArrayInitializer ::= LBRACE PushLeftBrace..."); }  //$NON-NLS-1$
5751
		    consumeArrayInitializer();  
5758
		    consumeArrayInitializer();  
5752
			break;
5759
			break;
5753
 
5760
 
5754
    case 234 : if (DEBUG) { System.out.println("ArrayInitializer ::= LBRACE PushLeftBrace..."); }  //$NON-NLS-1$
5761
    case 234 : if (DEBUG) { System.out.println("ArrayInitializer ::= LBRACE PushLeftBrace..."); }  //$NON-NLS-1$
5755
		    consumeArrayInitializer();  
5762
		    consumeArrayInitializer();  
5756
			break;
5763
			break;
5757
 
5764
 
5758
    case 236 : if (DEBUG) { System.out.println("VariableInitializers ::= VariableInitializers COMMA..."); }  //$NON-NLS-1$
5765
    case 236 : if (DEBUG) { System.out.println("VariableInitializers ::= VariableInitializers COMMA..."); }  //$NON-NLS-1$
5759
		    consumeVariableInitializers();  
5766
		    consumeVariableInitializers();  
5760
			break;
5767
			break;
5761
 
5768
 
5762
    case 237 : if (DEBUG) { System.out.println("Block ::= OpenBlock LBRACE BlockStatementsopt RBRACE"); }  //$NON-NLS-1$
5769
    case 237 : if (DEBUG) { System.out.println("Block ::= OpenBlock LBRACE BlockStatementsopt RBRACE"); }  //$NON-NLS-1$
5763
		    consumeBlock();  
5770
		    consumeBlock();  
5764
			break;
5771
			break;
5765
 
5772
 
5766
    case 238 : if (DEBUG) { System.out.println("OpenBlock ::="); }  //$NON-NLS-1$
5773
    case 238 : if (DEBUG) { System.out.println("OpenBlock ::="); }  //$NON-NLS-1$
5767
		    consumeOpenBlock() ;  
5774
		    consumeOpenBlock() ;  
5768
			break;
5775
			break;
5769
 
5776
 
5770
    case 240 : if (DEBUG) { System.out.println("BlockStatements ::= BlockStatements BlockStatement"); }  //$NON-NLS-1$
5777
    case 240 : if (DEBUG) { System.out.println("BlockStatements ::= BlockStatements BlockStatement"); }  //$NON-NLS-1$
5771
		    consumeBlockStatements() ;  
5778
		    consumeBlockStatements() ;  
5772
			break;
5779
			break;
5773
 
5780
 
5774
    case 244 : if (DEBUG) { System.out.println("BlockStatement ::= InterfaceDeclaration"); }  //$NON-NLS-1$
5781
    case 244 : if (DEBUG) { System.out.println("BlockStatement ::= InterfaceDeclaration"); }  //$NON-NLS-1$
5775
		    consumeInvalidInterfaceDeclaration();  
5782
		    consumeInvalidInterfaceDeclaration();  
5776
			break;
5783
			break;
5777
 
5784
 
5778
    case 245 : if (DEBUG) { System.out.println("BlockStatement ::= AnnotationTypeDeclaration"); }  //$NON-NLS-1$
5785
    case 245 : if (DEBUG) { System.out.println("BlockStatement ::= AnnotationTypeDeclaration"); }  //$NON-NLS-1$
5779
		    consumeInvalidAnnotationTypeDeclaration();  
5786
		    consumeInvalidAnnotationTypeDeclaration();  
5780
			break;
5787
			break;
5781
 
5788
 
5782
    case 246 : if (DEBUG) { System.out.println("BlockStatement ::= EnumDeclaration"); }  //$NON-NLS-1$
5789
    case 246 : if (DEBUG) { System.out.println("BlockStatement ::= EnumDeclaration"); }  //$NON-NLS-1$
5783
		    consumeInvalidEnumDeclaration();  
5790
		    consumeInvalidEnumDeclaration();  
5784
			break;
5791
			break;
5785
 
5792
 
5786
    case 247 : if (DEBUG) { System.out.println("LocalVariableDeclarationStatement ::=..."); }  //$NON-NLS-1$
5793
    case 247 : if (DEBUG) { System.out.println("LocalVariableDeclarationStatement ::=..."); }  //$NON-NLS-1$
5787
		    consumeLocalVariableDeclarationStatement();  
5794
		    consumeLocalVariableDeclarationStatement();  
5788
			break;
5795
			break;
5789
 
5796
 
5790
    case 248 : if (DEBUG) { System.out.println("LocalVariableDeclaration ::= Type PushModifiers..."); }  //$NON-NLS-1$
5797
    case 248 : if (DEBUG) { System.out.println("LocalVariableDeclaration ::= Type PushModifiers..."); }  //$NON-NLS-1$
5791
		    consumeLocalVariableDeclaration();  
5798
		    consumeLocalVariableDeclaration();  
5792
			break;
5799
			break;
5793
 
5800
 
5794
    case 249 : if (DEBUG) { System.out.println("LocalVariableDeclaration ::= Modifiers Type..."); }  //$NON-NLS-1$
5801
    case 249 : if (DEBUG) { System.out.println("LocalVariableDeclaration ::= Modifiers Type..."); }  //$NON-NLS-1$
5795
		    consumeLocalVariableDeclaration();  
5802
		    consumeLocalVariableDeclaration();  
5796
			break;
5803
			break;
5797
 
5804
 
5798
    case 250 : if (DEBUG) { System.out.println("PushModifiers ::="); }  //$NON-NLS-1$
5805
    case 250 : if (DEBUG) { System.out.println("PushModifiers ::="); }  //$NON-NLS-1$
5799
		    consumePushModifiers();  
5806
		    consumePushModifiers();  
5800
			break;
5807
			break;
5801
 
5808
 
5802
    case 251 : if (DEBUG) { System.out.println("PushModifiersForHeader ::="); }  //$NON-NLS-1$
5809
    case 251 : if (DEBUG) { System.out.println("PushModifiersForHeader ::="); }  //$NON-NLS-1$
5803
		    consumePushModifiersForHeader();  
5810
		    consumePushModifiersForHeader();  
5804
			break;
5811
			break;
5805
 
5812
 
5806
    case 252 : if (DEBUG) { System.out.println("PushRealModifiers ::="); }  //$NON-NLS-1$
5813
    case 252 : if (DEBUG) { System.out.println("PushRealModifiers ::="); }  //$NON-NLS-1$
5807
		    consumePushRealModifiers();  
5814
		    consumePushRealModifiers();  
5808
			break;
5815
			break;
5809
 
5816
 
5810
    case 279 : if (DEBUG) { System.out.println("EmptyStatement ::= SEMICOLON"); }  //$NON-NLS-1$
5817
    case 279 : if (DEBUG) { System.out.println("EmptyStatement ::= SEMICOLON"); }  //$NON-NLS-1$
5811
		    consumeEmptyStatement();  
5818
		    consumeEmptyStatement();  
5812
			break;
5819
			break;
5813
 
5820
 
5814
    case 280 : if (DEBUG) { System.out.println("LabeledStatement ::= Label COLON Statement"); }  //$NON-NLS-1$
5821
    case 280 : if (DEBUG) { System.out.println("LabeledStatement ::= Label COLON Statement"); }  //$NON-NLS-1$
5815
		    consumeStatementLabel() ;  
5822
		    consumeStatementLabel() ;  
5816
			break;
5823
			break;
5817
 
5824
 
5818
    case 281 : if (DEBUG) { System.out.println("LabeledStatementNoShortIf ::= Label COLON..."); }  //$NON-NLS-1$
5825
    case 281 : if (DEBUG) { System.out.println("LabeledStatementNoShortIf ::= Label COLON..."); }  //$NON-NLS-1$
5819
		    consumeStatementLabel() ;  
5826
		    consumeStatementLabel() ;  
5820
			break;
5827
			break;
5821
 
5828
 
5822
    case 282 : if (DEBUG) { System.out.println("Label ::= Identifier"); }  //$NON-NLS-1$
5829
    case 282 : if (DEBUG) { System.out.println("Label ::= Identifier"); }  //$NON-NLS-1$
5823
		    consumeLabel() ;  
5830
		    consumeLabel() ;  
5824
			break;
5831
			break;
5825
 
5832
 
5826
     case 283 : if (DEBUG) { System.out.println("ExpressionStatement ::= StatementExpression SEMICOLON"); }  //$NON-NLS-1$
5833
     case 283 : if (DEBUG) { System.out.println("ExpressionStatement ::= StatementExpression SEMICOLON"); }  //$NON-NLS-1$
5827
		    consumeExpressionStatement();  
5834
		    consumeExpressionStatement();  
5828
			break;
5835
			break;
5829
 
5836
 
5830
    case 292 : if (DEBUG) { System.out.println("IfThenStatement ::= if LPAREN Expression RPAREN..."); }  //$NON-NLS-1$
5837
    case 292 : if (DEBUG) { System.out.println("IfThenStatement ::= if LPAREN Expression RPAREN..."); }  //$NON-NLS-1$
5831
		    consumeStatementIfNoElse();  
5838
		    consumeStatementIfNoElse();  
5832
			break;
5839
			break;
5833
 
5840
 
5834
    case 293 : if (DEBUG) { System.out.println("IfThenElseStatement ::= if LPAREN Expression RPAREN..."); }  //$NON-NLS-1$
5841
    case 293 : if (DEBUG) { System.out.println("IfThenElseStatement ::= if LPAREN Expression RPAREN..."); }  //$NON-NLS-1$
5835
		    consumeStatementIfWithElse();  
5842
		    consumeStatementIfWithElse();  
5836
			break;
5843
			break;
5837
 
5844
 
5838
    case 294 : if (DEBUG) { System.out.println("IfThenElseStatementNoShortIf ::= if LPAREN Expression..."); }  //$NON-NLS-1$
5845
    case 294 : if (DEBUG) { System.out.println("IfThenElseStatementNoShortIf ::= if LPAREN Expression..."); }  //$NON-NLS-1$
5839
		    consumeStatementIfWithElse();  
5846
		    consumeStatementIfWithElse();  
5840
			break;
5847
			break;
5841
 
5848
 
5842
    case 295 : if (DEBUG) { System.out.println("SwitchStatement ::= switch LPAREN Expression RPAREN..."); }  //$NON-NLS-1$
5849
    case 295 : if (DEBUG) { System.out.println("SwitchStatement ::= switch LPAREN Expression RPAREN..."); }  //$NON-NLS-1$
5843
		    consumeStatementSwitch() ;  
5850
		    consumeStatementSwitch() ;  
5844
			break;
5851
			break;
5845
 
5852
 
5846
    case 296 : if (DEBUG) { System.out.println("SwitchBlock ::= LBRACE RBRACE"); }  //$NON-NLS-1$
5853
    case 296 : if (DEBUG) { System.out.println("SwitchBlock ::= LBRACE RBRACE"); }  //$NON-NLS-1$
5847
		    consumeEmptySwitchBlock() ;  
5854
		    consumeEmptySwitchBlock() ;  
5848
			break;
5855
			break;
5849
 
5856
 
5850
    case 299 : if (DEBUG) { System.out.println("SwitchBlock ::= LBRACE SwitchBlockStatements..."); }  //$NON-NLS-1$
5857
    case 299 : if (DEBUG) { System.out.println("SwitchBlock ::= LBRACE SwitchBlockStatements..."); }  //$NON-NLS-1$
5851
		    consumeSwitchBlock() ;  
5858
		    consumeSwitchBlock() ;  
5852
			break;
5859
			break;
5853
 
5860
 
5854
    case 301 : if (DEBUG) { System.out.println("SwitchBlockStatements ::= SwitchBlockStatements..."); }  //$NON-NLS-1$
5861
    case 301 : if (DEBUG) { System.out.println("SwitchBlockStatements ::= SwitchBlockStatements..."); }  //$NON-NLS-1$
5855
		    consumeSwitchBlockStatements() ;  
5862
		    consumeSwitchBlockStatements() ;  
5856
			break;
5863
			break;
5857
 
5864
 
5858
    case 302 : if (DEBUG) { System.out.println("SwitchBlockStatement ::= SwitchLabels BlockStatements"); }  //$NON-NLS-1$
5865
    case 302 : if (DEBUG) { System.out.println("SwitchBlockStatement ::= SwitchLabels BlockStatements"); }  //$NON-NLS-1$
5859
		    consumeSwitchBlockStatement() ;  
5866
		    consumeSwitchBlockStatement() ;  
5860
			break;
5867
			break;
5861
 
5868
 
5862
    case 304 : if (DEBUG) { System.out.println("SwitchLabels ::= SwitchLabels SwitchLabel"); }  //$NON-NLS-1$
5869
    case 304 : if (DEBUG) { System.out.println("SwitchLabels ::= SwitchLabels SwitchLabel"); }  //$NON-NLS-1$
5863
		    consumeSwitchLabels() ;  
5870
		    consumeSwitchLabels() ;  
5864
			break;
5871
			break;
5865
 
5872
 
5866
     case 305 : if (DEBUG) { System.out.println("SwitchLabel ::= case ConstantExpression COLON"); }  //$NON-NLS-1$
5873
     case 305 : if (DEBUG) { System.out.println("SwitchLabel ::= case ConstantExpression COLON"); }  //$NON-NLS-1$
5867
		    consumeCaseLabel();  
5874
		    consumeCaseLabel();  
5868
			break;
5875
			break;
5869
 
5876
 
5870
     case 306 : if (DEBUG) { System.out.println("SwitchLabel ::= default COLON"); }  //$NON-NLS-1$
5877
     case 306 : if (DEBUG) { System.out.println("SwitchLabel ::= default COLON"); }  //$NON-NLS-1$
5871
		    consumeDefaultLabel();  
5878
		    consumeDefaultLabel();  
5872
			break;
5879
			break;
5873
 
5880
 
5874
    case 307 : if (DEBUG) { System.out.println("WhileStatement ::= while LPAREN Expression RPAREN..."); }  //$NON-NLS-1$
5881
    case 307 : if (DEBUG) { System.out.println("WhileStatement ::= while LPAREN Expression RPAREN..."); }  //$NON-NLS-1$
5875
		    consumeStatementWhile() ;  
5882
		    consumeStatementWhile() ;  
5876
			break;
5883
			break;
5877
 
5884
 
5878
    case 308 : if (DEBUG) { System.out.println("WhileStatementNoShortIf ::= while LPAREN Expression..."); }  //$NON-NLS-1$
5885
    case 308 : if (DEBUG) { System.out.println("WhileStatementNoShortIf ::= while LPAREN Expression..."); }  //$NON-NLS-1$
5879
		    consumeStatementWhile() ;  
5886
		    consumeStatementWhile() ;  
5880
			break;
5887
			break;
5881
 
5888
 
5882
    case 309 : if (DEBUG) { System.out.println("DoStatement ::= do Statement while LPAREN Expression..."); }  //$NON-NLS-1$
5889
    case 309 : if (DEBUG) { System.out.println("DoStatement ::= do Statement while LPAREN Expression..."); }  //$NON-NLS-1$
5883
		    consumeStatementDo() ;  
5890
		    consumeStatementDo() ;  
5884
			break;
5891
			break;
5885
 
5892
 
5886
    case 310 : if (DEBUG) { System.out.println("ForStatement ::= for LPAREN ForInitopt SEMICOLON..."); }  //$NON-NLS-1$
5893
    case 310 : if (DEBUG) { System.out.println("ForStatement ::= for LPAREN ForInitopt SEMICOLON..."); }  //$NON-NLS-1$
5887
		    consumeStatementFor() ;  
5894
		    consumeStatementFor() ;  
5888
			break;
5895
			break;
5889
 
5896
 
5890
    case 311 : if (DEBUG) { System.out.println("ForStatementNoShortIf ::= for LPAREN ForInitopt..."); }  //$NON-NLS-1$
5897
    case 311 : if (DEBUG) { System.out.println("ForStatementNoShortIf ::= for LPAREN ForInitopt..."); }  //$NON-NLS-1$
5891
		    consumeStatementFor() ;  
5898
		    consumeStatementFor() ;  
5892
			break;
5899
			break;
5893
 
5900
 
5894
    case 312 : if (DEBUG) { System.out.println("ForInit ::= StatementExpressionList"); }  //$NON-NLS-1$
5901
    case 312 : if (DEBUG) { System.out.println("ForInit ::= StatementExpressionList"); }  //$NON-NLS-1$
5895
		    consumeForInit() ;  
5902
		    consumeForInit() ;  
5896
			break;
5903
			break;
5897
 
5904
 
5898
    case 316 : if (DEBUG) { System.out.println("StatementExpressionList ::= StatementExpressionList..."); }  //$NON-NLS-1$
5905
    case 316 : if (DEBUG) { System.out.println("StatementExpressionList ::= StatementExpressionList..."); }  //$NON-NLS-1$
5899
		    consumeStatementExpressionList() ;  
5906
		    consumeStatementExpressionList() ;  
5900
			break;
5907
			break;
5901
 
5908
 
5902
    case 317 : if (DEBUG) { System.out.println("AssertStatement ::= assert Expression SEMICOLON"); }  //$NON-NLS-1$
5909
    case 317 : if (DEBUG) { System.out.println("AssertStatement ::= assert Expression SEMICOLON"); }  //$NON-NLS-1$
5903
		    consumeSimpleAssertStatement() ;  
5910
		    consumeSimpleAssertStatement() ;  
5904
			break;
5911
			break;
5905
 
5912
 
5906
    case 318 : if (DEBUG) { System.out.println("AssertStatement ::= assert Expression COLON Expression"); }  //$NON-NLS-1$
5913
    case 318 : if (DEBUG) { System.out.println("AssertStatement ::= assert Expression COLON Expression"); }  //$NON-NLS-1$
5907
		    consumeAssertStatement() ;  
5914
		    consumeAssertStatement() ;  
5908
			break;
5915
			break;
5909
 
5916
 
5910
    case 319 : if (DEBUG) { System.out.println("BreakStatement ::= break SEMICOLON"); }  //$NON-NLS-1$
5917
    case 319 : if (DEBUG) { System.out.println("BreakStatement ::= break SEMICOLON"); }  //$NON-NLS-1$
5911
		    consumeStatementBreak() ;  
5918
		    consumeStatementBreak() ;  
5912
			break;
5919
			break;
5913
 
5920
 
5914
    case 320 : if (DEBUG) { System.out.println("BreakStatement ::= break Identifier SEMICOLON"); }  //$NON-NLS-1$
5921
    case 320 : if (DEBUG) { System.out.println("BreakStatement ::= break Identifier SEMICOLON"); }  //$NON-NLS-1$
5915
		    consumeStatementBreakWithLabel() ;  
5922
		    consumeStatementBreakWithLabel() ;  
5916
			break;
5923
			break;
5917
 
5924
 
5918
    case 321 : if (DEBUG) { System.out.println("ContinueStatement ::= continue SEMICOLON"); }  //$NON-NLS-1$
5925
    case 321 : if (DEBUG) { System.out.println("ContinueStatement ::= continue SEMICOLON"); }  //$NON-NLS-1$
5919
		    consumeStatementContinue() ;  
5926
		    consumeStatementContinue() ;  
5920
			break;
5927
			break;
5921
 
5928
 
5922
    case 322 : if (DEBUG) { System.out.println("ContinueStatement ::= continue Identifier SEMICOLON"); }  //$NON-NLS-1$
5929
    case 322 : if (DEBUG) { System.out.println("ContinueStatement ::= continue Identifier SEMICOLON"); }  //$NON-NLS-1$
5923
		    consumeStatementContinueWithLabel() ;  
5930
		    consumeStatementContinueWithLabel() ;  
5924
			break;
5931
			break;
5925
 
5932
 
5926
    case 323 : if (DEBUG) { System.out.println("ReturnStatement ::= return Expressionopt SEMICOLON"); }  //$NON-NLS-1$
5933
    case 323 : if (DEBUG) { System.out.println("ReturnStatement ::= return Expressionopt SEMICOLON"); }  //$NON-NLS-1$
5927
		    consumeStatementReturn() ;  
5934
		    consumeStatementReturn() ;  
5928
			break;
5935
			break;
5929
 
5936
 
5930
    case 324 : if (DEBUG) { System.out.println("ThrowStatement ::= throw Expression SEMICOLON"); }  //$NON-NLS-1$
5937
    case 324 : if (DEBUG) { System.out.println("ThrowStatement ::= throw Expression SEMICOLON"); }  //$NON-NLS-1$
5931
		    consumeStatementThrow();  
5938
		    consumeStatementThrow();  
5932
			break;
5939
			break;
5933
 
5940
 
5934
    case 325 : if (DEBUG) { System.out.println("SynchronizedStatement ::= OnlySynchronized LPAREN..."); }  //$NON-NLS-1$
5941
    case 325 : if (DEBUG) { System.out.println("SynchronizedStatement ::= OnlySynchronized LPAREN..."); }  //$NON-NLS-1$
5935
		    consumeStatementSynchronized();  
5942
		    consumeStatementSynchronized();  
5936
			break;
5943
			break;
5937
 
5944
 
5938
    case 326 : if (DEBUG) { System.out.println("OnlySynchronized ::= synchronized"); }  //$NON-NLS-1$
5945
    case 326 : if (DEBUG) { System.out.println("OnlySynchronized ::= synchronized"); }  //$NON-NLS-1$
5939
		    consumeOnlySynchronized();  
5946
		    consumeOnlySynchronized();  
5940
			break;
5947
			break;
5941
 
5948
 
5942
    case 327 : if (DEBUG) { System.out.println("TryStatement ::= try TryBlock Catches"); }  //$NON-NLS-1$
5949
    case 327 : if (DEBUG) { System.out.println("TryStatement ::= try TryBlock Catches"); }  //$NON-NLS-1$
5943
		    consumeStatementTry(false, false);  
5950
		    consumeStatementTry(false, false);  
5944
			break;
5951
			break;
5945
 
5952
 
5946
    case 328 : if (DEBUG) { System.out.println("TryStatement ::= try TryBlock Catchesopt Finally"); }  //$NON-NLS-1$
5953
    case 328 : if (DEBUG) { System.out.println("TryStatement ::= try TryBlock Catchesopt Finally"); }  //$NON-NLS-1$
5947
		    consumeStatementTry(true, false);  
5954
		    consumeStatementTry(true, false);  
5948
			break;
5955
			break;
5949
 
5956
 
5950
    case 329 : if (DEBUG) { System.out.println("TryStatementWithResources ::= try ResourceSpecification"); }  //$NON-NLS-1$
5957
    case 329 : if (DEBUG) { System.out.println("TryStatementWithResources ::= try ResourceSpecification"); }  //$NON-NLS-1$
5951
		    consumeStatementTry(false, true);  
5958
		    consumeStatementTry(false, true);  
5952
			break;
5959
			break;
5953
 
5960
 
5954
    case 330 : if (DEBUG) { System.out.println("TryStatementWithResources ::= try ResourceSpecification"); }  //$NON-NLS-1$
5961
    case 330 : if (DEBUG) { System.out.println("TryStatementWithResources ::= try ResourceSpecification"); }  //$NON-NLS-1$
5955
		    consumeStatementTry(true, true);  
5962
		    consumeStatementTry(true, true);  
5956
			break;
5963
			break;
5957
 
5964
 
5958
    case 331 : if (DEBUG) { System.out.println("ResourceSpecification ::= LPAREN Resources ;opt RPAREN"); }  //$NON-NLS-1$
5965
    case 331 : if (DEBUG) { System.out.println("ResourceSpecification ::= LPAREN Resources ;opt RPAREN"); }  //$NON-NLS-1$
5959
		    consumeResourceSpecification();  
5966
		    consumeResourceSpecification();  
5960
			break;
5967
			break;
5961
 
5968
 
5962
    case 332 : if (DEBUG) { System.out.println(";opt ::="); }  //$NON-NLS-1$
5969
    case 332 : if (DEBUG) { System.out.println(";opt ::="); }  //$NON-NLS-1$
5963
		    consumeResourceOptionalTrailingSemiColon(false);  
5970
		    consumeResourceOptionalTrailingSemiColon(false);  
5964
			break;
5971
			break;
5965
 
5972
 
5966
    case 333 : if (DEBUG) { System.out.println(";opt ::= SEMICOLON"); }  //$NON-NLS-1$
5973
    case 333 : if (DEBUG) { System.out.println(";opt ::= SEMICOLON"); }  //$NON-NLS-1$
5967
		    consumeResourceOptionalTrailingSemiColon(true);  
5974
		    consumeResourceOptionalTrailingSemiColon(true);  
5968
			break;
5975
			break;
5969
 
5976
 
5970
    case 334 : if (DEBUG) { System.out.println("Resources ::= Resource"); }  //$NON-NLS-1$
5977
    case 334 : if (DEBUG) { System.out.println("Resources ::= Resource"); }  //$NON-NLS-1$
5971
		    consumeSingleResource();  
5978
		    consumeSingleResource();  
5972
			break;
5979
			break;
5973
 
5980
 
5974
    case 335 : if (DEBUG) { System.out.println("Resources ::= Resources TrailingSemiColon Resource"); }  //$NON-NLS-1$
5981
    case 335 : if (DEBUG) { System.out.println("Resources ::= Resources TrailingSemiColon Resource"); }  //$NON-NLS-1$
5975
		    consumeMultipleResources();  
5982
		    consumeMultipleResources();  
5976
			break;
5983
			break;
5977
 
5984
 
5978
    case 336 : if (DEBUG) { System.out.println("TrailingSemiColon ::= SEMICOLON"); }  //$NON-NLS-1$
5985
    case 336 : if (DEBUG) { System.out.println("TrailingSemiColon ::= SEMICOLON"); }  //$NON-NLS-1$
5979
		    consumeResourceOptionalTrailingSemiColon(true);  
5986
		    consumeResourceOptionalTrailingSemiColon(true);  
5980
			break;
5987
			break;
5981
 
5988
 
5982
    case 337 : if (DEBUG) { System.out.println("Resource ::= Type PushModifiers VariableDeclaratorId..."); }  //$NON-NLS-1$
5989
    case 337 : if (DEBUG) { System.out.println("Resource ::= Type PushModifiers VariableDeclaratorId..."); }  //$NON-NLS-1$
5983
		    consumeResourceAsLocalVariableDeclaration();  
5990
		    consumeResourceAsLocalVariableDeclaration();  
5984
			break;
5991
			break;
5985
 
5992
 
5986
    case 338 : if (DEBUG) { System.out.println("Resource ::= Modifiers Type PushRealModifiers..."); }  //$NON-NLS-1$
5993
    case 338 : if (DEBUG) { System.out.println("Resource ::= Modifiers Type PushRealModifiers..."); }  //$NON-NLS-1$
5987
		    consumeResourceAsLocalVariableDeclaration();  
5994
		    consumeResourceAsLocalVariableDeclaration();  
5988
			break;
5995
			break;
5989
 
5996
 
5990
    case 340 : if (DEBUG) { System.out.println("ExitTryBlock ::="); }  //$NON-NLS-1$
5997
    case 340 : if (DEBUG) { System.out.println("ExitTryBlock ::="); }  //$NON-NLS-1$
5991
		    consumeExitTryBlock();  
5998
		    consumeExitTryBlock();  
5992
			break;
5999
			break;
5993
 
6000
 
5994
    case 342 : if (DEBUG) { System.out.println("Catches ::= Catches CatchClause"); }  //$NON-NLS-1$
6001
    case 342 : if (DEBUG) { System.out.println("Catches ::= Catches CatchClause"); }  //$NON-NLS-1$
5995
		    consumeCatches();  
6002
		    consumeCatches();  
5996
			break;
6003
			break;
5997
 
6004
 
5998
    case 343 : if (DEBUG) { System.out.println("CatchClause ::= catch LPAREN CatchFormalParameter RPAREN"); }  //$NON-NLS-1$
6005
    case 343 : if (DEBUG) { System.out.println("CatchClause ::= catch LPAREN CatchFormalParameter RPAREN"); }  //$NON-NLS-1$
5999
		    consumeStatementCatch() ;  
6006
		    consumeStatementCatch() ;  
6000
			break;
6007
			break;
6001
 
6008
 
6002
    case 345 : if (DEBUG) { System.out.println("PushLPAREN ::= LPAREN"); }  //$NON-NLS-1$
6009
    case 345 : if (DEBUG) { System.out.println("PushLPAREN ::= LPAREN"); }  //$NON-NLS-1$
6003
		    consumeLeftParen();  
6010
		    consumeLeftParen();  
6004
			break;
6011
			break;
6005
 
6012
 
6006
    case 346 : if (DEBUG) { System.out.println("PushRPAREN ::= RPAREN"); }  //$NON-NLS-1$
6013
    case 346 : if (DEBUG) { System.out.println("PushRPAREN ::= RPAREN"); }  //$NON-NLS-1$
6007
		    consumeRightParen();  
6014
		    consumeRightParen();  
6008
			break;
6015
			break;
6009
 
6016
 
6010
    case 351 : if (DEBUG) { System.out.println("PrimaryNoNewArray ::= this"); }  //$NON-NLS-1$
6017
    case 351 : if (DEBUG) { System.out.println("PrimaryNoNewArray ::= this"); }  //$NON-NLS-1$
6011
		    consumePrimaryNoNewArrayThis();  
6018
		    consumePrimaryNoNewArrayThis();  
6012
			break;
6019
			break;
6013
 
6020
 
6014
    case 352 : if (DEBUG) { System.out.println("PrimaryNoNewArray ::= PushLPAREN Expression_NotName..."); }  //$NON-NLS-1$
6021
    case 352 : if (DEBUG) { System.out.println("PrimaryNoNewArray ::= PushLPAREN Expression_NotName..."); }  //$NON-NLS-1$
6015
		    consumePrimaryNoNewArray();  
6022
		    consumePrimaryNoNewArray();  
6016
			break;
6023
			break;
6017
 
6024
 
6018
    case 353 : if (DEBUG) { System.out.println("PrimaryNoNewArray ::= PushLPAREN Name PushRPAREN"); }  //$NON-NLS-1$
6025
    case 353 : if (DEBUG) { System.out.println("PrimaryNoNewArray ::= PushLPAREN Name PushRPAREN"); }  //$NON-NLS-1$
6019
		    consumePrimaryNoNewArrayWithName();  
6026
		    consumePrimaryNoNewArrayWithName();  
6020
			break;
6027
			break;
6021
 
6028
 
6022
    case 356 : if (DEBUG) { System.out.println("PrimaryNoNewArray ::= Name DOT this"); }  //$NON-NLS-1$
6029
    case 356 : if (DEBUG) { System.out.println("PrimaryNoNewArray ::= Name DOT this"); }  //$NON-NLS-1$
6023
		    consumePrimaryNoNewArrayNameThis();  
6030
		    consumePrimaryNoNewArrayNameThis();  
6024
			break;
6031
			break;
6025
 
6032
 
6026
    case 357 : if (DEBUG) { System.out.println("PrimaryNoNewArray ::= Name DOT super"); }  //$NON-NLS-1$
6033
    case 357 : if (DEBUG) { System.out.println("PrimaryNoNewArray ::= Name DOT super"); }  //$NON-NLS-1$
6027
		    consumePrimaryNoNewArrayNameSuper();  
6034
		    consumePrimaryNoNewArrayNameSuper();  
6028
			break;
6035
			break;
6029
 
6036
 
6030
    case 358 : if (DEBUG) { System.out.println("PrimaryNoNewArray ::= Name DOT class"); }  //$NON-NLS-1$
6037
    case 358 : if (DEBUG) { System.out.println("PrimaryNoNewArray ::= Name DOT class"); }  //$NON-NLS-1$
6031
		    consumePrimaryNoNewArrayName();  
6038
		    consumePrimaryNoNewArrayName();  
6032
			break;
6039
			break;
6033
 
6040
 
6034
    case 359 : if (DEBUG) { System.out.println("PrimaryNoNewArray ::= Name Dims DOT class"); }  //$NON-NLS-1$
6041
    case 359 : if (DEBUG) { System.out.println("PrimaryNoNewArray ::= Name Dims DOT class"); }  //$NON-NLS-1$
6035
		    consumePrimaryNoNewArrayArrayType();  
6042
		    consumePrimaryNoNewArrayArrayType();  
6036
			break;
6043
			break;
6037
 
6044
 
6038
    case 360 : if (DEBUG) { System.out.println("PrimaryNoNewArray ::= PrimitiveType Dims DOT class"); }  //$NON-NLS-1$
6045
    case 360 : if (DEBUG) { System.out.println("PrimaryNoNewArray ::= PrimitiveType Dims DOT class"); }  //$NON-NLS-1$
6039
		    consumePrimaryNoNewArrayPrimitiveArrayType();  
6046
		    consumePrimaryNoNewArrayPrimitiveArrayType();  
6040
			break;
6047
			break;
6041
 
6048
 
6042
    case 361 : if (DEBUG) { System.out.println("PrimaryNoNewArray ::= PrimitiveType DOT class"); }  //$NON-NLS-1$
6049
    case 361 : if (DEBUG) { System.out.println("PrimaryNoNewArray ::= PrimitiveType DOT class"); }  //$NON-NLS-1$
6043
		    consumePrimaryNoNewArrayPrimitiveType();  
6050
		    consumePrimaryNoNewArrayPrimitiveType();  
6044
			break;
6051
			break;
6045
 
6052
 
6046
    case 364 : if (DEBUG) { System.out.println("AllocationHeader ::= new ClassType LPAREN..."); }  //$NON-NLS-1$
6053
    case 364 : if (DEBUG) { System.out.println("AllocationHeader ::= new ClassType LPAREN..."); }  //$NON-NLS-1$
6047
		    consumeAllocationHeader();  
6054
		    consumeAllocationHeader();  
6048
			break;
6055
			break;
6049
 
6056
 
6050
    case 365 : if (DEBUG) { System.out.println("ClassInstanceCreationExpression ::= new..."); }  //$NON-NLS-1$
6057
    case 365 : if (DEBUG) { System.out.println("ClassInstanceCreationExpression ::= new..."); }  //$NON-NLS-1$
6051
		    consumeClassInstanceCreationExpressionWithTypeArguments();  
6058
		    consumeClassInstanceCreationExpressionWithTypeArguments();  
6052
			break;
6059
			break;
6053
 
6060
 
6054
    case 366 : if (DEBUG) { System.out.println("ClassInstanceCreationExpression ::= new ClassType LPAREN"); }  //$NON-NLS-1$
6061
    case 366 : if (DEBUG) { System.out.println("ClassInstanceCreationExpression ::= new ClassType..."); }  //$NON-NLS-1$
6055
		    consumeClassInstanceCreationExpression();  
6062
		    consumeClassInstanceCreationExpression();  
6056
			break;
6063
			break;
6057
 
6064
 
6058
    case 367 : if (DEBUG) { System.out.println("ClassInstanceCreationExpression ::= Primary DOT new..."); }  //$NON-NLS-1$
6065
    case 367 : if (DEBUG) { System.out.println("ClassInstanceCreationExpression ::= Primary DOT new..."); }  //$NON-NLS-1$
6059
		    consumeClassInstanceCreationExpressionQualifiedWithTypeArguments() ;  
6066
		    consumeClassInstanceCreationExpressionQualifiedWithTypeArguments() ;  
6060
			break;
6067
			break;
6061
 
6068
 
6062
    case 368 : if (DEBUG) { System.out.println("ClassInstanceCreationExpression ::= Primary DOT new..."); }  //$NON-NLS-1$
6069
    case 368 : if (DEBUG) { System.out.println("ClassInstanceCreationExpression ::= Primary DOT new..."); }  //$NON-NLS-1$
6063
		    consumeClassInstanceCreationExpressionQualified() ;  
6070
		    consumeClassInstanceCreationExpressionQualified() ;  
6064
			break;
6071
			break;
6065
 
6072
 
6066
    case 369 : if (DEBUG) { System.out.println("ClassInstanceCreationExpression ::=..."); }  //$NON-NLS-1$
6073
    case 369 : if (DEBUG) { System.out.println("ClassInstanceCreationExpression ::=..."); }  //$NON-NLS-1$
6067
		    consumeClassInstanceCreationExpressionQualified() ;  
6074
		    consumeClassInstanceCreationExpressionQualified() ;  
6068
			break;
6075
			break;
6069
 
6076
 
6070
    case 370 : if (DEBUG) { System.out.println("ClassInstanceCreationExpression ::=..."); }  //$NON-NLS-1$
6077
    case 370 : if (DEBUG) { System.out.println("ClassInstanceCreationExpression ::=..."); }  //$NON-NLS-1$
6071
		    consumeClassInstanceCreationExpressionQualifiedWithTypeArguments() ;  
6078
		    consumeClassInstanceCreationExpressionQualifiedWithTypeArguments() ;  
6072
			break;
6079
			break;
6073
 
6080
 
6074
    case 371 : if (DEBUG) { System.out.println("ClassInstanceCreationExpressionName ::= Name DOT"); }  //$NON-NLS-1$
6081
    case 371 : if (DEBUG) { System.out.println("EnterInstanceCreationArgumentList ::="); }  //$NON-NLS-1$
6075
		    consumeClassInstanceCreationExpressionName() ;  
6082
		    consumeEnterInstanceCreationArgumentList();  
6076
			break;
6083
			break;
6077
 
6084
 
6078
    case 372 : if (DEBUG) { System.out.println("UnqualifiedClassBodyopt ::="); }  //$NON-NLS-1$
6085
    case 372 : if (DEBUG) { System.out.println("ClassInstanceCreationExpressionName ::= Name DOT"); }  //$NON-NLS-1$
6079
		    consumeClassBodyopt();  
6086
		    consumeClassInstanceCreationExpressionName() ;  
6080
			break;
6087
			break;
6081
 
6088
 
6082
    case 374 : if (DEBUG) { System.out.println("UnqualifiedEnterAnonymousClassBody ::="); }  //$NON-NLS-1$
6089
    case 373 : if (DEBUG) { System.out.println("UnqualifiedClassBodyopt ::="); }  //$NON-NLS-1$
6083
		    consumeEnterAnonymousClassBody(false);  
6090
		    consumeClassBodyopt();  
6084
			break;
6091
			break;
6085
 
6092
 
6086
    case 375 : if (DEBUG) { System.out.println("QualifiedClassBodyopt ::="); }  //$NON-NLS-1$
6093
    case 375 : if (DEBUG) { System.out.println("UnqualifiedEnterAnonymousClassBody ::="); }  //$NON-NLS-1$
6087
		    consumeClassBodyopt();  
6094
		    consumeEnterAnonymousClassBody(false);  
6088
			break;
6095
			break;
6089
 
6096
 
6090
    case 377 : if (DEBUG) { System.out.println("QualifiedEnterAnonymousClassBody ::="); }  //$NON-NLS-1$
6097
    case 376 : if (DEBUG) { System.out.println("QualifiedClassBodyopt ::="); }  //$NON-NLS-1$
6091
		    consumeEnterAnonymousClassBody(true);  
6098
		    consumeClassBodyopt();  
6092
			break;
6099
			break;
6093
 
6100
 
6094
    case 379 : if (DEBUG) { System.out.println("ArgumentList ::= ArgumentList COMMA Expression"); }  //$NON-NLS-1$
6101
    case 378 : if (DEBUG) { System.out.println("QualifiedEnterAnonymousClassBody ::="); }  //$NON-NLS-1$
6095
		    consumeArgumentList();  
6102
		    consumeEnterAnonymousClassBody(true);  
6096
			break;
6103
			break;
6097
 
6104
 
6098
    case 380 : if (DEBUG) { System.out.println("ArrayCreationHeader ::= new PrimitiveType..."); }  //$NON-NLS-1$
6105
    case 380 : if (DEBUG) { System.out.println("ArgumentList ::= ArgumentList COMMA Expression"); }  //$NON-NLS-1$
6099
		    consumeArrayCreationHeader();  
6106
		    consumeArgumentList();  
6100
			break;
6107
			break;
6101
 
6108
 
6102
    case 381 : if (DEBUG) { System.out.println("ArrayCreationHeader ::= new ClassOrInterfaceType..."); }  //$NON-NLS-1$
6109
    case 381 : if (DEBUG) { System.out.println("ArrayCreationHeader ::= new PrimitiveType..."); }  //$NON-NLS-1$
6103
		    consumeArrayCreationHeader();  
6110
		    consumeArrayCreationHeader();  
6104
			break;
6111
			break;
6105
 
6112
 
6106
    case 382 : if (DEBUG) { System.out.println("ArrayCreationWithoutArrayInitializer ::= new..."); }  //$NON-NLS-1$
6113
    case 382 : if (DEBUG) { System.out.println("ArrayCreationHeader ::= new ClassOrInterfaceType..."); }  //$NON-NLS-1$
6107
		    consumeArrayCreationExpressionWithoutInitializer();  
6114
		    consumeArrayCreationHeader();  
6108
			break;
6115
			break;
6109
 
6116
 
6110
    case 383 : if (DEBUG) { System.out.println("ArrayCreationWithArrayInitializer ::= new PrimitiveType"); }  //$NON-NLS-1$
6117
    case 383 : if (DEBUG) { System.out.println("ArrayCreationWithoutArrayInitializer ::= new..."); }  //$NON-NLS-1$
6111
		    consumeArrayCreationExpressionWithInitializer();  
6118
		    consumeArrayCreationExpressionWithoutInitializer();  
6112
			break;
6119
			break;
6113
 
6120
 
6114
    case 384 : if (DEBUG) { System.out.println("ArrayCreationWithoutArrayInitializer ::= new..."); }  //$NON-NLS-1$
6121
    case 384 : if (DEBUG) { System.out.println("ArrayCreationWithArrayInitializer ::= new PrimitiveType"); }  //$NON-NLS-1$
6115
		    consumeArrayCreationExpressionWithoutInitializer();  
6122
		    consumeArrayCreationExpressionWithInitializer();  
6116
			break;
6123
			break;
6117
 
6124
 
6118
    case 385 : if (DEBUG) { System.out.println("ArrayCreationWithArrayInitializer ::= new..."); }  //$NON-NLS-1$
6125
    case 385 : if (DEBUG) { System.out.println("ArrayCreationWithoutArrayInitializer ::= new..."); }  //$NON-NLS-1$
6119
		    consumeArrayCreationExpressionWithInitializer();  
6126
		    consumeArrayCreationExpressionWithoutInitializer();  
6120
			break;
6127
			break;
6121
 
6128
 
6122
    case 387 : if (DEBUG) { System.out.println("DimWithOrWithOutExprs ::= DimWithOrWithOutExprs..."); }  //$NON-NLS-1$
6129
    case 386 : if (DEBUG) { System.out.println("ArrayCreationWithArrayInitializer ::= new..."); }  //$NON-NLS-1$
6123
		    consumeDimWithOrWithOutExprs();  
6130
		    consumeArrayCreationExpressionWithInitializer();  
6124
			break;
6131
			break;
6125
 
6132
 
6126
     case 389 : if (DEBUG) { System.out.println("DimWithOrWithOutExpr ::= LBRACKET RBRACKET"); }  //$NON-NLS-1$
6133
    case 388 : if (DEBUG) { System.out.println("DimWithOrWithOutExprs ::= DimWithOrWithOutExprs..."); }  //$NON-NLS-1$
6127
		    consumeDimWithOrWithOutExpr();  
6134
		    consumeDimWithOrWithOutExprs();  
6128
			break;
6135
			break;
6129
 
6136
 
6130
     case 390 : if (DEBUG) { System.out.println("Dims ::= DimsLoop"); }  //$NON-NLS-1$
6137
     case 390 : if (DEBUG) { System.out.println("DimWithOrWithOutExpr ::= LBRACKET RBRACKET"); }  //$NON-NLS-1$
6131
		    consumeDims();  
6138
		    consumeDimWithOrWithOutExpr();  
6132
			break;
6139
			break;
6133
 
6140
 
6134
     case 393 : if (DEBUG) { System.out.println("OneDimLoop ::= LBRACKET RBRACKET"); }  //$NON-NLS-1$
6141
     case 391 : if (DEBUG) { System.out.println("Dims ::= DimsLoop"); }  //$NON-NLS-1$
6135
		    consumeOneDimLoop();  
6142
		    consumeDims();  
6136
			break;
6143
			break;
6137
 
6144
 
6138
    case 394 : if (DEBUG) { System.out.println("FieldAccess ::= Primary DOT Identifier"); }  //$NON-NLS-1$
6145
     case 394 : if (DEBUG) { System.out.println("OneDimLoop ::= LBRACKET RBRACKET"); }  //$NON-NLS-1$
6139
		    consumeFieldAccess(false);  
6146
		    consumeOneDimLoop();  
6140
			break;
6147
			break;
6141
 
6148
 
6142
    case 395 : if (DEBUG) { System.out.println("FieldAccess ::= super DOT Identifier"); }  //$NON-NLS-1$
6149
    case 395 : if (DEBUG) { System.out.println("FieldAccess ::= Primary DOT Identifier"); }  //$NON-NLS-1$
6143
		    consumeFieldAccess(true);  
6150
		    consumeFieldAccess(false);  
6144
			break;
6151
			break;
6145
 
6152
 
6146
    case 396 : if (DEBUG) { System.out.println("MethodInvocation ::= Name LPAREN ArgumentListopt RPAREN"); }  //$NON-NLS-1$
6153
    case 396 : if (DEBUG) { System.out.println("FieldAccess ::= super DOT Identifier"); }  //$NON-NLS-1$
6147
		    consumeMethodInvocationName();  
6154
		    consumeFieldAccess(true);  
6148
			break;
6155
			break;
6149
 
6156
 
6150
    case 397 : if (DEBUG) { System.out.println("MethodInvocation ::= Name DOT OnlyTypeArguments..."); }  //$NON-NLS-1$
6157
    case 397 : if (DEBUG) { System.out.println("MethodInvocation ::= Name LPAREN ArgumentListopt RPAREN"); }  //$NON-NLS-1$
6151
		    consumeMethodInvocationNameWithTypeArguments();  
6158
		    consumeMethodInvocationName();  
6152
			break;
6159
			break;
6153
 
6160
 
6154
    case 398 : if (DEBUG) { System.out.println("MethodInvocation ::= Primary DOT OnlyTypeArguments..."); }  //$NON-NLS-1$
6161
    case 398 : if (DEBUG) { System.out.println("MethodInvocation ::= Name DOT OnlyTypeArguments..."); }  //$NON-NLS-1$
6155
		    consumeMethodInvocationPrimaryWithTypeArguments();  
6162
		    consumeMethodInvocationNameWithTypeArguments();  
6156
			break;
6163
			break;
6157
 
6164
 
6158
    case 399 : if (DEBUG) { System.out.println("MethodInvocation ::= Primary DOT Identifier LPAREN..."); }  //$NON-NLS-1$
6165
    case 399 : if (DEBUG) { System.out.println("MethodInvocation ::= Primary DOT OnlyTypeArguments..."); }  //$NON-NLS-1$
6159
		    consumeMethodInvocationPrimary();  
6166
		    consumeMethodInvocationPrimaryWithTypeArguments();  
6160
			break;
6167
			break;
6161
 
6168
 
6162
    case 400 : if (DEBUG) { System.out.println("MethodInvocation ::= super DOT OnlyTypeArguments..."); }  //$NON-NLS-1$
6169
    case 400 : if (DEBUG) { System.out.println("MethodInvocation ::= Primary DOT Identifier LPAREN..."); }  //$NON-NLS-1$
6163
		    consumeMethodInvocationSuperWithTypeArguments();  
6170
		    consumeMethodInvocationPrimary();  
6164
			break;
6171
			break;
6165
 
6172
 
6166
    case 401 : if (DEBUG) { System.out.println("MethodInvocation ::= super DOT Identifier LPAREN..."); }  //$NON-NLS-1$
6173
    case 401 : if (DEBUG) { System.out.println("MethodInvocation ::= super DOT OnlyTypeArguments..."); }  //$NON-NLS-1$
6167
		    consumeMethodInvocationSuper();  
6174
		    consumeMethodInvocationSuperWithTypeArguments();  
6168
			break;
6175
			break;
6169
 
6176
 
6170
    case 402 : if (DEBUG) { System.out.println("ArrayAccess ::= Name LBRACKET Expression RBRACKET"); }  //$NON-NLS-1$
6177
    case 402 : if (DEBUG) { System.out.println("MethodInvocation ::= super DOT Identifier LPAREN..."); }  //$NON-NLS-1$
6171
		    consumeArrayAccess(true);  
6178
		    consumeMethodInvocationSuper();  
6172
			break;
6179
			break;
6173
 
6180
 
6174
    case 403 : if (DEBUG) { System.out.println("ArrayAccess ::= PrimaryNoNewArray LBRACKET Expression..."); }  //$NON-NLS-1$
6181
    case 403 : if (DEBUG) { System.out.println("ArrayAccess ::= Name LBRACKET Expression RBRACKET"); }  //$NON-NLS-1$
6175
		    consumeArrayAccess(false);  
6182
		    consumeArrayAccess(true);  
6176
			break;
6183
			break;
6177
 
6184
 
6178
    case 404 : if (DEBUG) { System.out.println("ArrayAccess ::= ArrayCreationWithArrayInitializer..."); }  //$NON-NLS-1$
6185
    case 404 : if (DEBUG) { System.out.println("ArrayAccess ::= PrimaryNoNewArray LBRACKET Expression..."); }  //$NON-NLS-1$
6179
		    consumeArrayAccess(false);  
6186
		    consumeArrayAccess(false);  
6180
			break;
6187
			break;
6181
 
6188
 
6182
    case 406 : if (DEBUG) { System.out.println("PostfixExpression ::= Name"); }  //$NON-NLS-1$
6189
    case 405 : if (DEBUG) { System.out.println("ArrayAccess ::= ArrayCreationWithArrayInitializer..."); }  //$NON-NLS-1$
6183
		    consumePostfixExpression();  
6190
		    consumeArrayAccess(false);  
6184
			break;
6191
			break;
6185
 
6192
 
6186
    case 409 : if (DEBUG) { System.out.println("PostIncrementExpression ::= PostfixExpression PLUS_PLUS"); }  //$NON-NLS-1$
6193
    case 407 : if (DEBUG) { System.out.println("PostfixExpression ::= Name"); }  //$NON-NLS-1$
6187
		    consumeUnaryExpression(OperatorIds.PLUS,true);  
6194
		    consumePostfixExpression();  
6188
			break;
6195
			break;
6189
 
6196
 
6190
    case 410 : if (DEBUG) { System.out.println("PostDecrementExpression ::= PostfixExpression..."); }  //$NON-NLS-1$
6197
    case 410 : if (DEBUG) { System.out.println("PostIncrementExpression ::= PostfixExpression PLUS_PLUS"); }  //$NON-NLS-1$
6191
		    consumeUnaryExpression(OperatorIds.MINUS,true);  
6198
		    consumeUnaryExpression(OperatorIds.PLUS,true);  
6192
			break;
6199
			break;
6193
 
6200
 
6194
    case 411 : if (DEBUG) { System.out.println("PushPosition ::="); }  //$NON-NLS-1$
6201
    case 411 : if (DEBUG) { System.out.println("PostDecrementExpression ::= PostfixExpression..."); }  //$NON-NLS-1$
6195
		    consumePushPosition();  
6202
		    consumeUnaryExpression(OperatorIds.MINUS,true);  
6196
			break;
6203
			break;
6197
 
6204
 
6198
    case 414 : if (DEBUG) { System.out.println("UnaryExpression ::= PLUS PushPosition UnaryExpression"); }  //$NON-NLS-1$
6205
    case 412 : if (DEBUG) { System.out.println("PushPosition ::="); }  //$NON-NLS-1$
6199
		    consumeUnaryExpression(OperatorIds.PLUS);  
6206
		    consumePushPosition();  
6200
			break;
6207
			break;
6201
 
6208
 
6202
    case 415 : if (DEBUG) { System.out.println("UnaryExpression ::= MINUS PushPosition UnaryExpression"); }  //$NON-NLS-1$
6209
    case 415 : if (DEBUG) { System.out.println("UnaryExpression ::= PLUS PushPosition UnaryExpression"); }  //$NON-NLS-1$
6203
		    consumeUnaryExpression(OperatorIds.MINUS);  
6210
		    consumeUnaryExpression(OperatorIds.PLUS);  
6204
			break;
6211
			break;
6205
 
6212
 
6206
    case 417 : if (DEBUG) { System.out.println("PreIncrementExpression ::= PLUS_PLUS PushPosition..."); }  //$NON-NLS-1$
6213
    case 416 : if (DEBUG) { System.out.println("UnaryExpression ::= MINUS PushPosition UnaryExpression"); }  //$NON-NLS-1$
6207
		    consumeUnaryExpression(OperatorIds.PLUS,false);  
6214
		    consumeUnaryExpression(OperatorIds.MINUS);  
6208
			break;
6215
			break;
6209
 
6216
 
6210
    case 418 : if (DEBUG) { System.out.println("PreDecrementExpression ::= MINUS_MINUS PushPosition..."); }  //$NON-NLS-1$
6217
    case 418 : if (DEBUG) { System.out.println("PreIncrementExpression ::= PLUS_PLUS PushPosition..."); }  //$NON-NLS-1$
6211
		    consumeUnaryExpression(OperatorIds.MINUS,false);  
6218
		    consumeUnaryExpression(OperatorIds.PLUS,false);  
6212
			break;
6219
			break;
6213
 
6220
 
6214
    case 420 : if (DEBUG) { System.out.println("UnaryExpressionNotPlusMinus ::= TWIDDLE PushPosition..."); }  //$NON-NLS-1$
6221
    case 419 : if (DEBUG) { System.out.println("PreDecrementExpression ::= MINUS_MINUS PushPosition..."); }  //$NON-NLS-1$
6215
		    consumeUnaryExpression(OperatorIds.TWIDDLE);  
6222
		    consumeUnaryExpression(OperatorIds.MINUS,false);  
6216
			break;
6223
			break;
6217
 
6224
 
6218
    case 421 : if (DEBUG) { System.out.println("UnaryExpressionNotPlusMinus ::= NOT PushPosition..."); }  //$NON-NLS-1$
6225
    case 421 : if (DEBUG) { System.out.println("UnaryExpressionNotPlusMinus ::= TWIDDLE PushPosition..."); }  //$NON-NLS-1$
6219
		    consumeUnaryExpression(OperatorIds.NOT);  
6226
		    consumeUnaryExpression(OperatorIds.TWIDDLE);  
6220
			break;
6227
			break;
6221
 
6228
 
6222
    case 423 : if (DEBUG) { System.out.println("CastExpression ::= PushLPAREN PrimitiveType Dimsopt..."); }  //$NON-NLS-1$
6229
    case 422 : if (DEBUG) { System.out.println("UnaryExpressionNotPlusMinus ::= NOT PushPosition..."); }  //$NON-NLS-1$
6223
		    consumeCastExpressionWithPrimitiveType();  
6230
		    consumeUnaryExpression(OperatorIds.NOT);  
6224
			break;
6231
			break;
6225
 
6232
 
6226
    case 424 : if (DEBUG) { System.out.println("CastExpression ::= PushLPAREN Name..."); }  //$NON-NLS-1$
6233
    case 424 : if (DEBUG) { System.out.println("CastExpression ::= PushLPAREN PrimitiveType Dimsopt..."); }  //$NON-NLS-1$
6227
		    consumeCastExpressionWithGenericsArray();  
6234
		    consumeCastExpressionWithPrimitiveType();  
6228
			break;
6235
			break;
6229
 
6236
 
6230
    case 425 : if (DEBUG) { System.out.println("CastExpression ::= PushLPAREN Name..."); }  //$NON-NLS-1$
6237
    case 425 : if (DEBUG) { System.out.println("CastExpression ::= PushLPAREN Name..."); }  //$NON-NLS-1$
6231
		    consumeCastExpressionWithQualifiedGenericsArray();  
6238
		    consumeCastExpressionWithGenericsArray();  
6232
			break;
6239
			break;
6233
 
6240
 
6234
    case 426 : if (DEBUG) { System.out.println("CastExpression ::= PushLPAREN Name PushRPAREN..."); }  //$NON-NLS-1$
6241
    case 426 : if (DEBUG) { System.out.println("CastExpression ::= PushLPAREN Name..."); }  //$NON-NLS-1$
6235
		    consumeCastExpressionLL1();  
6242
		    consumeCastExpressionWithQualifiedGenericsArray();  
6236
			break;
6243
			break;
6237
 
6244
 
6238
    case 427 : if (DEBUG) { System.out.println("CastExpression ::= PushLPAREN Name Dims PushRPAREN..."); }  //$NON-NLS-1$
6245
    case 427 : if (DEBUG) { System.out.println("CastExpression ::= PushLPAREN Name PushRPAREN..."); }  //$NON-NLS-1$
6239
		    consumeCastExpressionWithNameArray();  
6246
		    consumeCastExpressionLL1();  
6240
			break;
6247
			break;
6241
 
6248
 
6242
    case 428 : if (DEBUG) { System.out.println("OnlyTypeArgumentsForCastExpression ::= OnlyTypeArguments"); }  //$NON-NLS-1$
6249
    case 428 : if (DEBUG) { System.out.println("CastExpression ::= PushLPAREN Name Dims PushRPAREN..."); }  //$NON-NLS-1$
6243
		    consumeOnlyTypeArgumentsForCastExpression();  
6250
		    consumeCastExpressionWithNameArray();  
6244
			break;
6251
			break;
6245
 
6252
 
6246
    case 429 : if (DEBUG) { System.out.println("InsideCastExpression ::="); }  //$NON-NLS-1$
6253
    case 429 : if (DEBUG) { System.out.println("OnlyTypeArgumentsForCastExpression ::= OnlyTypeArguments"); }  //$NON-NLS-1$
6247
		    consumeInsideCastExpression();  
6254
		    consumeOnlyTypeArgumentsForCastExpression();  
6248
			break;
6255
			break;
6249
 
6256
 
6250
    case 430 : if (DEBUG) { System.out.println("InsideCastExpressionLL1 ::="); }  //$NON-NLS-1$
6257
    case 430 : if (DEBUG) { System.out.println("InsideCastExpression ::="); }  //$NON-NLS-1$
6251
		    consumeInsideCastExpressionLL1();  
6258
		    consumeInsideCastExpression();  
6252
			break;
6259
			break;
6253
 
6260
 
6254
    case 431 : if (DEBUG) { System.out.println("InsideCastExpressionWithQualifiedGenerics ::="); }  //$NON-NLS-1$
6261
    case 431 : if (DEBUG) { System.out.println("InsideCastExpressionLL1 ::="); }  //$NON-NLS-1$
6255
		    consumeInsideCastExpressionWithQualifiedGenerics();  
6262
		    consumeInsideCastExpressionLL1();  
6256
			break;
6263
			break;
6257
 
6264
 
6258
    case 433 : if (DEBUG) { System.out.println("MultiplicativeExpression ::= MultiplicativeExpression..."); }  //$NON-NLS-1$
6265
    case 432 : if (DEBUG) { System.out.println("InsideCastExpressionWithQualifiedGenerics ::="); }  //$NON-NLS-1$
6259
		    consumeBinaryExpression(OperatorIds.MULTIPLY);  
6266
		    consumeInsideCastExpressionWithQualifiedGenerics();  
6260
			break;
6267
			break;
6261
 
6268
 
6262
    case 434 : if (DEBUG) { System.out.println("MultiplicativeExpression ::= MultiplicativeExpression..."); }  //$NON-NLS-1$
6269
    case 434 : if (DEBUG) { System.out.println("MultiplicativeExpression ::= MultiplicativeExpression..."); }  //$NON-NLS-1$
6263
		    consumeBinaryExpression(OperatorIds.DIVIDE);  
6270
		    consumeBinaryExpression(OperatorIds.MULTIPLY);  
6264
			break;
6271
			break;
6265
 
6272
 
6266
    case 435 : if (DEBUG) { System.out.println("MultiplicativeExpression ::= MultiplicativeExpression..."); }  //$NON-NLS-1$
6273
    case 435 : if (DEBUG) { System.out.println("MultiplicativeExpression ::= MultiplicativeExpression..."); }  //$NON-NLS-1$
6267
		    consumeBinaryExpression(OperatorIds.REMAINDER);  
6274
		    consumeBinaryExpression(OperatorIds.DIVIDE);  
6268
			break;
6275
			break;
6269
 
6276
 
6270
    case 437 : if (DEBUG) { System.out.println("AdditiveExpression ::= AdditiveExpression PLUS..."); }  //$NON-NLS-1$
6277
    case 436 : if (DEBUG) { System.out.println("MultiplicativeExpression ::= MultiplicativeExpression..."); }  //$NON-NLS-1$
6271
		    consumeBinaryExpression(OperatorIds.PLUS);  
6278
		    consumeBinaryExpression(OperatorIds.REMAINDER);  
6272
			break;
6279
			break;
6273
 
6280
 
6274
    case 438 : if (DEBUG) { System.out.println("AdditiveExpression ::= AdditiveExpression MINUS..."); }  //$NON-NLS-1$
6281
    case 438 : if (DEBUG) { System.out.println("AdditiveExpression ::= AdditiveExpression PLUS..."); }  //$NON-NLS-1$
6275
		    consumeBinaryExpression(OperatorIds.MINUS);  
6282
		    consumeBinaryExpression(OperatorIds.PLUS);  
6276
			break;
6283
			break;
6277
 
6284
 
6278
    case 440 : if (DEBUG) { System.out.println("ShiftExpression ::= ShiftExpression LEFT_SHIFT..."); }  //$NON-NLS-1$
6285
    case 439 : if (DEBUG) { System.out.println("AdditiveExpression ::= AdditiveExpression MINUS..."); }  //$NON-NLS-1$
6279
		    consumeBinaryExpression(OperatorIds.LEFT_SHIFT);  
6286
		    consumeBinaryExpression(OperatorIds.MINUS);  
6280
			break;
6287
			break;
6281
 
6288
 
6282
    case 441 : if (DEBUG) { System.out.println("ShiftExpression ::= ShiftExpression RIGHT_SHIFT..."); }  //$NON-NLS-1$
6289
    case 441 : if (DEBUG) { System.out.println("ShiftExpression ::= ShiftExpression LEFT_SHIFT..."); }  //$NON-NLS-1$
6283
		    consumeBinaryExpression(OperatorIds.RIGHT_SHIFT);  
6290
		    consumeBinaryExpression(OperatorIds.LEFT_SHIFT);  
6284
			break;
6291
			break;
6285
 
6292
 
6286
    case 442 : if (DEBUG) { System.out.println("ShiftExpression ::= ShiftExpression UNSIGNED_RIGHT_SHIFT"); }  //$NON-NLS-1$
6293
    case 442 : if (DEBUG) { System.out.println("ShiftExpression ::= ShiftExpression RIGHT_SHIFT..."); }  //$NON-NLS-1$
6287
		    consumeBinaryExpression(OperatorIds.UNSIGNED_RIGHT_SHIFT);  
6294
		    consumeBinaryExpression(OperatorIds.RIGHT_SHIFT);  
6288
			break;
6295
			break;
6289
 
6296
 
6290
    case 444 : if (DEBUG) { System.out.println("RelationalExpression ::= RelationalExpression LESS..."); }  //$NON-NLS-1$
6297
    case 443 : if (DEBUG) { System.out.println("ShiftExpression ::= ShiftExpression UNSIGNED_RIGHT_SHIFT"); }  //$NON-NLS-1$
6291
		    consumeBinaryExpression(OperatorIds.LESS);  
6298
		    consumeBinaryExpression(OperatorIds.UNSIGNED_RIGHT_SHIFT);  
6292
			break;
6299
			break;
6293
 
6300
 
6294
    case 445 : if (DEBUG) { System.out.println("RelationalExpression ::= RelationalExpression GREATER..."); }  //$NON-NLS-1$
6301
    case 445 : if (DEBUG) { System.out.println("RelationalExpression ::= RelationalExpression LESS..."); }  //$NON-NLS-1$
6295
		    consumeBinaryExpression(OperatorIds.GREATER);  
6302
		    consumeBinaryExpression(OperatorIds.LESS);  
6296
			break;
6303
			break;
6297
 
6304
 
6298
    case 446 : if (DEBUG) { System.out.println("RelationalExpression ::= RelationalExpression LESS_EQUAL"); }  //$NON-NLS-1$
6305
    case 446 : if (DEBUG) { System.out.println("RelationalExpression ::= RelationalExpression GREATER..."); }  //$NON-NLS-1$
6299
		    consumeBinaryExpression(OperatorIds.LESS_EQUAL);  
6306
		    consumeBinaryExpression(OperatorIds.GREATER);  
6300
			break;
6307
			break;
6301
 
6308
 
6302
    case 447 : if (DEBUG) { System.out.println("RelationalExpression ::= RelationalExpression..."); }  //$NON-NLS-1$
6309
    case 447 : if (DEBUG) { System.out.println("RelationalExpression ::= RelationalExpression LESS_EQUAL"); }  //$NON-NLS-1$
6303
		    consumeBinaryExpression(OperatorIds.GREATER_EQUAL);  
6310
		    consumeBinaryExpression(OperatorIds.LESS_EQUAL);  
6304
			break;
6311
			break;
6305
 
6312
 
6306
    case 449 : if (DEBUG) { System.out.println("InstanceofExpression ::= InstanceofExpression instanceof"); }  //$NON-NLS-1$
6313
    case 448 : if (DEBUG) { System.out.println("RelationalExpression ::= RelationalExpression..."); }  //$NON-NLS-1$
6307
		    consumeInstanceOfExpression();  
6314
		    consumeBinaryExpression(OperatorIds.GREATER_EQUAL);  
6308
			break;
6315
			break;
6309
 
6316
 
6310
    case 451 : if (DEBUG) { System.out.println("EqualityExpression ::= EqualityExpression EQUAL_EQUAL..."); }  //$NON-NLS-1$
6317
    case 450 : if (DEBUG) { System.out.println("InstanceofExpression ::= InstanceofExpression instanceof"); }  //$NON-NLS-1$
6311
		    consumeEqualityExpression(OperatorIds.EQUAL_EQUAL);  
6318
		    consumeInstanceOfExpression();  
6312
			break;
6319
			break;
6313
 
6320
 
6314
    case 452 : if (DEBUG) { System.out.println("EqualityExpression ::= EqualityExpression NOT_EQUAL..."); }  //$NON-NLS-1$
6321
    case 452 : if (DEBUG) { System.out.println("EqualityExpression ::= EqualityExpression EQUAL_EQUAL..."); }  //$NON-NLS-1$
6315
		    consumeEqualityExpression(OperatorIds.NOT_EQUAL);  
6322
		    consumeEqualityExpression(OperatorIds.EQUAL_EQUAL);  
6316
			break;
6323
			break;
6317
 
6324
 
6318
    case 454 : if (DEBUG) { System.out.println("AndExpression ::= AndExpression AND EqualityExpression"); }  //$NON-NLS-1$
6325
    case 453 : if (DEBUG) { System.out.println("EqualityExpression ::= EqualityExpression NOT_EQUAL..."); }  //$NON-NLS-1$
6319
		    consumeBinaryExpression(OperatorIds.AND);  
6326
		    consumeEqualityExpression(OperatorIds.NOT_EQUAL);  
6320
			break;
6327
			break;
6321
 
6328
 
6322
    case 456 : if (DEBUG) { System.out.println("ExclusiveOrExpression ::= ExclusiveOrExpression XOR..."); }  //$NON-NLS-1$
6329
    case 455 : if (DEBUG) { System.out.println("AndExpression ::= AndExpression AND EqualityExpression"); }  //$NON-NLS-1$
6323
		    consumeBinaryExpression(OperatorIds.XOR);  
6330
		    consumeBinaryExpression(OperatorIds.AND);  
6324
			break;
6331
			break;
6325
 
6332
 
6326
    case 458 : if (DEBUG) { System.out.println("InclusiveOrExpression ::= InclusiveOrExpression OR..."); }  //$NON-NLS-1$
6333
    case 457 : if (DEBUG) { System.out.println("ExclusiveOrExpression ::= ExclusiveOrExpression XOR..."); }  //$NON-NLS-1$
6327
		    consumeBinaryExpression(OperatorIds.OR);  
6334
		    consumeBinaryExpression(OperatorIds.XOR);  
6328
			break;
6335
			break;
6329
 
6336
 
6330
    case 460 : if (DEBUG) { System.out.println("ConditionalAndExpression ::= ConditionalAndExpression..."); }  //$NON-NLS-1$
6337
    case 459 : if (DEBUG) { System.out.println("InclusiveOrExpression ::= InclusiveOrExpression OR..."); }  //$NON-NLS-1$
6331
		    consumeBinaryExpression(OperatorIds.AND_AND);  
6338
		    consumeBinaryExpression(OperatorIds.OR);  
6332
			break;
6339
			break;
6333
 
6340
 
6334
    case 462 : if (DEBUG) { System.out.println("ConditionalOrExpression ::= ConditionalOrExpression..."); }  //$NON-NLS-1$
6341
    case 461 : if (DEBUG) { System.out.println("ConditionalAndExpression ::= ConditionalAndExpression..."); }  //$NON-NLS-1$
6335
		    consumeBinaryExpression(OperatorIds.OR_OR);  
6342
		    consumeBinaryExpression(OperatorIds.AND_AND);  
6336
			break;
6343
			break;
6337
 
6344
 
6338
    case 464 : if (DEBUG) { System.out.println("ConditionalExpression ::= ConditionalOrExpression..."); }  //$NON-NLS-1$
6345
    case 463 : if (DEBUG) { System.out.println("ConditionalOrExpression ::= ConditionalOrExpression..."); }  //$NON-NLS-1$
6339
		    consumeConditionalExpression(OperatorIds.QUESTIONCOLON) ;  
6346
		    consumeBinaryExpression(OperatorIds.OR_OR);  
6340
			break;
6347
			break;
6341
 
6348
 
6342
    case 467 : if (DEBUG) { System.out.println("Assignment ::= PostfixExpression AssignmentOperator..."); }  //$NON-NLS-1$
6349
    case 465 : if (DEBUG) { System.out.println("ConditionalExpression ::= ConditionalOrExpression..."); }  //$NON-NLS-1$
6343
		    consumeAssignment();  
6350
		    consumeConditionalExpression(OperatorIds.QUESTIONCOLON) ;  
6344
			break;
6351
			break;
6345
 
6352
 
6346
    case 469 : if (DEBUG) { System.out.println("Assignment ::= InvalidArrayInitializerAssignement"); }  //$NON-NLS-1$
6353
    case 468 : if (DEBUG) { System.out.println("Assignment ::= PostfixExpression AssignmentOperator..."); }  //$NON-NLS-1$
6347
		    ignoreExpressionAssignment(); 
6354
		    consumeAssignment();  
6348
			break;
6355
			break;
6349
 
6356
 
6350
    case 470 : if (DEBUG) { System.out.println("AssignmentOperator ::= EQUAL"); }  //$NON-NLS-1$
6357
    case 470 : if (DEBUG) { System.out.println("Assignment ::= InvalidArrayInitializerAssignement"); }  //$NON-NLS-1$
6351
		    consumeAssignmentOperator(EQUAL);  
6358
		    ignoreExpressionAssignment(); 
6352
			break;
6359
			break;
6353
 
6360
 
6354
    case 471 : if (DEBUG) { System.out.println("AssignmentOperator ::= MULTIPLY_EQUAL"); }  //$NON-NLS-1$
6361
    case 471 : if (DEBUG) { System.out.println("AssignmentOperator ::= EQUAL"); }  //$NON-NLS-1$
6355
		    consumeAssignmentOperator(MULTIPLY);  
6362
		    consumeAssignmentOperator(EQUAL);  
6356
			break;
6363
			break;
6357
 
6364
 
6358
    case 472 : if (DEBUG) { System.out.println("AssignmentOperator ::= DIVIDE_EQUAL"); }  //$NON-NLS-1$
6365
    case 472 : if (DEBUG) { System.out.println("AssignmentOperator ::= MULTIPLY_EQUAL"); }  //$NON-NLS-1$
6359
		    consumeAssignmentOperator(DIVIDE);  
6366
		    consumeAssignmentOperator(MULTIPLY);  
6360
			break;
6367
			break;
6361
 
6368
 
6362
    case 473 : if (DEBUG) { System.out.println("AssignmentOperator ::= REMAINDER_EQUAL"); }  //$NON-NLS-1$
6369
    case 473 : if (DEBUG) { System.out.println("AssignmentOperator ::= DIVIDE_EQUAL"); }  //$NON-NLS-1$
6363
		    consumeAssignmentOperator(REMAINDER);  
6370
		    consumeAssignmentOperator(DIVIDE);  
6364
			break;
6371
			break;
6365
 
6372
 
6366
    case 474 : if (DEBUG) { System.out.println("AssignmentOperator ::= PLUS_EQUAL"); }  //$NON-NLS-1$
6373
    case 474 : if (DEBUG) { System.out.println("AssignmentOperator ::= REMAINDER_EQUAL"); }  //$NON-NLS-1$
6367
		    consumeAssignmentOperator(PLUS);  
6374
		    consumeAssignmentOperator(REMAINDER);  
6368
			break;
6375
			break;
6369
 
6376
 
6370
    case 475 : if (DEBUG) { System.out.println("AssignmentOperator ::= MINUS_EQUAL"); }  //$NON-NLS-1$
6377
    case 475 : if (DEBUG) { System.out.println("AssignmentOperator ::= PLUS_EQUAL"); }  //$NON-NLS-1$
6371
		    consumeAssignmentOperator(MINUS);  
6378
		    consumeAssignmentOperator(PLUS);  
6372
			break;
6379
			break;
6373
 
6380
 
6374
    case 476 : if (DEBUG) { System.out.println("AssignmentOperator ::= LEFT_SHIFT_EQUAL"); }  //$NON-NLS-1$
6381
    case 476 : if (DEBUG) { System.out.println("AssignmentOperator ::= MINUS_EQUAL"); }  //$NON-NLS-1$
6375
		    consumeAssignmentOperator(LEFT_SHIFT);  
6382
		    consumeAssignmentOperator(MINUS);  
6376
			break;
6383
			break;
6377
 
6384
 
6378
    case 477 : if (DEBUG) { System.out.println("AssignmentOperator ::= RIGHT_SHIFT_EQUAL"); }  //$NON-NLS-1$
6385
    case 477 : if (DEBUG) { System.out.println("AssignmentOperator ::= LEFT_SHIFT_EQUAL"); }  //$NON-NLS-1$
6379
		    consumeAssignmentOperator(RIGHT_SHIFT);  
6386
		    consumeAssignmentOperator(LEFT_SHIFT);  
6380
			break;
6387
			break;
6381
 
6388
 
6382
    case 478 : if (DEBUG) { System.out.println("AssignmentOperator ::= UNSIGNED_RIGHT_SHIFT_EQUAL"); }  //$NON-NLS-1$
6389
    case 478 : if (DEBUG) { System.out.println("AssignmentOperator ::= RIGHT_SHIFT_EQUAL"); }  //$NON-NLS-1$
6383
		    consumeAssignmentOperator(UNSIGNED_RIGHT_SHIFT);  
6390
		    consumeAssignmentOperator(RIGHT_SHIFT);  
6384
			break;
6391
			break;
6385
 
6392
 
6386
    case 479 : if (DEBUG) { System.out.println("AssignmentOperator ::= AND_EQUAL"); }  //$NON-NLS-1$
6393
    case 479 : if (DEBUG) { System.out.println("AssignmentOperator ::= UNSIGNED_RIGHT_SHIFT_EQUAL"); }  //$NON-NLS-1$
6387
		    consumeAssignmentOperator(AND);  
6394
		    consumeAssignmentOperator(UNSIGNED_RIGHT_SHIFT);  
6388
			break;
6395
			break;
6389
 
6396
 
6390
    case 480 : if (DEBUG) { System.out.println("AssignmentOperator ::= XOR_EQUAL"); }  //$NON-NLS-1$
6397
    case 480 : if (DEBUG) { System.out.println("AssignmentOperator ::= AND_EQUAL"); }  //$NON-NLS-1$
6391
		    consumeAssignmentOperator(XOR);  
6398
		    consumeAssignmentOperator(AND);  
6392
			break;
6399
			break;
6393
 
6400
 
6394
    case 481 : if (DEBUG) { System.out.println("AssignmentOperator ::= OR_EQUAL"); }  //$NON-NLS-1$
6401
    case 481 : if (DEBUG) { System.out.println("AssignmentOperator ::= XOR_EQUAL"); }  //$NON-NLS-1$
6395
		    consumeAssignmentOperator(OR);  
6402
		    consumeAssignmentOperator(XOR);  
6396
			break;
6403
			break;
6397
 
6404
 
6398
    case 485 : if (DEBUG) { System.out.println("Expressionopt ::="); }  //$NON-NLS-1$
6405
    case 482 : if (DEBUG) { System.out.println("AssignmentOperator ::= OR_EQUAL"); }  //$NON-NLS-1$
6399
		    consumeEmptyExpression();  
6406
		    consumeAssignmentOperator(OR);  
6400
			break;
6407
			break;
6401
 
6408
 
6402
    case 490 : if (DEBUG) { System.out.println("ClassBodyDeclarationsopt ::="); }  //$NON-NLS-1$
6409
    case 486 : if (DEBUG) { System.out.println("Expressionopt ::="); }  //$NON-NLS-1$
6403
		    consumeEmptyClassBodyDeclarationsopt();  
6410
		    consumeEmptyExpression();  
6404
			break;
6411
			break;
6405
 
6412
 
6406
    case 491 : if (DEBUG) { System.out.println("ClassBodyDeclarationsopt ::= NestedType..."); }  //$NON-NLS-1$
6413
    case 491 : if (DEBUG) { System.out.println("ClassBodyDeclarationsopt ::="); }  //$NON-NLS-1$
6407
		    consumeClassBodyDeclarationsopt();  
6414
		    consumeEmptyClassBodyDeclarationsopt();  
6408
			break;
6415
			break;
6409
 
6416
 
6410
     case 492 : if (DEBUG) { System.out.println("Modifiersopt ::="); }  //$NON-NLS-1$
6417
    case 492 : if (DEBUG) { System.out.println("ClassBodyDeclarationsopt ::= NestedType..."); }  //$NON-NLS-1$
6411
		    consumeDefaultModifiers();  
6418
		    consumeClassBodyDeclarationsopt();  
6412
			break;
6419
			break;
6413
 
6420
 
6414
    case 493 : if (DEBUG) { System.out.println("Modifiersopt ::= Modifiers"); }  //$NON-NLS-1$
6421
     case 493 : if (DEBUG) { System.out.println("Modifiersopt ::="); }  //$NON-NLS-1$
6415
		    consumeModifiers();  
6422
		    consumeDefaultModifiers();  
6416
			break;
6423
			break;
6417
 
6424
 
6418
    case 494 : if (DEBUG) { System.out.println("BlockStatementsopt ::="); }  //$NON-NLS-1$
6425
    case 494 : if (DEBUG) { System.out.println("Modifiersopt ::= Modifiers"); }  //$NON-NLS-1$
6419
		    consumeEmptyBlockStatementsopt();  
6426
		    consumeModifiers();  
6420
			break;
6427
			break;
6421
 
6428
 
6422
     case 496 : if (DEBUG) { System.out.println("Dimsopt ::="); }  //$NON-NLS-1$
6429
    case 495 : if (DEBUG) { System.out.println("BlockStatementsopt ::="); }  //$NON-NLS-1$
6423
		    consumeEmptyDimsopt();  
6430
		    consumeEmptyBlockStatementsopt();  
6424
			break;
6431
			break;
6425
 
6432
 
6426
     case 498 : if (DEBUG) { System.out.println("ArgumentListopt ::="); }  //$NON-NLS-1$
6433
     case 497 : if (DEBUG) { System.out.println("Dimsopt ::="); }  //$NON-NLS-1$
6427
		    consumeEmptyArgumentListopt();  
6434
		    consumeEmptyDimsopt();  
6428
			break;
6435
			break;
6429
 
6436
 
6430
    case 502 : if (DEBUG) { System.out.println("FormalParameterListopt ::="); }  //$NON-NLS-1$
6437
     case 499 : if (DEBUG) { System.out.println("ArgumentListopt ::="); }  //$NON-NLS-1$
6431
		    consumeFormalParameterListopt();  
6438
		    consumeEmptyArgumentListopt();  
6432
			break;
6439
			break;
6433
 
6440
 
6434
     case 506 : if (DEBUG) { System.out.println("InterfaceMemberDeclarationsopt ::="); }  //$NON-NLS-1$
6441
    case 503 : if (DEBUG) { System.out.println("FormalParameterListopt ::="); }  //$NON-NLS-1$
6435
		    consumeEmptyInterfaceMemberDeclarationsopt();  
6442
		    consumeFormalParameterListopt();  
6436
			break;
6443
			break;
6437
 
6444
 
6438
     case 507 : if (DEBUG) { System.out.println("InterfaceMemberDeclarationsopt ::= NestedType..."); }  //$NON-NLS-1$
6445
     case 507 : if (DEBUG) { System.out.println("InterfaceMemberDeclarationsopt ::="); }  //$NON-NLS-1$
6439
		    consumeInterfaceMemberDeclarationsopt();  
6446
		    consumeEmptyInterfaceMemberDeclarationsopt();  
6440
			break;
6447
			break;
6441
 
6448
 
6442
    case 508 : if (DEBUG) { System.out.println("NestedType ::="); }  //$NON-NLS-1$
6449
     case 508 : if (DEBUG) { System.out.println("InterfaceMemberDeclarationsopt ::= NestedType..."); }  //$NON-NLS-1$
6443
		    consumeNestedType();  
6450
		    consumeInterfaceMemberDeclarationsopt();  
6444
			break;
6451
			break;
6445
6452
 
6446
     case 509 : if (DEBUG) { System.out.println("ForInitopt ::="); }  //$NON-NLS-1$
6453
    case 509 : if (DEBUG) { System.out.println("NestedType ::="); }  //$NON-NLS-1$
6447
		    consumeEmptyForInitopt();  
6454
		    consumeNestedType();  
6448
			break;
6455
			break;
6449
 
6456
6450
     case 511 : if (DEBUG) { System.out.println("ForUpdateopt ::="); }  //$NON-NLS-1$
6457
     case 510 : if (DEBUG) { System.out.println("ForInitopt ::="); }  //$NON-NLS-1$
6451
		    consumeEmptyForUpdateopt();  
6458
		    consumeEmptyForInitopt();  
6452
			break;
6459
			break;
6453
 
6460
 
6454
     case 515 : if (DEBUG) { System.out.println("Catchesopt ::="); }  //$NON-NLS-1$
6461
     case 512 : if (DEBUG) { System.out.println("ForUpdateopt ::="); }  //$NON-NLS-1$
6455
		    consumeEmptyCatchesopt();  
6462
		    consumeEmptyForUpdateopt();  
6456
			break;
6463
			break;
6457
 
6464
 
6458
     case 517 : if (DEBUG) { System.out.println("EnumDeclaration ::= EnumHeader EnumBody"); }  //$NON-NLS-1$
6465
     case 516 : if (DEBUG) { System.out.println("Catchesopt ::="); }  //$NON-NLS-1$
6459
		    consumeEnumDeclaration();  
6466
		    consumeEmptyCatchesopt();  
6460
			break;
6467
			break;
6461
 
6468
 
6462
     case 518 : if (DEBUG) { System.out.println("EnumHeader ::= EnumHeaderName ClassHeaderImplementsopt"); }  //$NON-NLS-1$
6469
     case 518 : if (DEBUG) { System.out.println("EnumDeclaration ::= EnumHeader EnumBody"); }  //$NON-NLS-1$
6463
		    consumeEnumHeader();  
6470
		    consumeEnumDeclaration();  
6464
			break;
6471
			break;
6465
 
6472
 
6466
     case 519 : if (DEBUG) { System.out.println("EnumHeaderName ::= Modifiersopt enum Identifier"); }  //$NON-NLS-1$
6473
     case 519 : if (DEBUG) { System.out.println("EnumHeader ::= EnumHeaderName ClassHeaderImplementsopt"); }  //$NON-NLS-1$
6467
		    consumeEnumHeaderName();  
6474
		    consumeEnumHeader();  
6468
			break;
6475
			break;
6469
 
6476
 
6470
     case 520 : if (DEBUG) { System.out.println("EnumHeaderName ::= Modifiersopt enum Identifier..."); }  //$NON-NLS-1$
6477
     case 520 : if (DEBUG) { System.out.println("EnumHeaderName ::= Modifiersopt enum Identifier"); }  //$NON-NLS-1$
6471
		    consumeEnumHeaderNameWithTypeParameters();  
6478
		    consumeEnumHeaderName();  
6472
			break;
6479
			break;
6473
 
6480
 
6474
     case 521 : if (DEBUG) { System.out.println("EnumBody ::= LBRACE EnumBodyDeclarationsopt RBRACE"); }  //$NON-NLS-1$
6481
     case 521 : if (DEBUG) { System.out.println("EnumHeaderName ::= Modifiersopt enum Identifier..."); }  //$NON-NLS-1$
6475
		    consumeEnumBodyNoConstants();  
6482
		    consumeEnumHeaderNameWithTypeParameters();  
6476
			break;
6483
			break;
6477
 
6484
 
6478
     case 522 : if (DEBUG) { System.out.println("EnumBody ::= LBRACE COMMA EnumBodyDeclarationsopt..."); }  //$NON-NLS-1$
6485
     case 522 : if (DEBUG) { System.out.println("EnumBody ::= LBRACE EnumBodyDeclarationsopt RBRACE"); }  //$NON-NLS-1$
6479
		    consumeEnumBodyNoConstants();  
6486
		    consumeEnumBodyNoConstants();  
6480
			break;
6487
			break;
6481
 
6488
 
6482
     case 523 : if (DEBUG) { System.out.println("EnumBody ::= LBRACE EnumConstants COMMA..."); }  //$NON-NLS-1$
6489
     case 523 : if (DEBUG) { System.out.println("EnumBody ::= LBRACE COMMA EnumBodyDeclarationsopt..."); }  //$NON-NLS-1$
6483
		    consumeEnumBodyWithConstants();  
6490
		    consumeEnumBodyNoConstants();  
6484
			break;
6491
			break;
6485
 
6492
 
6486
     case 524 : if (DEBUG) { System.out.println("EnumBody ::= LBRACE EnumConstants..."); }  //$NON-NLS-1$
6493
     case 524 : if (DEBUG) { System.out.println("EnumBody ::= LBRACE EnumConstants COMMA..."); }  //$NON-NLS-1$
6487
		    consumeEnumBodyWithConstants();  
6494
		    consumeEnumBodyWithConstants();  
6488
			break;
6495
			break;
6489
 
6496
 
6490
    case 526 : if (DEBUG) { System.out.println("EnumConstants ::= EnumConstants COMMA EnumConstant"); }  //$NON-NLS-1$
6497
     case 525 : if (DEBUG) { System.out.println("EnumBody ::= LBRACE EnumConstants..."); }  //$NON-NLS-1$
6491
		    consumeEnumConstants();  
6498
		    consumeEnumBodyWithConstants();  
6492
			break;
6499
			break;
6493
 
6500
 
6494
    case 527 : if (DEBUG) { System.out.println("EnumConstantHeaderName ::= Modifiersopt Identifier"); }  //$NON-NLS-1$
6501
    case 527 : if (DEBUG) { System.out.println("EnumConstants ::= EnumConstants COMMA EnumConstant"); }  //$NON-NLS-1$
6495
		    consumeEnumConstantHeaderName();  
6502
		    consumeEnumConstants();  
6496
			break;
6503
			break;
6497
 
6504
 
6498
    case 528 : if (DEBUG) { System.out.println("EnumConstantHeader ::= EnumConstantHeaderName..."); }  //$NON-NLS-1$
6505
    case 528 : if (DEBUG) { System.out.println("EnumConstantHeaderName ::= Modifiersopt Identifier"); }  //$NON-NLS-1$
6499
		    consumeEnumConstantHeader();  
6506
		    consumeEnumConstantHeaderName();  
6500
			break;
6507
			break;
6501
 
6508
 
6502
    case 529 : if (DEBUG) { System.out.println("EnumConstant ::= EnumConstantHeader ForceNoDiet..."); }  //$NON-NLS-1$
6509
    case 529 : if (DEBUG) { System.out.println("EnumConstantHeader ::= EnumConstantHeaderName..."); }  //$NON-NLS-1$
6503
		    consumeEnumConstantWithClassBody();  
6510
		    consumeEnumConstantHeader();  
6504
			break;
6511
			break;
6505
 
6512
 
6506
    case 530 : if (DEBUG) { System.out.println("EnumConstant ::= EnumConstantHeader"); }  //$NON-NLS-1$
6513
    case 530 : if (DEBUG) { System.out.println("EnumConstant ::= EnumConstantHeader ForceNoDiet..."); }  //$NON-NLS-1$
6507
		    consumeEnumConstantNoClassBody();  
6514
		    consumeEnumConstantWithClassBody();  
6508
			break;
6515
			break;
6509
 
6516
 
6510
    case 531 : if (DEBUG) { System.out.println("Arguments ::= LPAREN ArgumentListopt RPAREN"); }  //$NON-NLS-1$
6517
    case 531 : if (DEBUG) { System.out.println("EnumConstant ::= EnumConstantHeader"); }  //$NON-NLS-1$
6511
		    consumeArguments();  
6518
		    consumeEnumConstantNoClassBody();  
6512
			break;
6519
			break;
6513
 
6520
 
6514
    case 532 : if (DEBUG) { System.out.println("Argumentsopt ::="); }  //$NON-NLS-1$
6521
    case 532 : if (DEBUG) { System.out.println("Arguments ::= LPAREN ArgumentListopt RPAREN"); }  //$NON-NLS-1$
6515
		    consumeEmptyArguments();  
6522
		    consumeArguments();  
6516
			break;
6523
			break;
6517
 
6524
 
6518
    case 534 : if (DEBUG) { System.out.println("EnumDeclarations ::= SEMICOLON ClassBodyDeclarationsopt"); }  //$NON-NLS-1$
6525
    case 533 : if (DEBUG) { System.out.println("Argumentsopt ::="); }  //$NON-NLS-1$
6519
		    consumeEnumDeclarations();  
6526
		    consumeEmptyArguments();  
6520
			break;
6527
			break;
6521
 
6528
 
6522
    case 535 : if (DEBUG) { System.out.println("EnumBodyDeclarationsopt ::="); }  //$NON-NLS-1$
6529
    case 535 : if (DEBUG) { System.out.println("EnumDeclarations ::= SEMICOLON ClassBodyDeclarationsopt"); }  //$NON-NLS-1$
6523
		    consumeEmptyEnumDeclarations();  
6530
		    consumeEnumDeclarations();  
6524
			break;
6531
			break;
6525
 
6532
 
6526
    case 537 : if (DEBUG) { System.out.println("EnhancedForStatement ::= EnhancedForStatementHeader..."); }  //$NON-NLS-1$
6533
    case 536 : if (DEBUG) { System.out.println("EnumBodyDeclarationsopt ::="); }  //$NON-NLS-1$
6527
		    consumeEnhancedForStatement();  
6534
		    consumeEmptyEnumDeclarations();  
6528
			break;
6535
			break;
6529
 
6536
 
6530
    case 538 : if (DEBUG) { System.out.println("EnhancedForStatementNoShortIf ::=..."); }  //$NON-NLS-1$
6537
    case 538 : if (DEBUG) { System.out.println("EnhancedForStatement ::= EnhancedForStatementHeader..."); }  //$NON-NLS-1$
6531
		    consumeEnhancedForStatement();  
6538
		    consumeEnhancedForStatement();  
6532
			break;
6539
			break;
6533
 
6540
 
6534
    case 539 : if (DEBUG) { System.out.println("EnhancedForStatementHeaderInit ::= for LPAREN Type..."); }  //$NON-NLS-1$
6541
    case 539 : if (DEBUG) { System.out.println("EnhancedForStatementNoShortIf ::=..."); }  //$NON-NLS-1$
6535
		    consumeEnhancedForStatementHeaderInit(false);  
6542
		    consumeEnhancedForStatement();  
6536
			break;
6543
			break;
6537
 
6544
 
6538
    case 540 : if (DEBUG) { System.out.println("EnhancedForStatementHeaderInit ::= for LPAREN Modifiers"); }  //$NON-NLS-1$
6545
    case 540 : if (DEBUG) { System.out.println("EnhancedForStatementHeaderInit ::= for LPAREN Type..."); }  //$NON-NLS-1$
6539
		    consumeEnhancedForStatementHeaderInit(true);  
6546
		    consumeEnhancedForStatementHeaderInit(false);  
6540
			break;
6547
			break;
6541
 
6548
 
6542
    case 541 : if (DEBUG) { System.out.println("EnhancedForStatementHeader ::=..."); }  //$NON-NLS-1$
6549
    case 541 : if (DEBUG) { System.out.println("EnhancedForStatementHeaderInit ::= for LPAREN Modifiers"); }  //$NON-NLS-1$
6543
		    consumeEnhancedForStatementHeader();  
6550
		    consumeEnhancedForStatementHeaderInit(true);  
6544
			break;
6551
			break;
6545
 
6552
 
6546
    case 542 : if (DEBUG) { System.out.println("SingleStaticImportDeclaration ::=..."); }  //$NON-NLS-1$
6553
    case 542 : if (DEBUG) { System.out.println("EnhancedForStatementHeader ::=..."); }  //$NON-NLS-1$
6547
		    consumeImportDeclaration();  
6554
		    consumeEnhancedForStatementHeader();  
6548
			break;
6555
			break;
6549
 
6556
 
6550
    case 543 : if (DEBUG) { System.out.println("SingleStaticImportDeclarationName ::= import static Name"); }  //$NON-NLS-1$
6557
    case 543 : if (DEBUG) { System.out.println("SingleStaticImportDeclaration ::=..."); }  //$NON-NLS-1$
6551
		    consumeSingleStaticImportDeclarationName();  
6558
		    consumeImportDeclaration();  
6552
			break;
6559
			break;
6553
 
6560
 
6554
    case 544 : if (DEBUG) { System.out.println("StaticImportOnDemandDeclaration ::=..."); }  //$NON-NLS-1$
6561
    case 544 : if (DEBUG) { System.out.println("SingleStaticImportDeclarationName ::= import static Name"); }  //$NON-NLS-1$
6555
		    consumeImportDeclaration();  
6562
		    consumeSingleStaticImportDeclarationName();  
6556
			break;
6563
			break;
6557
 
6564
 
6558
    case 545 : if (DEBUG) { System.out.println("StaticImportOnDemandDeclarationName ::= import static..."); }  //$NON-NLS-1$
6565
    case 545 : if (DEBUG) { System.out.println("StaticImportOnDemandDeclaration ::=..."); }  //$NON-NLS-1$
6559
		    consumeStaticImportOnDemandDeclarationName();  
6566
		    consumeImportDeclaration();  
6560
			break;
6567
			break;
6561
 
6568
 
6562
    case 546 : if (DEBUG) { System.out.println("TypeArguments ::= LESS TypeArgumentList1"); }  //$NON-NLS-1$
6569
    case 546 : if (DEBUG) { System.out.println("StaticImportOnDemandDeclarationName ::= import static..."); }  //$NON-NLS-1$
6563
		    consumeTypeArguments();  
6570
		    consumeStaticImportOnDemandDeclarationName();  
6564
			break;
6571
			break;
6565
 
6572
 
6566
    case 547 : if (DEBUG) { System.out.println("OnlyTypeArguments ::= LESS TypeArgumentList1"); }  //$NON-NLS-1$
6573
    case 547 : if (DEBUG) { System.out.println("TypeArguments ::= LESS TypeArgumentList1"); }  //$NON-NLS-1$
6567
		    consumeOnlyTypeArguments();  
6574
		    consumeTypeArguments();  
6568
			break;
6575
			break;
6569
 
6576
 
6570
    case 549 : if (DEBUG) { System.out.println("TypeArgumentList1 ::= TypeArgumentList COMMA..."); }  //$NON-NLS-1$
6577
    case 548 : if (DEBUG) { System.out.println("OnlyTypeArguments ::= LESS TypeArgumentList1"); }  //$NON-NLS-1$
6571
		    consumeTypeArgumentList1();  
6578
		    consumeOnlyTypeArguments();  
6572
			break;
6579
			break;
6573
 
6580
 
6574
    case 551 : if (DEBUG) { System.out.println("TypeArgumentList ::= TypeArgumentList COMMA TypeArgument"); }  //$NON-NLS-1$
6581
    case 550 : if (DEBUG) { System.out.println("TypeArgumentList1 ::= TypeArgumentList COMMA..."); }  //$NON-NLS-1$
6575
		    consumeTypeArgumentList();  
6582
		    consumeTypeArgumentList1();  
6576
			break;
6583
			break;
6577
 
6584
 
6578
    case 552 : if (DEBUG) { System.out.println("TypeArgument ::= ReferenceType"); }  //$NON-NLS-1$
6585
    case 552 : if (DEBUG) { System.out.println("TypeArgumentList ::= TypeArgumentList COMMA TypeArgument"); }  //$NON-NLS-1$
6579
		    consumeTypeArgument();  
6586
		    consumeTypeArgumentList();  
6580
			break;
6587
			break;
6581
 
6588
 
6582
    case 556 : if (DEBUG) { System.out.println("ReferenceType1 ::= ReferenceType GREATER"); }  //$NON-NLS-1$
6589
    case 553 : if (DEBUG) { System.out.println("TypeArgument ::= ReferenceType"); }  //$NON-NLS-1$
6583
		    consumeReferenceType1();  
6590
		    consumeTypeArgument();  
6584
			break;
6591
			break;
6585
 
6592
 
6586
    case 557 : if (DEBUG) { System.out.println("ReferenceType1 ::= ClassOrInterface LESS..."); }  //$NON-NLS-1$
6593
    case 557 : if (DEBUG) { System.out.println("ReferenceType1 ::= ReferenceType GREATER"); }  //$NON-NLS-1$
6587
		    consumeTypeArgumentReferenceType1();  
6594
		    consumeReferenceType1();  
6588
			break;
6595
			break;
6589
 
6596
 
6590
    case 559 : if (DEBUG) { System.out.println("TypeArgumentList2 ::= TypeArgumentList COMMA..."); }  //$NON-NLS-1$
6597
    case 558 : if (DEBUG) { System.out.println("ReferenceType1 ::= ClassOrInterface LESS..."); }  //$NON-NLS-1$
6591
		    consumeTypeArgumentList2();  
6598
		    consumeTypeArgumentReferenceType1();  
6592
			break;
6599
			break;
6593
 
6600
 
6594
    case 562 : if (DEBUG) { System.out.println("ReferenceType2 ::= ReferenceType RIGHT_SHIFT"); }  //$NON-NLS-1$
6601
    case 560 : if (DEBUG) { System.out.println("TypeArgumentList2 ::= TypeArgumentList COMMA..."); }  //$NON-NLS-1$
6595
		    consumeReferenceType2();  
6602
		    consumeTypeArgumentList2();  
6596
			break;
6603
			break;
6597
 
6604
 
6598
    case 563 : if (DEBUG) { System.out.println("ReferenceType2 ::= ClassOrInterface LESS..."); }  //$NON-NLS-1$
6605
    case 563 : if (DEBUG) { System.out.println("ReferenceType2 ::= ReferenceType RIGHT_SHIFT"); }  //$NON-NLS-1$
6599
		    consumeTypeArgumentReferenceType2();  
6606
		    consumeReferenceType2();  
6600
			break;
6607
			break;
6601
 
6608
 
6602
    case 565 : if (DEBUG) { System.out.println("TypeArgumentList3 ::= TypeArgumentList COMMA..."); }  //$NON-NLS-1$
6609
    case 564 : if (DEBUG) { System.out.println("ReferenceType2 ::= ClassOrInterface LESS..."); }  //$NON-NLS-1$
6603
		    consumeTypeArgumentList3();  
6610
		    consumeTypeArgumentReferenceType2();  
6604
			break;
6611
			break;
6605
 
6612
 
6606
    case 568 : if (DEBUG) { System.out.println("ReferenceType3 ::= ReferenceType UNSIGNED_RIGHT_SHIFT"); }  //$NON-NLS-1$
6613
    case 566 : if (DEBUG) { System.out.println("TypeArgumentList3 ::= TypeArgumentList COMMA..."); }  //$NON-NLS-1$
6607
		    consumeReferenceType3();  
6614
		    consumeTypeArgumentList3();  
6608
			break;
6615
			break;
6609
 
6616
 
6610
    case 569 : if (DEBUG) { System.out.println("Wildcard ::= QUESTION"); }  //$NON-NLS-1$
6617
    case 569 : if (DEBUG) { System.out.println("ReferenceType3 ::= ReferenceType UNSIGNED_RIGHT_SHIFT"); }  //$NON-NLS-1$
6611
		    consumeWildcard();  
6618
		    consumeReferenceType3();  
6612
			break;
6619
			break;
6613
 
6620
 
6614
    case 570 : if (DEBUG) { System.out.println("Wildcard ::= QUESTION WildcardBounds"); }  //$NON-NLS-1$
6621
    case 570 : if (DEBUG) { System.out.println("Wildcard ::= QUESTION"); }  //$NON-NLS-1$
6615
		    consumeWildcardWithBounds();  
6622
		    consumeWildcard();  
6616
			break;
6623
			break;
6617
 
6624
 
6618
    case 571 : if (DEBUG) { System.out.println("WildcardBounds ::= extends ReferenceType"); }  //$NON-NLS-1$
6625
    case 571 : if (DEBUG) { System.out.println("Wildcard ::= QUESTION WildcardBounds"); }  //$NON-NLS-1$
6619
		    consumeWildcardBoundsExtends();  
6626
		    consumeWildcardWithBounds();  
6620
			break;
6627
			break;
6621
 
6628
 
6622
    case 572 : if (DEBUG) { System.out.println("WildcardBounds ::= super ReferenceType"); }  //$NON-NLS-1$
6629
    case 572 : if (DEBUG) { System.out.println("WildcardBounds ::= extends ReferenceType"); }  //$NON-NLS-1$
6623
		    consumeWildcardBoundsSuper();  
6630
		    consumeWildcardBoundsExtends();  
6624
			break;
6631
			break;
6625
 
6632
 
6626
    case 573 : if (DEBUG) { System.out.println("Wildcard1 ::= QUESTION GREATER"); }  //$NON-NLS-1$
6633
    case 573 : if (DEBUG) { System.out.println("WildcardBounds ::= super ReferenceType"); }  //$NON-NLS-1$
6627
		    consumeWildcard1();  
6634
		    consumeWildcardBoundsSuper();  
6628
			break;
6635
			break;
6629
 
6636
 
6630
    case 574 : if (DEBUG) { System.out.println("Wildcard1 ::= QUESTION WildcardBounds1"); }  //$NON-NLS-1$
6637
    case 574 : if (DEBUG) { System.out.println("Wildcard1 ::= QUESTION GREATER"); }  //$NON-NLS-1$
6631
		    consumeWildcard1WithBounds();  
6638
		    consumeWildcard1();  
6632
			break;
6639
			break;
6633
 
6640
 
6634
    case 575 : if (DEBUG) { System.out.println("WildcardBounds1 ::= extends ReferenceType1"); }  //$NON-NLS-1$
6641
    case 575 : if (DEBUG) { System.out.println("Wildcard1 ::= QUESTION WildcardBounds1"); }  //$NON-NLS-1$
6635
		    consumeWildcardBounds1Extends();  
6642
		    consumeWildcard1WithBounds();  
6636
			break;
6643
			break;
6637
 
6644
 
6638
    case 576 : if (DEBUG) { System.out.println("WildcardBounds1 ::= super ReferenceType1"); }  //$NON-NLS-1$
6645
    case 576 : if (DEBUG) { System.out.println("WildcardBounds1 ::= extends ReferenceType1"); }  //$NON-NLS-1$
6639
		    consumeWildcardBounds1Super();  
6646
		    consumeWildcardBounds1Extends();  
6640
			break;
6647
			break;
6641
 
6648
 
6642
    case 577 : if (DEBUG) { System.out.println("Wildcard2 ::= QUESTION RIGHT_SHIFT"); }  //$NON-NLS-1$
6649
    case 577 : if (DEBUG) { System.out.println("WildcardBounds1 ::= super ReferenceType1"); }  //$NON-NLS-1$
6643
		    consumeWildcard2();  
6650
		    consumeWildcardBounds1Super();  
6644
			break;
6651
			break;
6645
 
6652
 
6646
    case 578 : if (DEBUG) { System.out.println("Wildcard2 ::= QUESTION WildcardBounds2"); }  //$NON-NLS-1$
6653
    case 578 : if (DEBUG) { System.out.println("Wildcard2 ::= QUESTION RIGHT_SHIFT"); }  //$NON-NLS-1$
6647
		    consumeWildcard2WithBounds();  
6654
		    consumeWildcard2();  
6648
			break;
6655
			break;
6649
 
6656
 
6650
    case 579 : if (DEBUG) { System.out.println("WildcardBounds2 ::= extends ReferenceType2"); }  //$NON-NLS-1$
6657
    case 579 : if (DEBUG) { System.out.println("Wildcard2 ::= QUESTION WildcardBounds2"); }  //$NON-NLS-1$
6651
		    consumeWildcardBounds2Extends();  
6658
		    consumeWildcard2WithBounds();  
6652
			break;
6659
			break;
6653
 
6660
 
6654
    case 580 : if (DEBUG) { System.out.println("WildcardBounds2 ::= super ReferenceType2"); }  //$NON-NLS-1$
6661
    case 580 : if (DEBUG) { System.out.println("WildcardBounds2 ::= extends ReferenceType2"); }  //$NON-NLS-1$
6655
		    consumeWildcardBounds2Super();  
6662
		    consumeWildcardBounds2Extends();  
6656
			break;
6663
			break;
6657
 
6664
 
6658
    case 581 : if (DEBUG) { System.out.println("Wildcard3 ::= QUESTION UNSIGNED_RIGHT_SHIFT"); }  //$NON-NLS-1$
6665
    case 581 : if (DEBUG) { System.out.println("WildcardBounds2 ::= super ReferenceType2"); }  //$NON-NLS-1$
6659
		    consumeWildcard3();  
6666
		    consumeWildcardBounds2Super();  
6660
			break;
6667
			break;
6661
 
6668
 
6662
    case 582 : if (DEBUG) { System.out.println("Wildcard3 ::= QUESTION WildcardBounds3"); }  //$NON-NLS-1$
6669
    case 582 : if (DEBUG) { System.out.println("Wildcard3 ::= QUESTION UNSIGNED_RIGHT_SHIFT"); }  //$NON-NLS-1$
6663
		    consumeWildcard3WithBounds();  
6670
		    consumeWildcard3();  
6664
			break;
6671
			break;
6665
 
6672
 
6666
    case 583 : if (DEBUG) { System.out.println("WildcardBounds3 ::= extends ReferenceType3"); }  //$NON-NLS-1$
6673
    case 583 : if (DEBUG) { System.out.println("Wildcard3 ::= QUESTION WildcardBounds3"); }  //$NON-NLS-1$
6667
		    consumeWildcardBounds3Extends();  
6674
		    consumeWildcard3WithBounds();  
6668
			break;
6675
			break;
6669
 
6676
 
6670
    case 584 : if (DEBUG) { System.out.println("WildcardBounds3 ::= super ReferenceType3"); }  //$NON-NLS-1$
6677
    case 584 : if (DEBUG) { System.out.println("WildcardBounds3 ::= extends ReferenceType3"); }  //$NON-NLS-1$
6671
		    consumeWildcardBounds3Super();  
6678
		    consumeWildcardBounds3Extends();  
6672
			break;
6679
			break;
6673
 
6680
 
6674
    case 585 : if (DEBUG) { System.out.println("TypeParameterHeader ::= Identifier"); }  //$NON-NLS-1$
6681
    case 585 : if (DEBUG) { System.out.println("WildcardBounds3 ::= super ReferenceType3"); }  //$NON-NLS-1$
6675
		    consumeTypeParameterHeader();  
6682
		    consumeWildcardBounds3Super();  
6676
			break;
6683
			break;
6677
 
6684
 
6678
    case 586 : if (DEBUG) { System.out.println("TypeParameters ::= LESS TypeParameterList1"); }  //$NON-NLS-1$
6685
    case 586 : if (DEBUG) { System.out.println("TypeParameterHeader ::= Identifier"); }  //$NON-NLS-1$
6679
		    consumeTypeParameters();  
6686
		    consumeTypeParameterHeader();  
6680
			break;
6687
			break;
6681
 
6688
 
6682
    case 588 : if (DEBUG) { System.out.println("TypeParameterList ::= TypeParameterList COMMA..."); }  //$NON-NLS-1$
6689
    case 587 : if (DEBUG) { System.out.println("TypeParameters ::= LESS TypeParameterList1"); }  //$NON-NLS-1$
6683
		    consumeTypeParameterList();  
6690
		    consumeTypeParameters();  
6684
			break;
6691
			break;
6685
 
6692
 
6686
    case 590 : if (DEBUG) { System.out.println("TypeParameter ::= TypeParameterHeader extends..."); }  //$NON-NLS-1$
6693
    case 589 : if (DEBUG) { System.out.println("TypeParameterList ::= TypeParameterList COMMA..."); }  //$NON-NLS-1$
6687
		    consumeTypeParameterWithExtends();  
6694
		    consumeTypeParameterList();  
6688
			break;
6695
			break;
6689
 
6696
 
6690
    case 591 : if (DEBUG) { System.out.println("TypeParameter ::= TypeParameterHeader extends..."); }  //$NON-NLS-1$
6697
    case 591 : if (DEBUG) { System.out.println("TypeParameter ::= TypeParameterHeader extends..."); }  //$NON-NLS-1$
6691
		    consumeTypeParameterWithExtendsAndBounds();  
6698
		    consumeTypeParameterWithExtends();  
6692
			break;
6699
			break;
6693
 
6700
 
6694
    case 593 : if (DEBUG) { System.out.println("AdditionalBoundList ::= AdditionalBoundList..."); }  //$NON-NLS-1$
6701
    case 592 : if (DEBUG) { System.out.println("TypeParameter ::= TypeParameterHeader extends..."); }  //$NON-NLS-1$
6695
		    consumeAdditionalBoundList();  
6702
		    consumeTypeParameterWithExtendsAndBounds();  
6696
			break;
6703
			break;
6697
 
6704
 
6698
    case 594 : if (DEBUG) { System.out.println("AdditionalBound ::= AND ReferenceType"); }  //$NON-NLS-1$
6705
    case 594 : if (DEBUG) { System.out.println("AdditionalBoundList ::= AdditionalBoundList..."); }  //$NON-NLS-1$
6699
		    consumeAdditionalBound();  
6706
		    consumeAdditionalBoundList();  
6700
			break;
6707
			break;
6701
 
6708
 
6702
    case 596 : if (DEBUG) { System.out.println("TypeParameterList1 ::= TypeParameterList COMMA..."); }  //$NON-NLS-1$
6709
    case 595 : if (DEBUG) { System.out.println("AdditionalBound ::= AND ReferenceType"); }  //$NON-NLS-1$
6703
		    consumeTypeParameterList1();  
6710
		    consumeAdditionalBound();  
6704
			break;
6711
			break;
6705
 
6712
 
6706
    case 597 : if (DEBUG) { System.out.println("TypeParameter1 ::= TypeParameterHeader GREATER"); }  //$NON-NLS-1$
6713
    case 597 : if (DEBUG) { System.out.println("TypeParameterList1 ::= TypeParameterList COMMA..."); }  //$NON-NLS-1$
6707
		    consumeTypeParameter1();  
6714
		    consumeTypeParameterList1();  
6708
			break;
6715
			break;
6709
 
6716
 
6710
    case 598 : if (DEBUG) { System.out.println("TypeParameter1 ::= TypeParameterHeader extends..."); }  //$NON-NLS-1$
6717
    case 598 : if (DEBUG) { System.out.println("TypeParameter1 ::= TypeParameterHeader GREATER"); }  //$NON-NLS-1$
6711
		    consumeTypeParameter1WithExtends();  
6718
		    consumeTypeParameter1();  
6712
			break;
6719
			break;
6713
 
6720
 
6714
    case 599 : if (DEBUG) { System.out.println("TypeParameter1 ::= TypeParameterHeader extends..."); }  //$NON-NLS-1$
6721
    case 599 : if (DEBUG) { System.out.println("TypeParameter1 ::= TypeParameterHeader extends..."); }  //$NON-NLS-1$
6715
		    consumeTypeParameter1WithExtendsAndBounds();  
6722
		    consumeTypeParameter1WithExtends();  
6716
			break;
6723
			break;
6717
 
6724
 
6718
    case 601 : if (DEBUG) { System.out.println("AdditionalBoundList1 ::= AdditionalBoundList..."); }  //$NON-NLS-1$
6725
    case 600 : if (DEBUG) { System.out.println("TypeParameter1 ::= TypeParameterHeader extends..."); }  //$NON-NLS-1$
6719
		    consumeAdditionalBoundList1();  
6726
		    consumeTypeParameter1WithExtendsAndBounds();  
6720
			break;
6727
			break;
6721
 
6728
 
6722
    case 602 : if (DEBUG) { System.out.println("AdditionalBound1 ::= AND ReferenceType1"); }  //$NON-NLS-1$
6729
    case 602 : if (DEBUG) { System.out.println("AdditionalBoundList1 ::= AdditionalBoundList..."); }  //$NON-NLS-1$
6723
		    consumeAdditionalBound1();  
6730
		    consumeAdditionalBoundList1();  
6724
			break;
6731
			break;
6725
 
6732
 
6726
    case 608 : if (DEBUG) { System.out.println("UnaryExpression_NotName ::= PLUS PushPosition..."); }  //$NON-NLS-1$
6733
    case 603 : if (DEBUG) { System.out.println("AdditionalBound1 ::= AND ReferenceType1"); }  //$NON-NLS-1$
6727
		    consumeUnaryExpression(OperatorIds.PLUS);  
6734
		    consumeAdditionalBound1();  
6728
			break;
6735
			break;
6729
 
6736
 
6730
    case 609 : if (DEBUG) { System.out.println("UnaryExpression_NotName ::= MINUS PushPosition..."); }  //$NON-NLS-1$
6737
    case 609 : if (DEBUG) { System.out.println("UnaryExpression_NotName ::= PLUS PushPosition..."); }  //$NON-NLS-1$
6731
		    consumeUnaryExpression(OperatorIds.MINUS);  
6738
		    consumeUnaryExpression(OperatorIds.PLUS);  
6732
			break;
6739
			break;
6733
 
6740
 
6734
    case 612 : if (DEBUG) { System.out.println("UnaryExpressionNotPlusMinus_NotName ::= TWIDDLE..."); }  //$NON-NLS-1$
6741
    case 610 : if (DEBUG) { System.out.println("UnaryExpression_NotName ::= MINUS PushPosition..."); }  //$NON-NLS-1$
6735
		    consumeUnaryExpression(OperatorIds.TWIDDLE);  
6742
		    consumeUnaryExpression(OperatorIds.MINUS);  
6736
			break;
6743
			break;
6737
 
6744
 
6738
    case 613 : if (DEBUG) { System.out.println("UnaryExpressionNotPlusMinus_NotName ::= NOT PushPosition"); }  //$NON-NLS-1$
6745
    case 613 : if (DEBUG) { System.out.println("UnaryExpressionNotPlusMinus_NotName ::= TWIDDLE..."); }  //$NON-NLS-1$
6739
		    consumeUnaryExpression(OperatorIds.NOT);  
6746
		    consumeUnaryExpression(OperatorIds.TWIDDLE);  
6740
			break;
6747
			break;
6741
 
6748
 
6742
    case 616 : if (DEBUG) { System.out.println("MultiplicativeExpression_NotName ::=..."); }  //$NON-NLS-1$
6749
    case 614 : if (DEBUG) { System.out.println("UnaryExpressionNotPlusMinus_NotName ::= NOT PushPosition"); }  //$NON-NLS-1$
6743
		    consumeBinaryExpression(OperatorIds.MULTIPLY);  
6750
		    consumeUnaryExpression(OperatorIds.NOT);  
6744
			break;
6751
			break;
6745
 
6752
 
6746
    case 617 : if (DEBUG) { System.out.println("MultiplicativeExpression_NotName ::= Name MULTIPLY..."); }  //$NON-NLS-1$
6753
    case 617 : if (DEBUG) { System.out.println("MultiplicativeExpression_NotName ::=..."); }  //$NON-NLS-1$
6747
		    consumeBinaryExpressionWithName(OperatorIds.MULTIPLY);  
6754
		    consumeBinaryExpression(OperatorIds.MULTIPLY);  
6748
			break;
6755
			break;
6749
 
6756
 
6750
    case 618 : if (DEBUG) { System.out.println("MultiplicativeExpression_NotName ::=..."); }  //$NON-NLS-1$
6757
    case 618 : if (DEBUG) { System.out.println("MultiplicativeExpression_NotName ::= Name MULTIPLY..."); }  //$NON-NLS-1$
6751
		    consumeBinaryExpression(OperatorIds.DIVIDE);  
6758
		    consumeBinaryExpressionWithName(OperatorIds.MULTIPLY);  
6752
			break;
6759
			break;
6753
 
6760
 
6754
    case 619 : if (DEBUG) { System.out.println("MultiplicativeExpression_NotName ::= Name DIVIDE..."); }  //$NON-NLS-1$
6761
    case 619 : if (DEBUG) { System.out.println("MultiplicativeExpression_NotName ::=..."); }  //$NON-NLS-1$
6755
		    consumeBinaryExpressionWithName(OperatorIds.DIVIDE);  
6762
		    consumeBinaryExpression(OperatorIds.DIVIDE);  
6756
			break;
6763
			break;
6757
 
6764
 
6758
    case 620 : if (DEBUG) { System.out.println("MultiplicativeExpression_NotName ::=..."); }  //$NON-NLS-1$
6765
    case 620 : if (DEBUG) { System.out.println("MultiplicativeExpression_NotName ::= Name DIVIDE..."); }  //$NON-NLS-1$
6759
		    consumeBinaryExpression(OperatorIds.REMAINDER);  
6766
		    consumeBinaryExpressionWithName(OperatorIds.DIVIDE);  
6760
			break;
6767
			break;
6761
 
6768
 
6762
    case 621 : if (DEBUG) { System.out.println("MultiplicativeExpression_NotName ::= Name REMAINDER..."); }  //$NON-NLS-1$
6769
    case 621 : if (DEBUG) { System.out.println("MultiplicativeExpression_NotName ::=..."); }  //$NON-NLS-1$
6763
		    consumeBinaryExpressionWithName(OperatorIds.REMAINDER);  
6770
		    consumeBinaryExpression(OperatorIds.REMAINDER);  
6764
			break;
6771
			break;
6765
 
6772
 
6766
    case 623 : if (DEBUG) { System.out.println("AdditiveExpression_NotName ::=..."); }  //$NON-NLS-1$
6773
    case 622 : if (DEBUG) { System.out.println("MultiplicativeExpression_NotName ::= Name REMAINDER..."); }  //$NON-NLS-1$
6767
		    consumeBinaryExpression(OperatorIds.PLUS);  
6774
		    consumeBinaryExpressionWithName(OperatorIds.REMAINDER);  
6768
			break;
6775
			break;
6769
 
6776
 
6770
    case 624 : if (DEBUG) { System.out.println("AdditiveExpression_NotName ::= Name PLUS..."); }  //$NON-NLS-1$
6777
    case 624 : if (DEBUG) { System.out.println("AdditiveExpression_NotName ::=..."); }  //$NON-NLS-1$
6771
		    consumeBinaryExpressionWithName(OperatorIds.PLUS);  
6778
		    consumeBinaryExpression(OperatorIds.PLUS);  
6772
			break;
6779
			break;
6773
 
6780
 
6774
    case 625 : if (DEBUG) { System.out.println("AdditiveExpression_NotName ::=..."); }  //$NON-NLS-1$
6781
    case 625 : if (DEBUG) { System.out.println("AdditiveExpression_NotName ::= Name PLUS..."); }  //$NON-NLS-1$
6775
		    consumeBinaryExpression(OperatorIds.MINUS);  
6782
		    consumeBinaryExpressionWithName(OperatorIds.PLUS);  
6776
			break;
6783
			break;
6777
 
6784
 
6778
    case 626 : if (DEBUG) { System.out.println("AdditiveExpression_NotName ::= Name MINUS..."); }  //$NON-NLS-1$
6785
    case 626 : if (DEBUG) { System.out.println("AdditiveExpression_NotName ::=..."); }  //$NON-NLS-1$
6779
		    consumeBinaryExpressionWithName(OperatorIds.MINUS);  
6786
		    consumeBinaryExpression(OperatorIds.MINUS);  
6780
			break;
6787
			break;
6781
 
6788
 
6782
    case 628 : if (DEBUG) { System.out.println("ShiftExpression_NotName ::= ShiftExpression_NotName..."); }  //$NON-NLS-1$
6789
    case 627 : if (DEBUG) { System.out.println("AdditiveExpression_NotName ::= Name MINUS..."); }  //$NON-NLS-1$
6783
		    consumeBinaryExpression(OperatorIds.LEFT_SHIFT);  
6790
		    consumeBinaryExpressionWithName(OperatorIds.MINUS);  
6784
			break;
6791
			break;
6785
 
6792
 
6786
    case 629 : if (DEBUG) { System.out.println("ShiftExpression_NotName ::= Name LEFT_SHIFT..."); }  //$NON-NLS-1$
6793
    case 629 : if (DEBUG) { System.out.println("ShiftExpression_NotName ::= ShiftExpression_NotName..."); }  //$NON-NLS-1$
6787
		    consumeBinaryExpressionWithName(OperatorIds.LEFT_SHIFT);  
6794
		    consumeBinaryExpression(OperatorIds.LEFT_SHIFT);  
6788
			break;
6795
			break;
6789
 
6796
 
6790
    case 630 : if (DEBUG) { System.out.println("ShiftExpression_NotName ::= ShiftExpression_NotName..."); }  //$NON-NLS-1$
6797
    case 630 : if (DEBUG) { System.out.println("ShiftExpression_NotName ::= Name LEFT_SHIFT..."); }  //$NON-NLS-1$
6791
		    consumeBinaryExpression(OperatorIds.RIGHT_SHIFT);  
6798
		    consumeBinaryExpressionWithName(OperatorIds.LEFT_SHIFT);  
6792
			break;
6799
			break;
6793
 
6800
 
6794
    case 631 : if (DEBUG) { System.out.println("ShiftExpression_NotName ::= Name RIGHT_SHIFT..."); }  //$NON-NLS-1$
6801
    case 631 : if (DEBUG) { System.out.println("ShiftExpression_NotName ::= ShiftExpression_NotName..."); }  //$NON-NLS-1$
6795
		    consumeBinaryExpressionWithName(OperatorIds.RIGHT_SHIFT);  
6802
		    consumeBinaryExpression(OperatorIds.RIGHT_SHIFT);  
6796
			break;
6803
			break;
6797
 
6804
 
6798
    case 632 : if (DEBUG) { System.out.println("ShiftExpression_NotName ::= ShiftExpression_NotName..."); }  //$NON-NLS-1$
6805
    case 632 : if (DEBUG) { System.out.println("ShiftExpression_NotName ::= Name RIGHT_SHIFT..."); }  //$NON-NLS-1$
6799
		    consumeBinaryExpression(OperatorIds.UNSIGNED_RIGHT_SHIFT);  
6806
		    consumeBinaryExpressionWithName(OperatorIds.RIGHT_SHIFT);  
6800
			break;
6807
			break;
6801
 
6808
 
6802
    case 633 : if (DEBUG) { System.out.println("ShiftExpression_NotName ::= Name UNSIGNED_RIGHT_SHIFT..."); }  //$NON-NLS-1$
6809
    case 633 : if (DEBUG) { System.out.println("ShiftExpression_NotName ::= ShiftExpression_NotName..."); }  //$NON-NLS-1$
6803
		    consumeBinaryExpressionWithName(OperatorIds.UNSIGNED_RIGHT_SHIFT);  
6810
		    consumeBinaryExpression(OperatorIds.UNSIGNED_RIGHT_SHIFT);  
6804
			break;
6811
			break;
6805
 
6812
 
6806
    case 635 : if (DEBUG) { System.out.println("RelationalExpression_NotName ::= ShiftExpression_NotName"); }  //$NON-NLS-1$
6813
    case 634 : if (DEBUG) { System.out.println("ShiftExpression_NotName ::= Name UNSIGNED_RIGHT_SHIFT..."); }  //$NON-NLS-1$
6807
		    consumeBinaryExpression(OperatorIds.LESS);  
6814
		    consumeBinaryExpressionWithName(OperatorIds.UNSIGNED_RIGHT_SHIFT);  
6808
			break;
6815
			break;
6809
 
6816
 
6810
    case 636 : if (DEBUG) { System.out.println("RelationalExpression_NotName ::= Name LESS..."); }  //$NON-NLS-1$
6817
    case 636 : if (DEBUG) { System.out.println("RelationalExpression_NotName ::= ShiftExpression_NotName"); }  //$NON-NLS-1$
6811
		    consumeBinaryExpressionWithName(OperatorIds.LESS);  
6818
		    consumeBinaryExpression(OperatorIds.LESS);  
6812
			break;
6819
			break;
6813
 
6820
 
6814
    case 637 : if (DEBUG) { System.out.println("RelationalExpression_NotName ::= ShiftExpression_NotName"); }  //$NON-NLS-1$
6821
    case 637 : if (DEBUG) { System.out.println("RelationalExpression_NotName ::= Name LESS..."); }  //$NON-NLS-1$
6815
		    consumeBinaryExpression(OperatorIds.GREATER);  
6822
		    consumeBinaryExpressionWithName(OperatorIds.LESS);  
6816
			break;
6823
			break;
6817
 
6824
 
6818
    case 638 : if (DEBUG) { System.out.println("RelationalExpression_NotName ::= Name GREATER..."); }  //$NON-NLS-1$
6825
    case 638 : if (DEBUG) { System.out.println("RelationalExpression_NotName ::= ShiftExpression_NotName"); }  //$NON-NLS-1$
6819
		    consumeBinaryExpressionWithName(OperatorIds.GREATER);  
6826
		    consumeBinaryExpression(OperatorIds.GREATER);  
6820
			break;
6827
			break;
6821
 
6828
 
6822
    case 639 : if (DEBUG) { System.out.println("RelationalExpression_NotName ::=..."); }  //$NON-NLS-1$
6829
    case 639 : if (DEBUG) { System.out.println("RelationalExpression_NotName ::= Name GREATER..."); }  //$NON-NLS-1$
6823
		    consumeBinaryExpression(OperatorIds.LESS_EQUAL);  
6830
		    consumeBinaryExpressionWithName(OperatorIds.GREATER);  
6824
			break;
6831
			break;
6825
 
6832
 
6826
    case 640 : if (DEBUG) { System.out.println("RelationalExpression_NotName ::= Name LESS_EQUAL..."); }  //$NON-NLS-1$
6833
    case 640 : if (DEBUG) { System.out.println("RelationalExpression_NotName ::=..."); }  //$NON-NLS-1$
6827
		    consumeBinaryExpressionWithName(OperatorIds.LESS_EQUAL);  
6834
		    consumeBinaryExpression(OperatorIds.LESS_EQUAL);  
6828
			break;
6835
			break;
6829
 
6836
 
6830
    case 641 : if (DEBUG) { System.out.println("RelationalExpression_NotName ::=..."); }  //$NON-NLS-1$
6837
    case 641 : if (DEBUG) { System.out.println("RelationalExpression_NotName ::= Name LESS_EQUAL..."); }  //$NON-NLS-1$
6831
		    consumeBinaryExpression(OperatorIds.GREATER_EQUAL);  
6838
		    consumeBinaryExpressionWithName(OperatorIds.LESS_EQUAL);  
6832
			break;
6839
			break;
6833
 
6840
 
6834
    case 642 : if (DEBUG) { System.out.println("RelationalExpression_NotName ::= Name GREATER_EQUAL..."); }  //$NON-NLS-1$
6841
    case 642 : if (DEBUG) { System.out.println("RelationalExpression_NotName ::=..."); }  //$NON-NLS-1$
6835
		    consumeBinaryExpressionWithName(OperatorIds.GREATER_EQUAL);  
6842
		    consumeBinaryExpression(OperatorIds.GREATER_EQUAL);  
6836
			break;
6843
			break;
6837
 
6844
 
6838
    case 644 : if (DEBUG) { System.out.println("InstanceofExpression_NotName ::= Name instanceof..."); }  //$NON-NLS-1$
6845
    case 643 : if (DEBUG) { System.out.println("RelationalExpression_NotName ::= Name GREATER_EQUAL..."); }  //$NON-NLS-1$
6839
		    consumeInstanceOfExpressionWithName();  
6846
		    consumeBinaryExpressionWithName(OperatorIds.GREATER_EQUAL);  
6840
			break;
6847
			break;
6841
 
6848
 
6842
    case 645 : if (DEBUG) { System.out.println("InstanceofExpression_NotName ::=..."); }  //$NON-NLS-1$
6849
    case 645 : if (DEBUG) { System.out.println("InstanceofExpression_NotName ::= Name instanceof..."); }  //$NON-NLS-1$
6843
		    consumeInstanceOfExpression();  
6850
		    consumeInstanceOfExpressionWithName();  
6844
			break;
6851
			break;
6845
 
6852
 
6846
    case 647 : if (DEBUG) { System.out.println("EqualityExpression_NotName ::=..."); }  //$NON-NLS-1$
6853
    case 646 : if (DEBUG) { System.out.println("InstanceofExpression_NotName ::=..."); }  //$NON-NLS-1$
6847
		    consumeEqualityExpression(OperatorIds.EQUAL_EQUAL);  
6854
		    consumeInstanceOfExpression();  
6848
			break;
6855
			break;
6849
 
6856
 
6850
    case 648 : if (DEBUG) { System.out.println("EqualityExpression_NotName ::= Name EQUAL_EQUAL..."); }  //$NON-NLS-1$
6857
    case 648 : if (DEBUG) { System.out.println("EqualityExpression_NotName ::=..."); }  //$NON-NLS-1$
6851
		    consumeEqualityExpressionWithName(OperatorIds.EQUAL_EQUAL);  
6858
		    consumeEqualityExpression(OperatorIds.EQUAL_EQUAL);  
6852
			break;
6859
			break;
6853
 
6860
 
6854
    case 649 : if (DEBUG) { System.out.println("EqualityExpression_NotName ::=..."); }  //$NON-NLS-1$
6861
    case 649 : if (DEBUG) { System.out.println("EqualityExpression_NotName ::= Name EQUAL_EQUAL..."); }  //$NON-NLS-1$
6855
		    consumeEqualityExpression(OperatorIds.NOT_EQUAL);  
6862
		    consumeEqualityExpressionWithName(OperatorIds.EQUAL_EQUAL);  
6856
			break;
6863
			break;
6857
 
6864
 
6858
    case 650 : if (DEBUG) { System.out.println("EqualityExpression_NotName ::= Name NOT_EQUAL..."); }  //$NON-NLS-1$
6865
    case 650 : if (DEBUG) { System.out.println("EqualityExpression_NotName ::=..."); }  //$NON-NLS-1$
6859
		    consumeEqualityExpressionWithName(OperatorIds.NOT_EQUAL);  
6866
		    consumeEqualityExpression(OperatorIds.NOT_EQUAL);  
6860
			break;
6867
			break;
6861
 
6868
 
6862
    case 652 : if (DEBUG) { System.out.println("AndExpression_NotName ::= AndExpression_NotName AND..."); }  //$NON-NLS-1$
6869
    case 651 : if (DEBUG) { System.out.println("EqualityExpression_NotName ::= Name NOT_EQUAL..."); }  //$NON-NLS-1$
6863
		    consumeBinaryExpression(OperatorIds.AND);  
6870
		    consumeEqualityExpressionWithName(OperatorIds.NOT_EQUAL);  
6864
			break;
6871
			break;
6865
 
6872
 
6866
    case 653 : if (DEBUG) { System.out.println("AndExpression_NotName ::= Name AND EqualityExpression"); }  //$NON-NLS-1$
6873
    case 653 : if (DEBUG) { System.out.println("AndExpression_NotName ::= AndExpression_NotName AND..."); }  //$NON-NLS-1$
6867
		    consumeBinaryExpressionWithName(OperatorIds.AND);  
6874
		    consumeBinaryExpression(OperatorIds.AND);  
6868
			break;
6875
			break;
6869
 
6876
 
6870
    case 655 : if (DEBUG) { System.out.println("ExclusiveOrExpression_NotName ::=..."); }  //$NON-NLS-1$
6877
    case 654 : if (DEBUG) { System.out.println("AndExpression_NotName ::= Name AND EqualityExpression"); }  //$NON-NLS-1$
6871
		    consumeBinaryExpression(OperatorIds.XOR);  
6878
		    consumeBinaryExpressionWithName(OperatorIds.AND);  
6872
			break;
6879
			break;
6873
 
6880
 
6874
    case 656 : if (DEBUG) { System.out.println("ExclusiveOrExpression_NotName ::= Name XOR AndExpression"); }  //$NON-NLS-1$
6881
    case 656 : if (DEBUG) { System.out.println("ExclusiveOrExpression_NotName ::=..."); }  //$NON-NLS-1$
6875
		    consumeBinaryExpressionWithName(OperatorIds.XOR);  
6882
		    consumeBinaryExpression(OperatorIds.XOR);  
6876
			break;
6883
			break;
6877
 
6884
 
6878
    case 658 : if (DEBUG) { System.out.println("InclusiveOrExpression_NotName ::=..."); }  //$NON-NLS-1$
6885
    case 657 : if (DEBUG) { System.out.println("ExclusiveOrExpression_NotName ::= Name XOR AndExpression"); }  //$NON-NLS-1$
6879
		    consumeBinaryExpression(OperatorIds.OR);  
6886
		    consumeBinaryExpressionWithName(OperatorIds.XOR);  
6880
			break;
6887
			break;
6881
 
6888
 
6882
    case 659 : if (DEBUG) { System.out.println("InclusiveOrExpression_NotName ::= Name OR..."); }  //$NON-NLS-1$
6889
    case 659 : if (DEBUG) { System.out.println("InclusiveOrExpression_NotName ::=..."); }  //$NON-NLS-1$
6883
		    consumeBinaryExpressionWithName(OperatorIds.OR);  
6890
		    consumeBinaryExpression(OperatorIds.OR);  
6884
			break;
6891
			break;
6885
 
6892
 
6886
    case 661 : if (DEBUG) { System.out.println("ConditionalAndExpression_NotName ::=..."); }  //$NON-NLS-1$
6893
    case 660 : if (DEBUG) { System.out.println("InclusiveOrExpression_NotName ::= Name OR..."); }  //$NON-NLS-1$
6887
		    consumeBinaryExpression(OperatorIds.AND_AND);  
6894
		    consumeBinaryExpressionWithName(OperatorIds.OR);  
6888
			break;
6895
			break;
6889
 
6896
 
6890
    case 662 : if (DEBUG) { System.out.println("ConditionalAndExpression_NotName ::= Name AND_AND..."); }  //$NON-NLS-1$
6897
    case 662 : if (DEBUG) { System.out.println("ConditionalAndExpression_NotName ::=..."); }  //$NON-NLS-1$
6891
		    consumeBinaryExpressionWithName(OperatorIds.AND_AND);  
6898
		    consumeBinaryExpression(OperatorIds.AND_AND);  
6892
			break;
6899
			break;
6893
 
6900
 
6894
    case 664 : if (DEBUG) { System.out.println("ConditionalOrExpression_NotName ::=..."); }  //$NON-NLS-1$
6901
    case 663 : if (DEBUG) { System.out.println("ConditionalAndExpression_NotName ::= Name AND_AND..."); }  //$NON-NLS-1$
6895
		    consumeBinaryExpression(OperatorIds.OR_OR);  
6902
		    consumeBinaryExpressionWithName(OperatorIds.AND_AND);  
6896
			break;
6903
			break;
6897
 
6904
 
6898
    case 665 : if (DEBUG) { System.out.println("ConditionalOrExpression_NotName ::= Name OR_OR..."); }  //$NON-NLS-1$
6905
    case 665 : if (DEBUG) { System.out.println("ConditionalOrExpression_NotName ::=..."); }  //$NON-NLS-1$
6899
		    consumeBinaryExpressionWithName(OperatorIds.OR_OR);  
6906
		    consumeBinaryExpression(OperatorIds.OR_OR);  
6900
			break;
6907
			break;
6901
 
6908
 
6902
    case 667 : if (DEBUG) { System.out.println("ConditionalExpression_NotName ::=..."); }  //$NON-NLS-1$
6909
    case 666 : if (DEBUG) { System.out.println("ConditionalOrExpression_NotName ::= Name OR_OR..."); }  //$NON-NLS-1$
6903
		    consumeConditionalExpression(OperatorIds.QUESTIONCOLON) ;  
6910
		    consumeBinaryExpressionWithName(OperatorIds.OR_OR);  
6904
			break;
6911
			break;
6905
 
6912
 
6906
    case 668 : if (DEBUG) { System.out.println("ConditionalExpression_NotName ::= Name QUESTION..."); }  //$NON-NLS-1$
6913
    case 668 : if (DEBUG) { System.out.println("ConditionalExpression_NotName ::=..."); }  //$NON-NLS-1$
6907
		    consumeConditionalExpressionWithName(OperatorIds.QUESTIONCOLON) ;  
6914
		    consumeConditionalExpression(OperatorIds.QUESTIONCOLON) ;  
6908
			break;
6915
			break;
6909
 
6916
 
6910
    case 672 : if (DEBUG) { System.out.println("AnnotationTypeDeclarationHeaderName ::= Modifiers AT..."); }  //$NON-NLS-1$
6917
    case 669 : if (DEBUG) { System.out.println("ConditionalExpression_NotName ::= Name QUESTION..."); }  //$NON-NLS-1$
6911
		    consumeAnnotationTypeDeclarationHeaderName() ;  
6918
		    consumeConditionalExpressionWithName(OperatorIds.QUESTIONCOLON) ;  
6912
			break;
6919
			break;
6913
 
6920
 
6914
    case 673 : if (DEBUG) { System.out.println("AnnotationTypeDeclarationHeaderName ::= Modifiers AT..."); }  //$NON-NLS-1$
6921
    case 673 : if (DEBUG) { System.out.println("AnnotationTypeDeclarationHeaderName ::= Modifiers AT..."); }  //$NON-NLS-1$
6915
		    consumeAnnotationTypeDeclarationHeaderNameWithTypeParameters() ;  
6922
		    consumeAnnotationTypeDeclarationHeaderName() ;  
6916
			break;
6923
			break;
6917
 
6924
 
6918
    case 674 : if (DEBUG) { System.out.println("AnnotationTypeDeclarationHeaderName ::= AT..."); }  //$NON-NLS-1$
6925
    case 674 : if (DEBUG) { System.out.println("AnnotationTypeDeclarationHeaderName ::= Modifiers AT..."); }  //$NON-NLS-1$
6919
		    consumeAnnotationTypeDeclarationHeaderNameWithTypeParameters() ;  
6926
		    consumeAnnotationTypeDeclarationHeaderNameWithTypeParameters() ;  
6920
			break;
6927
			break;
6921
 
6928
 
6922
    case 675 : if (DEBUG) { System.out.println("AnnotationTypeDeclarationHeaderName ::= AT..."); }  //$NON-NLS-1$
6929
    case 675 : if (DEBUG) { System.out.println("AnnotationTypeDeclarationHeaderName ::= AT..."); }  //$NON-NLS-1$
6923
		    consumeAnnotationTypeDeclarationHeaderName() ;  
6930
		    consumeAnnotationTypeDeclarationHeaderNameWithTypeParameters() ;  
6924
			break;
6931
			break;
6925
 
6932
 
6926
    case 676 : if (DEBUG) { System.out.println("AnnotationTypeDeclarationHeader ::=..."); }  //$NON-NLS-1$
6933
    case 676 : if (DEBUG) { System.out.println("AnnotationTypeDeclarationHeaderName ::= AT..."); }  //$NON-NLS-1$
6927
		    consumeAnnotationTypeDeclarationHeader() ;  
6934
		    consumeAnnotationTypeDeclarationHeaderName() ;  
6928
			break;
6935
			break;
6929
 
6936
 
6930
    case 677 : if (DEBUG) { System.out.println("AnnotationTypeDeclaration ::=..."); }  //$NON-NLS-1$
6937
    case 677 : if (DEBUG) { System.out.println("AnnotationTypeDeclarationHeader ::=..."); }  //$NON-NLS-1$
6931
		    consumeAnnotationTypeDeclaration() ;  
6938
		    consumeAnnotationTypeDeclarationHeader() ;  
6932
			break;
6939
			break;
6933
 
6940
 
6934
    case 679 : if (DEBUG) { System.out.println("AnnotationTypeMemberDeclarationsopt ::="); }  //$NON-NLS-1$
6941
    case 678 : if (DEBUG) { System.out.println("AnnotationTypeDeclaration ::=..."); }  //$NON-NLS-1$
6935
		    consumeEmptyAnnotationTypeMemberDeclarationsopt() ;  
6942
		    consumeAnnotationTypeDeclaration() ;  
6936
			break;
6943
			break;
6937
 
6944
 
6938
    case 680 : if (DEBUG) { System.out.println("AnnotationTypeMemberDeclarationsopt ::= NestedType..."); }  //$NON-NLS-1$
6945
    case 680 : if (DEBUG) { System.out.println("AnnotationTypeMemberDeclarationsopt ::="); }  //$NON-NLS-1$
6939
		    consumeAnnotationTypeMemberDeclarationsopt() ;  
6946
		    consumeEmptyAnnotationTypeMemberDeclarationsopt() ;  
6940
			break;
6947
			break;
6941
 
6948
 
6942
    case 682 : if (DEBUG) { System.out.println("AnnotationTypeMemberDeclarations ::=..."); }  //$NON-NLS-1$
6949
    case 681 : if (DEBUG) { System.out.println("AnnotationTypeMemberDeclarationsopt ::= NestedType..."); }  //$NON-NLS-1$
6943
		    consumeAnnotationTypeMemberDeclarations() ;  
6950
		    consumeAnnotationTypeMemberDeclarationsopt() ;  
6944
			break;
6951
			break;
6945
 
6952
 
6946
    case 683 : if (DEBUG) { System.out.println("AnnotationMethodHeaderName ::= Modifiersopt..."); }  //$NON-NLS-1$
6953
    case 683 : if (DEBUG) { System.out.println("AnnotationTypeMemberDeclarations ::=..."); }  //$NON-NLS-1$
6947
		    consumeMethodHeaderNameWithTypeParameters(true);  
6954
		    consumeAnnotationTypeMemberDeclarations() ;  
6948
			break;
6955
			break;
6949
 
6956
 
6950
    case 684 : if (DEBUG) { System.out.println("AnnotationMethodHeaderName ::= Modifiersopt Type..."); }  //$NON-NLS-1$
6957
    case 684 : if (DEBUG) { System.out.println("AnnotationMethodHeaderName ::= Modifiersopt..."); }  //$NON-NLS-1$
6951
		    consumeMethodHeaderName(true);  
6958
		    consumeMethodHeaderNameWithTypeParameters(true);  
6952
			break;
6959
			break;
6953
 
6960
 
6954
    case 685 : if (DEBUG) { System.out.println("AnnotationMethodHeaderDefaultValueopt ::="); }  //$NON-NLS-1$
6961
    case 685 : if (DEBUG) { System.out.println("AnnotationMethodHeaderName ::= Modifiersopt Type..."); }  //$NON-NLS-1$
6955
		    consumeEmptyMethodHeaderDefaultValue() ;  
6962
		    consumeMethodHeaderName(true);  
6956
			break;
6963
			break;
6957
 
6964
 
6958
    case 686 : if (DEBUG) { System.out.println("AnnotationMethodHeaderDefaultValueopt ::= DefaultValue"); }  //$NON-NLS-1$
6965
    case 686 : if (DEBUG) { System.out.println("AnnotationMethodHeaderDefaultValueopt ::="); }  //$NON-NLS-1$
6959
		    consumeMethodHeaderDefaultValue();  
6966
		    consumeEmptyMethodHeaderDefaultValue() ;  
6960
			break;
6967
			break;
6961
 
6968
 
6962
    case 687 : if (DEBUG) { System.out.println("AnnotationMethodHeader ::= AnnotationMethodHeaderName..."); }  //$NON-NLS-1$
6969
    case 687 : if (DEBUG) { System.out.println("AnnotationMethodHeaderDefaultValueopt ::= DefaultValue"); }  //$NON-NLS-1$
6963
		    consumeMethodHeader();  
6970
		    consumeMethodHeaderDefaultValue();  
6964
			break;
6971
			break;
6965
 
6972
 
6966
    case 688 : if (DEBUG) { System.out.println("AnnotationTypeMemberDeclaration ::=..."); }  //$NON-NLS-1$
6973
    case 688 : if (DEBUG) { System.out.println("AnnotationMethodHeader ::= AnnotationMethodHeaderName..."); }  //$NON-NLS-1$
6967
		    consumeAnnotationTypeMemberDeclaration() ;  
6974
		    consumeMethodHeader();  
6968
			break;
6975
			break;
6969
 
6976
 
6970
    case 696 : if (DEBUG) { System.out.println("AnnotationName ::= AT Name"); }  //$NON-NLS-1$
6977
    case 689 : if (DEBUG) { System.out.println("AnnotationTypeMemberDeclaration ::=..."); }  //$NON-NLS-1$
6971
		    consumeAnnotationName() ;  
6978
		    consumeAnnotationTypeMemberDeclaration() ;  
6972
			break;
6979
			break;
6973
 
6980
 
6974
    case 697 : if (DEBUG) { System.out.println("NormalAnnotation ::= AnnotationName LPAREN..."); }  //$NON-NLS-1$
6981
    case 697 : if (DEBUG) { System.out.println("AnnotationName ::= AT Name"); }  //$NON-NLS-1$
6975
		    consumeNormalAnnotation() ;  
6982
		    consumeAnnotationName() ;  
6976
			break;
6983
			break;
6977
 
6984
 
6978
    case 698 : if (DEBUG) { System.out.println("MemberValuePairsopt ::="); }  //$NON-NLS-1$
6985
    case 698 : if (DEBUG) { System.out.println("NormalAnnotation ::= AnnotationName LPAREN..."); }  //$NON-NLS-1$
6979
		    consumeEmptyMemberValuePairsopt() ;  
6986
		    consumeNormalAnnotation() ;  
6980
			break;
6987
			break;
6981
 
6988
 
6982
    case 701 : if (DEBUG) { System.out.println("MemberValuePairs ::= MemberValuePairs COMMA..."); }  //$NON-NLS-1$
6989
    case 699 : if (DEBUG) { System.out.println("MemberValuePairsopt ::="); }  //$NON-NLS-1$
6983
		    consumeMemberValuePairs() ;  
6990
		    consumeEmptyMemberValuePairsopt() ;  
6984
			break;
6991
			break;
6985
 
6992
 
6986
    case 702 : if (DEBUG) { System.out.println("MemberValuePair ::= SimpleName EQUAL EnterMemberValue..."); }  //$NON-NLS-1$
6993
    case 702 : if (DEBUG) { System.out.println("MemberValuePairs ::= MemberValuePairs COMMA..."); }  //$NON-NLS-1$
6987
		    consumeMemberValuePair() ;  
6994
		    consumeMemberValuePairs() ;  
6988
			break;
6995
			break;
6989
 
6996
 
6990
    case 703 : if (DEBUG) { System.out.println("EnterMemberValue ::="); }  //$NON-NLS-1$
6997
    case 703 : if (DEBUG) { System.out.println("MemberValuePair ::= SimpleName EQUAL EnterMemberValue..."); }  //$NON-NLS-1$
6991
		    consumeEnterMemberValue() ;  
6998
		    consumeMemberValuePair() ;  
6992
			break;
6999
			break;
6993
 
7000
 
6994
    case 704 : if (DEBUG) { System.out.println("ExitMemberValue ::="); }  //$NON-NLS-1$
7001
    case 704 : if (DEBUG) { System.out.println("EnterMemberValue ::="); }  //$NON-NLS-1$
6995
		    consumeExitMemberValue() ;  
7002
		    consumeEnterMemberValue() ;  
6996
			break;
7003
			break;
6997
 
7004
 
6998
    case 706 : if (DEBUG) { System.out.println("MemberValue ::= Name"); }  //$NON-NLS-1$
7005
    case 705 : if (DEBUG) { System.out.println("ExitMemberValue ::="); }  //$NON-NLS-1$
6999
		    consumeMemberValueAsName() ;  
7006
		    consumeExitMemberValue() ;  
7000
			break;
7007
			break;
7001
 
7008
 
7002
    case 709 : if (DEBUG) { System.out.println("MemberValueArrayInitializer ::=..."); }  //$NON-NLS-1$
7009
    case 707 : if (DEBUG) { System.out.println("MemberValue ::= Name"); }  //$NON-NLS-1$
7003
		    consumeMemberValueArrayInitializer() ;  
7010
		    consumeMemberValueAsName() ;  
7004
			break;
7011
			break;
7005
 
7012
 
7006
    case 710 : if (DEBUG) { System.out.println("MemberValueArrayInitializer ::=..."); }  //$NON-NLS-1$
7013
    case 710 : if (DEBUG) { System.out.println("MemberValueArrayInitializer ::=..."); }  //$NON-NLS-1$
7007
		    consumeMemberValueArrayInitializer() ;  
7014
		    consumeMemberValueArrayInitializer() ;  
7008
			break;
7015
			break;
7009
 
7016
 
7010
    case 711 : if (DEBUG) { System.out.println("MemberValueArrayInitializer ::=..."); }  //$NON-NLS-1$
7017
    case 711 : if (DEBUG) { System.out.println("MemberValueArrayInitializer ::=..."); }  //$NON-NLS-1$
7011
		    consumeEmptyMemberValueArrayInitializer() ;  
7018
		    consumeMemberValueArrayInitializer() ;  
7012
			break;
7019
			break;
7013
 
7020
 
7014
    case 712 : if (DEBUG) { System.out.println("MemberValueArrayInitializer ::=..."); }  //$NON-NLS-1$
7021
    case 712 : if (DEBUG) { System.out.println("MemberValueArrayInitializer ::=..."); }  //$NON-NLS-1$
7015
		    consumeEmptyMemberValueArrayInitializer() ;  
7022
		    consumeEmptyMemberValueArrayInitializer() ;  
7016
			break;
7023
			break;
7017
 
7024
 
7018
    case 713 : if (DEBUG) { System.out.println("EnterMemberValueArrayInitializer ::="); }  //$NON-NLS-1$
7025
    case 713 : if (DEBUG) { System.out.println("MemberValueArrayInitializer ::=..."); }  //$NON-NLS-1$
7019
		    consumeEnterMemberValueArrayInitializer() ;  
7026
		    consumeEmptyMemberValueArrayInitializer() ;  
7020
			break;
7027
			break;
7021
 
7028
 
7022
    case 715 : if (DEBUG) { System.out.println("MemberValues ::= MemberValues COMMA MemberValue"); }  //$NON-NLS-1$
7029
    case 714 : if (DEBUG) { System.out.println("EnterMemberValueArrayInitializer ::="); }  //$NON-NLS-1$
7023
		    consumeMemberValues() ;  
7030
		    consumeEnterMemberValueArrayInitializer() ;  
7024
			break;
7031
			break;
7025
 
7032
 
7026
    case 716 : if (DEBUG) { System.out.println("MarkerAnnotation ::= AnnotationName"); }  //$NON-NLS-1$
7033
    case 716 : if (DEBUG) { System.out.println("MemberValues ::= MemberValues COMMA MemberValue"); }  //$NON-NLS-1$
7027
		    consumeMarkerAnnotation() ;  
7034
		    consumeMemberValues() ;  
7028
			break;
7035
			break;
7029
 
7036
 
7030
    case 717 : if (DEBUG) { System.out.println("SingleMemberAnnotationMemberValue ::= MemberValue"); }  //$NON-NLS-1$
7037
    case 717 : if (DEBUG) { System.out.println("MarkerAnnotation ::= AnnotationName"); }  //$NON-NLS-1$
7031
		    consumeSingleMemberAnnotationMemberValue() ;  
7038
		    consumeMarkerAnnotation() ;  
7032
			break;
7039
			break;
7033
 
7040
 
7034
    case 718 : if (DEBUG) { System.out.println("SingleMemberAnnotation ::= AnnotationName LPAREN..."); }  //$NON-NLS-1$
7041
    case 718 : if (DEBUG) { System.out.println("SingleMemberAnnotationMemberValue ::= MemberValue"); }  //$NON-NLS-1$
7035
		    consumeSingleMemberAnnotation() ;  
7042
		    consumeSingleMemberAnnotationMemberValue() ;  
7036
			break;
7043
			break;
7037
 
7044
 
7038
    case 719 : if (DEBUG) { System.out.println("RecoveryMethodHeaderName ::= Modifiersopt TypeParameters"); }  //$NON-NLS-1$
7045
    case 719 : if (DEBUG) { System.out.println("SingleMemberAnnotation ::= AnnotationName LPAREN..."); }  //$NON-NLS-1$
7039
		    consumeRecoveryMethodHeaderNameWithTypeParameters();  
7046
		    consumeSingleMemberAnnotation() ;  
7040
			break;
7047
			break;
7041
 
7048
 
7042
    case 720 : if (DEBUG) { System.out.println("RecoveryMethodHeaderName ::= Modifiersopt Type..."); }  //$NON-NLS-1$
7049
    case 720 : if (DEBUG) { System.out.println("RecoveryMethodHeaderName ::= Modifiersopt TypeParameters"); }  //$NON-NLS-1$
7043
		    consumeRecoveryMethodHeaderName();  
7050
		    consumeRecoveryMethodHeaderNameWithTypeParameters();  
7044
			break;
7051
			break;
7045
 
7052
 
7046
    case 721 : if (DEBUG) { System.out.println("RecoveryMethodHeader ::= RecoveryMethodHeaderName..."); }  //$NON-NLS-1$
7053
    case 721 : if (DEBUG) { System.out.println("RecoveryMethodHeaderName ::= Modifiersopt Type..."); }  //$NON-NLS-1$
7047
		    consumeMethodHeader();  
7054
		    consumeRecoveryMethodHeaderName();  
7048
			break;
7055
			break;
7049
 
7056
 
7050
    case 722 : if (DEBUG) { System.out.println("RecoveryMethodHeader ::= RecoveryMethodHeaderName..."); }  //$NON-NLS-1$
7057
    case 722 : if (DEBUG) { System.out.println("RecoveryMethodHeader ::= RecoveryMethodHeaderName..."); }  //$NON-NLS-1$
7051
		    consumeMethodHeader();  
7058
		    consumeMethodHeader();  
7052
			break;
7059
			break;
7053
 
7060
 
7054
	}
7061
    case 723 : if (DEBUG) { System.out.println("RecoveryMethodHeader ::= RecoveryMethodHeaderName..."); }  //$NON-NLS-1$
7062
		    consumeMethodHeader();  
7063
			break;
7064
 
7065
	}
7066
}
7067
protected void consumeEnterInstanceCreationArgumentList() {
7068
	this.shouldDeferRecovery = true;
7055
}
7069
}
7056
protected void consumeSimpleAssertStatement() {
7070
protected void consumeSimpleAssertStatement() {
7057
	// AssertStatement ::= 'assert' Expression ';'
7071
	// AssertStatement ::= 'assert' Expression ';'
Lines 8852-8862 Link Here
8852
				int c1, c2, c3, c4;
8866
				int c1, c2, c3, c4;
8853
				index[0]++;
8867
				index[0]++;
8854
				while (comment[index[0]] == 'u') index[0]++;
8868
				while (comment[index[0]] == 'u') index[0]++;
8855
				if (!(((c1 = ScannerHelper.getNumericValue(comment[index[0]++])) > 15
8869
				if (!(((c1 = ScannerHelper.getHexadecimalValue(comment[index[0]++])) > 15
8856
					|| c1 < 0)
8870
					|| c1 < 0)
8857
					|| ((c2 = ScannerHelper.getNumericValue(comment[index[0]++])) > 15 || c2 < 0)
8871
					|| ((c2 = ScannerHelper.getHexadecimalValue(comment[index[0]++])) > 15 || c2 < 0)
8858
					|| ((c3 = ScannerHelper.getNumericValue(comment[index[0]++])) > 15 || c3 < 0)
8872
					|| ((c3 = ScannerHelper.getHexadecimalValue(comment[index[0]++])) > 15 || c3 < 0)
8859
					|| ((c4 = ScannerHelper.getNumericValue(comment[index[0]++])) > 15 || c4 < 0))) {
8873
					|| ((c4 = ScannerHelper.getHexadecimalValue(comment[index[0]++])) > 15 || c4 < 0))) {
8860
						nextCharacter = (char) (((c1 * 16 + c2) * 16 + c3) * 16 + c4);
8874
						nextCharacter = (char) (((c1 * 16 + c2) * 16 + c3) * 16 + c4);
8861
				}
8875
				}
8862
				break;
8876
				break;
Lines 9551-9558 Link Here
9551
		this.stack[this.stateStackTop] = act;
9565
		this.stack[this.stateStackTop] = act;
9552
9566
9553
		act = tAction(act, this.currentToken);
9567
		act = tAction(act, this.currentToken);
9554
		if (act == ERROR_ACTION || this.restartRecovery) {
9568
		if (act == ERROR_ACTION || (this.restartRecovery && !this.shouldDeferRecovery)) {
9555
9569
			this.shouldDeferRecovery = false;
9556
			if (DEBUG_AUTOMATON) {
9570
			if (DEBUG_AUTOMATON) {
9557
				if (this.restartRecovery) {
9571
				if (this.restartRecovery) {
9558
					System.out.println("Restart      - "); //$NON-NLS-1$
9572
					System.out.println("Restart      - "); //$NON-NLS-1$
Lines 9722-9727 Link Here
9722
	boolean oldMethodRecoveryActivated = this.methodRecoveryActivated;
9736
	boolean oldMethodRecoveryActivated = this.methodRecoveryActivated;
9723
	if(this.options.performMethodsFullRecovery) {
9737
	if(this.options.performMethodsFullRecovery) {
9724
		this.methodRecoveryActivated = true;
9738
		this.methodRecoveryActivated = true;
9739
		// we should not relocate bodyStart if there is a block within the statements
9740
		this.ignoreNextOpeningBrace = true;
9725
	}
9741
	}
9726
9742
9727
	initialize();
9743
	initialize();
Lines 9971-9976 Link Here
9971
9987
9972
	boolean oldMethodRecoveryActivated = this.methodRecoveryActivated;
9988
	boolean oldMethodRecoveryActivated = this.methodRecoveryActivated;
9973
	if(this.options.performMethodsFullRecovery) {
9989
	if(this.options.performMethodsFullRecovery) {
9990
		// we should not relocate bodyStart if there is a block within the statements
9991
		this.ignoreNextOpeningBrace = true;
9974
		this.methodRecoveryActivated = true;
9992
		this.methodRecoveryActivated = true;
9975
		this.rParenPos = md.sourceEnd;
9993
		this.rParenPos = md.sourceEnd;
9976
	}
9994
	}
(-)a/org.eclipse.jdt.core/compiler/org/eclipse/jdt/internal/compiler/parser/ParserBasicInformation.java (-35 / +35 lines)
Lines 1-35 Link Here
1
/*******************************************************************************
1
/*******************************************************************************
2
 * Copyright (c) 2000, 2011 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
6
 * http://www.eclipse.org/legal/epl-v10.html
6
 * http://www.eclipse.org/legal/epl-v10.html
7
 * 
7
 * 
8
 * Contributors:
8
 * Contributors:
9
 *     IBM Corporation - initial API and implementation
9
 *     IBM Corporation - initial API and implementation
10
 *******************************************************************************/
10
 *******************************************************************************/
11
package org.eclipse.jdt.internal.compiler.parser;
11
package org.eclipse.jdt.internal.compiler.parser;
12
12
13
/*An interface that contains static declarations for some basic information
13
/*An interface that contains static declarations for some basic information
14
 about the parser such as the number of rules in the grammar, the starting state, etc...*/
14
 about the parser such as the number of rules in the grammar, the starting state, etc...*/
15
public interface ParserBasicInformation {
15
public interface ParserBasicInformation {
16
16
17
	int ERROR_SYMBOL = 110,
17
	int ERROR_SYMBOL = 110,
18
		MAX_NAME_LENGTH = 41,
18
		MAX_NAME_LENGTH = 41,
19
		NUM_STATES = 1002,
19
		NUM_STATES = 1008,
20
20
21
		NT_OFFSET = 110,
21
		NT_OFFSET = 110,
22
		SCOPE_UBOUND = 137,
22
		SCOPE_UBOUND = 137,
23
		SCOPE_SIZE = 138,
23
		SCOPE_SIZE = 138,
24
		LA_STATE_OFFSET = 12446,
24
		LA_STATE_OFFSET = 12379,
25
		MAX_LA = 1,
25
		MAX_LA = 1,
26
		NUM_RULES = 722,
26
		NUM_RULES = 723,
27
		NUM_TERMINALS = 110,
27
		NUM_TERMINALS = 110,
28
		NUM_NON_TERMINALS = 323,
28
		NUM_NON_TERMINALS = 324,
29
		NUM_SYMBOLS = 433,
29
		NUM_SYMBOLS = 434,
30
		START_STATE = 1084,
30
		START_STATE = 1260,
31
		EOFT_SYMBOL = 69,
31
		EOFT_SYMBOL = 69,
32
		EOLT_SYMBOL = 69,
32
		EOLT_SYMBOL = 69,
33
		ACCEPT_ACTION = 12445,
33
		ACCEPT_ACTION = 12378,
34
		ERROR_ACTION = 12446;
34
		ERROR_ACTION = 12379;
35
}
35
}
(-)a/org.eclipse.jdt.core/compiler/org/eclipse/jdt/internal/compiler/parser/RecoveredElement.java (-1 / +10 lines)
Lines 1-5 Link Here
1
/*******************************************************************************
1
/*******************************************************************************
2
 * Copyright (c) 2000, 2008 IBM Corporation and others.
2
 * Copyright (c) 2000, 2012 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 107-112 Link Here
107
	/* default behavior is to delegate recording to parent if any */
107
	/* default behavior is to delegate recording to parent if any */
108
	resetPendingModifiers();
108
	resetPendingModifiers();
109
	if (this.parent == null) return this; // ignore
109
	if (this.parent == null) return this; // ignore
110
	if (this instanceof RecoveredType) {
111
		TypeDeclaration typeDeclaration = ((RecoveredType) this).typeDeclaration;
112
		if (typeDeclaration != null && (typeDeclaration.bits & ASTNode.IsAnonymousType) != 0) { 
113
			// https://bugs.eclipse.org/bugs/show_bug.cgi?id=291040, new X(<SelectOnMessageSend:zoo()>) { ???
114
			if (statement.sourceStart > typeDeclaration.sourceStart && statement.sourceEnd < typeDeclaration.sourceEnd) {
115
				return this;
116
			}
117
		}
118
	}
110
	this.updateSourceEndIfNecessary(previousAvailableLineEnd(statement.sourceStart - 1));
119
	this.updateSourceEndIfNecessary(previousAvailableLineEnd(statement.sourceStart - 1));
111
	return this.parent.add(statement, bracketBalanceValue);
120
	return this.parent.add(statement, bracketBalanceValue);
112
}
121
}
(-)a/org.eclipse.jdt.core/compiler/org/eclipse/jdt/internal/compiler/parser/RecoveredType.java (-1 / +21 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 366003 - CCE in ASTNode.resolveAnnotations(ASTNode.java:639)
10
 *******************************************************************************/
11
 *******************************************************************************/
11
package org.eclipse.jdt.internal.compiler.parser;
12
package org.eclipse.jdt.internal.compiler.parser;
12
13
Lines 773-776 Link Here
773
		this.typeDeclaration.bodyEnd = end;
774
		this.typeDeclaration.bodyEnd = end;
774
	}
775
	}
775
}
776
}
777
public void annotationsConsumed(Annotation[] consumedAnnotations) {
778
	RecoveredAnnotation[] keep = new RecoveredAnnotation[this.pendingAnnotationCount];
779
	int numKeep = 0;
780
	int pendingCount = this.pendingAnnotationCount;
781
	int consumedLength = consumedAnnotations.length;
782
	outerLoop:
783
	for (int i = 0; i < pendingCount; i++) {
784
		Annotation pendingAnnotationAST = this.pendingAnnotations[i].annotation;
785
		for (int j = 0; j < consumedLength; j++) {
786
			if (consumedAnnotations[j] == pendingAnnotationAST)
787
				continue outerLoop;
788
		}
789
		keep[numKeep++] = this.pendingAnnotations[i];
790
	}
791
	if (numKeep != this.pendingAnnotationCount) {
792
		this.pendingAnnotations = keep;
793
		this.pendingAnnotationCount = numKeep;
794
	}
795
}
776
}
796
}
(-)a/org.eclipse.jdt.core/compiler/org/eclipse/jdt/internal/compiler/parser/Scanner.java (-7 / +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 186342 - [compiler][null] Using annotations for null checking
10
 *******************************************************************************/
11
 *******************************************************************************/
11
package org.eclipse.jdt.internal.compiler.parser;
12
package org.eclipse.jdt.internal.compiler.parser;
12
13
Lines 1819-1831 Link Here
1819
		this.currentPosition += (this.eofPosition - this.currentPosition);
1820
		this.currentPosition += (this.eofPosition - this.currentPosition);
1820
		throw new InvalidInputException(INVALID_UNICODE_ESCAPE);
1821
		throw new InvalidInputException(INVALID_UNICODE_ESCAPE);
1821
	}
1822
	}
1822
	if ((c1 = ScannerHelper.getNumericValue(this.source[this.currentPosition++])) > 15
1823
	if ((c1 = ScannerHelper.getHexadecimalValue(this.source[this.currentPosition++])) > 15
1823
    		|| c1 < 0
1824
    		|| c1 < 0
1824
    		|| (c2 = ScannerHelper.getNumericValue(this.source[this.currentPosition++])) > 15
1825
    		|| (c2 = ScannerHelper.getHexadecimalValue(this.source[this.currentPosition++])) > 15
1825
    		|| c2 < 0
1826
    		|| c2 < 0
1826
    		|| (c3 = ScannerHelper.getNumericValue(this.source[this.currentPosition++])) > 15
1827
    		|| (c3 = ScannerHelper.getHexadecimalValue(this.source[this.currentPosition++])) > 15
1827
    		|| c3 < 0
1828
    		|| c3 < 0
1828
    		|| (c4 = ScannerHelper.getNumericValue(this.source[this.currentPosition++])) > 15
1829
    		|| (c4 = ScannerHelper.getHexadecimalValue(this.source[this.currentPosition++])) > 15
1829
    		|| c4 < 0){
1830
    		|| c4 < 0){
1830
		throw new InvalidInputException(INVALID_UNICODE_ESCAPE);
1831
		throw new InvalidInputException(INVALID_UNICODE_ESCAPE);
1831
	}
1832
	}
Lines 2725-2742 Link Here
2725
			// OctalDigit OctalDigit
2726
			// OctalDigit OctalDigit
2726
			// ZeroToThree OctalDigit OctalDigit
2727
			// ZeroToThree OctalDigit OctalDigit
2727
2728
2728
			int number = ScannerHelper.getNumericValue(this.currentCharacter);
2729
			int number = ScannerHelper.getHexadecimalValue(this.currentCharacter);
2729
			if (number >= 0 && number <= 7) {
2730
			if (number >= 0 && number <= 7) {
2730
				boolean zeroToThreeNot = number > 3;
2731
				boolean zeroToThreeNot = number > 3;
2731
				if (ScannerHelper.isDigit(this.currentCharacter = this.source[this.currentPosition++])) {
2732
				if (ScannerHelper.isDigit(this.currentCharacter = this.source[this.currentPosition++])) {
2732
					int digit = ScannerHelper.getNumericValue(this.currentCharacter);
2733
					int digit = ScannerHelper.getHexadecimalValue(this.currentCharacter);
2733
					if (digit >= 0 && digit <= 7) {
2734
					if (digit >= 0 && digit <= 7) {
2734
						number = (number * 8) + digit;
2735
						number = (number * 8) + digit;
2735
						if (ScannerHelper.isDigit(this.currentCharacter = this.source[this.currentPosition++])) {
2736
						if (ScannerHelper.isDigit(this.currentCharacter = this.source[this.currentPosition++])) {
2736
							if (zeroToThreeNot) {// has read \NotZeroToThree OctalDigit Digit --> ignore last character
2737
							if (zeroToThreeNot) {// has read \NotZeroToThree OctalDigit Digit --> ignore last character
2737
								this.currentPosition--;
2738
								this.currentPosition--;
2738
							} else {
2739
							} else {
2739
								digit = ScannerHelper.getNumericValue(this.currentCharacter);
2740
								digit = ScannerHelper.getHexadecimalValue(this.currentCharacter);
2740
								if (digit >= 0 && digit <= 7){ // has read \ZeroToThree OctalDigit OctalDigit
2741
								if (digit >= 0 && digit <= 7){ // has read \ZeroToThree OctalDigit OctalDigit
2741
									number = (number * 8) + digit;
2742
									number = (number * 8) + digit;
2742
								} else {// has read \ZeroToThree OctalDigit NonOctalDigit --> ignore last character
2743
								} else {// has read \ZeroToThree OctalDigit NonOctalDigit --> ignore last character
(-)a/org.eclipse.jdt.core/compiler/org/eclipse/jdt/internal/compiler/parser/ScannerHelper.java (+44 lines)
Lines 475-480 Link Here
475
	}
475
	}
476
	return Character.getNumericValue(c);
476
	return Character.getNumericValue(c);
477
}
477
}
478
public static int getHexadecimalValue(char c) {
479
	switch(c) {
480
		case '0' :
481
			return 0;
482
		case '1' :
483
			return 1;
484
		case '2' :
485
			return 2;
486
		case '3' :
487
			return 3;
488
		case '4' :
489
			return 4;
490
		case '5' :
491
			return 5;
492
		case '6' :
493
			return 6;
494
		case '7' :
495
			return 7;
496
		case '8' :
497
			return 8;
498
		case '9' :
499
			return 9;
500
		case 'A' :
501
		case 'a' :
502
			return 10;
503
		case 'B' :
504
		case 'b' :
505
			return 11;
506
		case 'C' :
507
		case 'c' :
508
			return 12;
509
		case 'D' :
510
		case 'd' :
511
			return 13;
512
		case 'E' :
513
		case 'e' :
514
			return 14;
515
		case 'F' :
516
		case 'f' :
517
			return 15;
518
		default:
519
			return -1;
520
	}
521
}
478
public static char toUpperCase(char c) {
522
public static char toUpperCase(char c) {
479
	if (c < MAX_OBVIOUS) {
523
	if (c < MAX_OBVIOUS) {
480
		if ((ScannerHelper.OBVIOUS_IDENT_CHAR_NATURES[c] & ScannerHelper.C_UPPER_LETTER) != 0) {
524
		if ((ScannerHelper.OBVIOUS_IDENT_CHAR_NATURES[c] & ScannerHelper.C_UPPER_LETTER) != 0) {
(-)a/org.eclipse.jdt.core/compiler/org/eclipse/jdt/internal/compiler/parser/TerminalTokens.java (-146 / +146 lines)
Lines 1-146 Link Here
1
/*******************************************************************************
1
/*******************************************************************************
2
 * Copyright (c) 2000, 2011 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
6
 * http://www.eclipse.org/legal/epl-v10.html
6
 * http://www.eclipse.org/legal/epl-v10.html
7
 *
7
 *
8
 * Contributors:
8
 * Contributors:
9
 *     IBM Corporation - initial API and implementation
9
 *     IBM Corporation - initial API and implementation
10
 *******************************************************************************/
10
 *******************************************************************************/
11
package org.eclipse.jdt.internal.compiler.parser;
11
package org.eclipse.jdt.internal.compiler.parser;
12
12
13
/**
13
/**
14
 * IMPORTANT NOTE: These constants are dedicated to the internal Scanner implementation.
14
 * IMPORTANT NOTE: These constants are dedicated to the internal Scanner implementation.
15
 * It is mirrored in org.eclipse.jdt.core.compiler public package where it is API.
15
 * It is mirrored in org.eclipse.jdt.core.compiler public package where it is API.
16
 * The mirror implementation is using the backward compatible ITerminalSymbols constant
16
 * The mirror implementation is using the backward compatible ITerminalSymbols constant
17
 * definitions (stable with 2.0), whereas the internal implementation uses TerminalTokens
17
 * definitions (stable with 2.0), whereas the internal implementation uses TerminalTokens
18
 * which constant values reflect the latest parser generation state.
18
 * which constant values reflect the latest parser generation state.
19
 */
19
 */
20
/**
20
/**
21
 * Maps each terminal symbol in the java-grammar into a unique integer.
21
 * Maps each terminal symbol in the java-grammar into a unique integer.
22
 * This integer is used to represent the terminal when computing a parsing action.
22
 * This integer is used to represent the terminal when computing a parsing action.
23
 *
23
 *
24
 * Disclaimer : These constant values are generated automatically using a Java
24
 * Disclaimer : These constant values are generated automatically using a Java
25
 * grammar, therefore their actual values are subject to change if new keywords
25
 * grammar, therefore their actual values are subject to change if new keywords
26
 * were added to the language (for instance, 'assert' is a keyword in 1.4).
26
 * were added to the language (for instance, 'assert' is a keyword in 1.4).
27
 */
27
 */
28
public interface TerminalTokens {
28
public interface TerminalTokens {
29
29
30
	// special tokens not part of grammar - not autogenerated
30
	// special tokens not part of grammar - not autogenerated
31
	int TokenNameWHITESPACE = 1000,
31
	int TokenNameWHITESPACE = 1000,
32
		TokenNameCOMMENT_LINE = 1001,
32
		TokenNameCOMMENT_LINE = 1001,
33
		TokenNameCOMMENT_BLOCK = 1002,
33
		TokenNameCOMMENT_BLOCK = 1002,
34
		TokenNameCOMMENT_JAVADOC = 1003;
34
		TokenNameCOMMENT_JAVADOC = 1003;
35
35
36
	int TokenNameIdentifier = 26,
36
	int TokenNameIdentifier = 26,
37
		TokenNameabstract = 56,
37
		TokenNameabstract = 56,
38
		TokenNameassert = 74,
38
		TokenNameassert = 74,
39
		TokenNameboolean = 32,
39
		TokenNameboolean = 32,
40
		TokenNamebreak = 75,
40
		TokenNamebreak = 75,
41
		TokenNamebyte = 33,
41
		TokenNamebyte = 33,
42
		TokenNamecase = 102,
42
		TokenNamecase = 102,
43
		TokenNamecatch = 100,
43
		TokenNamecatch = 100,
44
		TokenNamechar = 34,
44
		TokenNamechar = 34,
45
		TokenNameclass = 72,
45
		TokenNameclass = 72,
46
		TokenNamecontinue = 76,
46
		TokenNamecontinue = 76,
47
		TokenNameconst = 108,
47
		TokenNameconst = 108,
48
		TokenNamedefault = 97,
48
		TokenNamedefault = 97,
49
		TokenNamedo = 77,
49
		TokenNamedo = 77,
50
		TokenNamedouble = 35,
50
		TokenNamedouble = 35,
51
		TokenNameelse = 104,
51
		TokenNameelse = 104,
52
		TokenNameenum = 98,
52
		TokenNameenum = 98,
53
		TokenNameextends = 99,
53
		TokenNameextends = 99,
54
		TokenNamefalse = 44,
54
		TokenNamefalse = 44,
55
		TokenNamefinal = 57,
55
		TokenNamefinal = 57,
56
		TokenNamefinally = 103,
56
		TokenNamefinally = 103,
57
		TokenNamefloat = 36,
57
		TokenNamefloat = 36,
58
		TokenNamefor = 78,
58
		TokenNamefor = 78,
59
		TokenNamegoto = 109,
59
		TokenNamegoto = 109,
60
		TokenNameif = 79,
60
		TokenNameif = 79,
61
		TokenNameimplements = 106,
61
		TokenNameimplements = 106,
62
		TokenNameimport = 101,
62
		TokenNameimport = 101,
63
		TokenNameinstanceof = 13,
63
		TokenNameinstanceof = 13,
64
		TokenNameint = 37,
64
		TokenNameint = 37,
65
		TokenNameinterface = 95,
65
		TokenNameinterface = 95,
66
		TokenNamelong = 38,
66
		TokenNamelong = 38,
67
		TokenNamenative = 58,
67
		TokenNamenative = 58,
68
		TokenNamenew = 43,
68
		TokenNamenew = 43,
69
		TokenNamenull = 45,
69
		TokenNamenull = 45,
70
		TokenNamepackage = 96,
70
		TokenNamepackage = 96,
71
		TokenNameprivate = 59,
71
		TokenNameprivate = 59,
72
		TokenNameprotected = 60,
72
		TokenNameprotected = 60,
73
		TokenNamepublic = 61,
73
		TokenNamepublic = 61,
74
		TokenNamereturn = 80,
74
		TokenNamereturn = 80,
75
		TokenNameshort = 39,
75
		TokenNameshort = 39,
76
		TokenNamestatic = 54,
76
		TokenNamestatic = 54,
77
		TokenNamestrictfp = 62,
77
		TokenNamestrictfp = 62,
78
		TokenNamesuper = 41,
78
		TokenNamesuper = 41,
79
		TokenNameswitch = 81,
79
		TokenNameswitch = 81,
80
		TokenNamesynchronized = 55,
80
		TokenNamesynchronized = 55,
81
		TokenNamethis = 42,
81
		TokenNamethis = 42,
82
		TokenNamethrow = 82,
82
		TokenNamethrow = 82,
83
		TokenNamethrows = 105,
83
		TokenNamethrows = 105,
84
		TokenNametransient = 63,
84
		TokenNametransient = 63,
85
		TokenNametrue = 46,
85
		TokenNametrue = 46,
86
		TokenNametry = 83,
86
		TokenNametry = 83,
87
		TokenNamevoid = 40,
87
		TokenNamevoid = 40,
88
		TokenNamevolatile = 64,
88
		TokenNamevolatile = 64,
89
		TokenNamewhile = 73,
89
		TokenNamewhile = 73,
90
		TokenNameIntegerLiteral = 47,
90
		TokenNameIntegerLiteral = 47,
91
		TokenNameLongLiteral = 48,
91
		TokenNameLongLiteral = 48,
92
		TokenNameFloatingPointLiteral = 49,
92
		TokenNameFloatingPointLiteral = 49,
93
		TokenNameDoubleLiteral = 50,
93
		TokenNameDoubleLiteral = 50,
94
		TokenNameCharacterLiteral = 51,
94
		TokenNameCharacterLiteral = 51,
95
		TokenNameStringLiteral = 52,
95
		TokenNameStringLiteral = 52,
96
		TokenNamePLUS_PLUS = 8,
96
		TokenNamePLUS_PLUS = 8,
97
		TokenNameMINUS_MINUS = 9,
97
		TokenNameMINUS_MINUS = 9,
98
		TokenNameEQUAL_EQUAL = 18,
98
		TokenNameEQUAL_EQUAL = 18,
99
		TokenNameLESS_EQUAL = 14,
99
		TokenNameLESS_EQUAL = 14,
100
		TokenNameGREATER_EQUAL = 15,
100
		TokenNameGREATER_EQUAL = 15,
101
		TokenNameNOT_EQUAL = 19,
101
		TokenNameNOT_EQUAL = 19,
102
		TokenNameLEFT_SHIFT = 17,
102
		TokenNameLEFT_SHIFT = 17,
103
		TokenNameRIGHT_SHIFT = 10,
103
		TokenNameRIGHT_SHIFT = 10,
104
		TokenNameUNSIGNED_RIGHT_SHIFT = 12,
104
		TokenNameUNSIGNED_RIGHT_SHIFT = 12,
105
		TokenNamePLUS_EQUAL = 84,
105
		TokenNamePLUS_EQUAL = 84,
106
		TokenNameMINUS_EQUAL = 85,
106
		TokenNameMINUS_EQUAL = 85,
107
		TokenNameMULTIPLY_EQUAL = 86,
107
		TokenNameMULTIPLY_EQUAL = 86,
108
		TokenNameDIVIDE_EQUAL = 87,
108
		TokenNameDIVIDE_EQUAL = 87,
109
		TokenNameAND_EQUAL = 88,
109
		TokenNameAND_EQUAL = 88,
110
		TokenNameOR_EQUAL = 89,
110
		TokenNameOR_EQUAL = 89,
111
		TokenNameXOR_EQUAL = 90,
111
		TokenNameXOR_EQUAL = 90,
112
		TokenNameREMAINDER_EQUAL = 91,
112
		TokenNameREMAINDER_EQUAL = 91,
113
		TokenNameLEFT_SHIFT_EQUAL = 92,
113
		TokenNameLEFT_SHIFT_EQUAL = 92,
114
		TokenNameRIGHT_SHIFT_EQUAL = 93,
114
		TokenNameRIGHT_SHIFT_EQUAL = 93,
115
		TokenNameUNSIGNED_RIGHT_SHIFT_EQUAL = 94,
115
		TokenNameUNSIGNED_RIGHT_SHIFT_EQUAL = 94,
116
		TokenNameOR_OR = 25,
116
		TokenNameOR_OR = 25,
117
		TokenNameAND_AND = 24,
117
		TokenNameAND_AND = 24,
118
		TokenNamePLUS = 1,
118
		TokenNamePLUS = 1,
119
		TokenNameMINUS = 2,
119
		TokenNameMINUS = 2,
120
		TokenNameNOT = 66,
120
		TokenNameNOT = 66,
121
		TokenNameREMAINDER = 5,
121
		TokenNameREMAINDER = 5,
122
		TokenNameXOR = 21,
122
		TokenNameXOR = 21,
123
		TokenNameAND = 20,
123
		TokenNameAND = 20,
124
		TokenNameMULTIPLY = 4,
124
		TokenNameMULTIPLY = 4,
125
		TokenNameOR = 22,
125
		TokenNameOR = 22,
126
		TokenNameTWIDDLE = 67,
126
		TokenNameTWIDDLE = 67,
127
		TokenNameDIVIDE = 6,
127
		TokenNameDIVIDE = 6,
128
		TokenNameGREATER = 11,
128
		TokenNameGREATER = 11,
129
		TokenNameLESS = 7,
129
		TokenNameLESS = 7,
130
		TokenNameLPAREN = 29,
130
		TokenNameLPAREN = 29,
131
		TokenNameRPAREN = 28,
131
		TokenNameRPAREN = 28,
132
		TokenNameLBRACE = 68,
132
		TokenNameLBRACE = 68,
133
		TokenNameRBRACE = 31,
133
		TokenNameRBRACE = 31,
134
		TokenNameLBRACKET = 16,
134
		TokenNameLBRACKET = 16,
135
		TokenNameRBRACKET = 70,
135
		TokenNameRBRACKET = 70,
136
		TokenNameSEMICOLON = 27,
136
		TokenNameSEMICOLON = 27,
137
		TokenNameQUESTION = 23,
137
		TokenNameQUESTION = 23,
138
		TokenNameCOLON = 65,
138
		TokenNameCOLON = 65,
139
		TokenNameCOMMA = 30,
139
		TokenNameCOMMA = 30,
140
		TokenNameDOT = 3,
140
		TokenNameDOT = 3,
141
		TokenNameEQUAL = 71,
141
		TokenNameEQUAL = 71,
142
		TokenNameAT = 53,
142
		TokenNameAT = 53,
143
		TokenNameELLIPSIS = 107,
143
		TokenNameELLIPSIS = 107,
144
		TokenNameEOF = 69,
144
		TokenNameEOF = 69,
145
		TokenNameERROR = 110;
145
		TokenNameERROR = 110;
146
}
146
}
(-)a/org.eclipse.jdt.core/compiler/org/eclipse/jdt/internal/compiler/parser/parser19.rsc (-1 / +1 lines)
Lines 1-2 Link Here
1
hhgFFFDDgAAA!FdAfAID
1
hhgFFFDDgAAA!FdAfAID
2
JJD!DDbGG_!!H!Ab!!!!55!
2
JJD!DDbGG_!!H!Ab!!!!55!
(-)a/org.eclipse.jdt.core/compiler/org/eclipse/jdt/internal/compiler/parser/readableNames.properties (-11 / +2 lines)
Lines 1-15 Link Here
1
###############################################################################
2
# Copyright (c) 2011 IBM Corporation and others.
3
# All rights reserved. This program and the accompanying materials
4
# are made available under the terms of the Eclipse Public License v1.0
5
# which accompanies this distribution, and is available at
6
# http://www.eclipse.org/legal/epl-v10.html
7
#
8
# Contributors:
9
#     IBM Corporation - initial API and implementation
10
###############################################################################
11
,opt=,
1
,opt=,
12
\;opt=;
2
;opt=;
13
AbstractMethodDeclaration=MethodDeclaration
3
AbstractMethodDeclaration=MethodDeclaration
14
AdditionalBound1=AdditionalBound1
4
AdditionalBound1=AdditionalBound1
15
AdditionalBound=AdditionalBound
5
AdditionalBound=AdditionalBound
Lines 109-114 Link Here
109
EnhancedForStatementHeaderInit=EnhancedForStatementHeaderInit
99
EnhancedForStatementHeaderInit=EnhancedForStatementHeaderInit
110
EnhancedForStatementNoShortIf=EnhancedForStatementNoShortIf
100
EnhancedForStatementNoShortIf=EnhancedForStatementNoShortIf
111
EnterCompilationUnit=EnterCompilationUnit
101
EnterCompilationUnit=EnterCompilationUnit
102
EnterInstanceCreationArgumentList=EnterInstanceCreationArgumentList
112
EnterMemberValue=EnterMemberValue
103
EnterMemberValue=EnterMemberValue
113
EnterMemberValueArrayInitializer=EnterMemberValueArrayInitializer
104
EnterMemberValueArrayInitializer=EnterMemberValueArrayInitializer
114
EnterVariable=EnterVariable
105
EnterVariable=EnterVariable
(-)a/org.eclipse.jdt.core/compiler/org/eclipse/jdt/internal/compiler/problem/ProblemHandler.java (-1 / +22 lines)
Lines 1-5 Link Here
1
/*******************************************************************************
1
/*******************************************************************************
2
 * Copyright (c) 2000, 2009 IBM Corporation and others.
2
 * Copyright (c) 2000, 2012 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 12-20 Link Here
12
12
13
import org.eclipse.jdt.core.compiler.CategorizedProblem;
13
import org.eclipse.jdt.core.compiler.CategorizedProblem;
14
import org.eclipse.jdt.core.compiler.CharOperation;
14
import org.eclipse.jdt.core.compiler.CharOperation;
15
import org.eclipse.jdt.core.compiler.IProblem;
15
import org.eclipse.jdt.internal.compiler.CompilationResult;
16
import org.eclipse.jdt.internal.compiler.CompilationResult;
16
import org.eclipse.jdt.internal.compiler.IErrorHandlingPolicy;
17
import org.eclipse.jdt.internal.compiler.IErrorHandlingPolicy;
17
import org.eclipse.jdt.internal.compiler.IProblemFactory;
18
import org.eclipse.jdt.internal.compiler.IProblemFactory;
19
import org.eclipse.jdt.internal.compiler.ast.CompilationUnitDeclaration;
20
import org.eclipse.jdt.internal.compiler.env.ICompilationUnit;
18
import org.eclipse.jdt.internal.compiler.impl.CompilerOptions;
21
import org.eclipse.jdt.internal.compiler.impl.CompilerOptions;
19
import org.eclipse.jdt.internal.compiler.impl.ReferenceContext;
22
import org.eclipse.jdt.internal.compiler.impl.ReferenceContext;
20
import org.eclipse.jdt.internal.compiler.util.Util;
23
import org.eclipse.jdt.internal.compiler.util.Util;
Lines 114-119 Link Here
114
	if (severity == ProblemSeverities.Ignore)
117
	if (severity == ProblemSeverities.Ignore)
115
		return;
118
		return;
116
119
120
	if ((severity & ProblemSeverities.Optional) != 0 && problemId != IProblem.Task) {
121
		ICompilationUnit cu = unitResult.getCompilationUnit();
122
		try{
123
			if (cu != null && cu.ignoreOptionalProblems())
124
				return;
125
		// workaround for illegal implementation of ICompilationUnit, see https://bugs.eclipse.org/372351
126
		} catch (AbstractMethodError ex) {
127
			// continue
128
		}
129
	}
130
117
	// if no reference context, we need to abort from the current compilation process
131
	// if no reference context, we need to abort from the current compilation process
118
	if (referenceContext == null) {
132
	if (referenceContext == null) {
119
		if ((severity & ProblemSeverities.Error) != 0) { // non reportable error is fatal
133
		if ((severity & ProblemSeverities.Error) != 0) { // non reportable error is fatal
Lines 150-155 Link Here
150
		case ProblemSeverities.Error :
164
		case ProblemSeverities.Error :
151
			record(problem, unitResult, referenceContext);
165
			record(problem, unitResult, referenceContext);
152
			if ((severity & ProblemSeverities.Fatal) != 0) {
166
			if ((severity & ProblemSeverities.Fatal) != 0) {
167
				// don't abort or tag as error if the error is suppressed
168
				if (!referenceContext.hasErrors() && (severity & ProblemSeverities.Optional) != 0 && this.options.suppressOptionalErrors) {
169
					CompilationUnitDeclaration unitDecl = referenceContext.getCompilationUnitDeclaration();
170
					if (unitDecl != null && unitDecl.isSuppressed(problem)) {
171
						return;
172
					}
173
				}
153
				referenceContext.tagAsHavingErrors();
174
				referenceContext.tagAsHavingErrors();
154
				// should abort ?
175
				// should abort ?
155
				int abortLevel;
176
				int abortLevel;
(-)a/org.eclipse.jdt.core/compiler/org/eclipse/jdt/internal/compiler/problem/ProblemReporter.java (-18 / +406 lines)
Lines 1-5 Link Here
1
/*******************************************************************************
1
/*******************************************************************************
2
 * Copyright (c) 2000, 2011 IBM Corporation and others.
2
 * Copyright (c) 2000, 2012 IBM Corporation and others.
3
 * All rights reserved. This program and the accompanying materials
3
 * All rights reserved. This program and the accompanying materials
4
 * are made available under the terms of the Eclipse Public License v1.0
4
 * are made available under the terms of the Eclipse Public License v1.0
5
 * which accompanies this distribution, and is available at
5
 * which accompanies this distribution, and is available at
Lines 8-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  - Contributions for 
11
 *     Stephan Herrmann  - Contributions for
12
 *     						bug 236385 - 
12
 *	     						bug 236385 - [compiler] Warn for potential programming problem if an object is created but not used
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
15
 *								bug 186342 - [compiler][null] Using annotations for null checking
16
 *								bug 365519 - editorial cleanup after bug 186342 and bug 365387
17
 *								bug 365662 - [compiler][null] warn on contradictory and redundant null annotations
18
 *								bug 365531 - [compiler][null] investigate alternative strategy for internally encoding nullness defaults
14
 *******************************************************************************/
19
 *******************************************************************************/
15
package org.eclipse.jdt.internal.compiler.problem;
20
package org.eclipse.jdt.internal.compiler.problem;
16
21
Lines 51-56 Link Here
51
import org.eclipse.jdt.internal.compiler.ast.EqualExpression;
56
import org.eclipse.jdt.internal.compiler.ast.EqualExpression;
52
import org.eclipse.jdt.internal.compiler.ast.ExplicitConstructorCall;
57
import org.eclipse.jdt.internal.compiler.ast.ExplicitConstructorCall;
53
import org.eclipse.jdt.internal.compiler.ast.Expression;
58
import org.eclipse.jdt.internal.compiler.ast.Expression;
59
import org.eclipse.jdt.internal.compiler.ast.FakedTrackingVariable;
54
import org.eclipse.jdt.internal.compiler.ast.FieldDeclaration;
60
import org.eclipse.jdt.internal.compiler.ast.FieldDeclaration;
55
import org.eclipse.jdt.internal.compiler.ast.FieldReference;
61
import org.eclipse.jdt.internal.compiler.ast.FieldReference;
56
import org.eclipse.jdt.internal.compiler.ast.ImportReference;
62
import org.eclipse.jdt.internal.compiler.ast.ImportReference;
Lines 82-87 Link Here
82
import org.eclipse.jdt.internal.compiler.classfmt.ClassFileConstants;
88
import org.eclipse.jdt.internal.compiler.classfmt.ClassFileConstants;
83
import org.eclipse.jdt.internal.compiler.env.AccessRestriction;
89
import org.eclipse.jdt.internal.compiler.env.AccessRestriction;
84
import org.eclipse.jdt.internal.compiler.env.ICompilationUnit;
90
import org.eclipse.jdt.internal.compiler.env.ICompilationUnit;
91
import org.eclipse.jdt.internal.compiler.flow.FlowInfo;
85
import org.eclipse.jdt.internal.compiler.impl.CompilerOptions;
92
import org.eclipse.jdt.internal.compiler.impl.CompilerOptions;
86
import org.eclipse.jdt.internal.compiler.impl.ReferenceContext;
93
import org.eclipse.jdt.internal.compiler.impl.ReferenceContext;
87
import org.eclipse.jdt.internal.compiler.lookup.ArrayBinding;
94
import org.eclipse.jdt.internal.compiler.lookup.ArrayBinding;
Lines 91-96 Link Here
91
import org.eclipse.jdt.internal.compiler.lookup.InvocationSite;
98
import org.eclipse.jdt.internal.compiler.lookup.InvocationSite;
92
import org.eclipse.jdt.internal.compiler.lookup.LocalVariableBinding;
99
import org.eclipse.jdt.internal.compiler.lookup.LocalVariableBinding;
93
import org.eclipse.jdt.internal.compiler.lookup.MethodBinding;
100
import org.eclipse.jdt.internal.compiler.lookup.MethodBinding;
101
import org.eclipse.jdt.internal.compiler.lookup.PackageBinding;
94
import org.eclipse.jdt.internal.compiler.lookup.ParameterizedGenericMethodBinding;
102
import org.eclipse.jdt.internal.compiler.lookup.ParameterizedGenericMethodBinding;
95
import org.eclipse.jdt.internal.compiler.lookup.ProblemMethodBinding;
103
import org.eclipse.jdt.internal.compiler.lookup.ProblemMethodBinding;
96
import org.eclipse.jdt.internal.compiler.lookup.ProblemReasons;
104
import org.eclipse.jdt.internal.compiler.lookup.ProblemReasons;
Lines 285-290 Link Here
285
			return CompilerOptions.NullReference;
293
			return CompilerOptions.NullReference;
286
294
287
		case IProblem.PotentialNullLocalVariableReference:
295
		case IProblem.PotentialNullLocalVariableReference:
296
		case IProblem.PotentialNullMessageSendReference:
288
			return CompilerOptions.PotentialNullReference;
297
			return CompilerOptions.PotentialNullReference;
289
298
290
		case IProblem.RedundantLocalVariableNullAssignment:
299
		case IProblem.RedundantLocalVariableNullAssignment:
Lines 293-299 Link Here
293
		case IProblem.NonNullLocalVariableComparisonYieldsFalse:
302
		case IProblem.NonNullLocalVariableComparisonYieldsFalse:
294
		case IProblem.NullLocalVariableComparisonYieldsFalse:
303
		case IProblem.NullLocalVariableComparisonYieldsFalse:
295
		case IProblem.NullLocalVariableInstanceofYieldsFalse:
304
		case IProblem.NullLocalVariableInstanceofYieldsFalse:
305
		case IProblem.RedundantNullCheckOnNonNullMessageSend:
296
			return CompilerOptions.RedundantNullCheck;
306
			return CompilerOptions.RedundantNullCheck;
307
308
		case IProblem.RequiredNonNullButProvidedNull:
309
		case IProblem.IllegalReturnNullityRedefinition:
310
		case IProblem.IllegalRedefinitionToNonNullParameter:
311
		case IProblem.IllegalDefinitionToNonNullParameter:
312
		case IProblem.ParameterLackingNonNullAnnotation:
313
		case IProblem.ParameterLackingNullableAnnotation:
314
		case IProblem.CannotImplementIncompatibleNullness:
315
			return CompilerOptions.NullSpecViolation;
316
317
		case IProblem.RequiredNonNullButProvidedPotentialNull:
318
			return CompilerOptions.PotentialNullSpecViolation;
319
		case IProblem.RequiredNonNullButProvidedUnknown:
320
			return CompilerOptions.NullSpecInsufficientInfo;
321
		case IProblem.RedundantNullAnnotation:
322
		case IProblem.RedundantNullDefaultAnnotation:
323
		case IProblem.RedundantNullDefaultAnnotationPackage:
324
		case IProblem.RedundantNullDefaultAnnotationType:
325
		case IProblem.RedundantNullDefaultAnnotationMethod:
326
			return CompilerOptions.RedundantNullAnnotation;
297
327
298
		case IProblem.BoxingConversion :
328
		case IProblem.BoxingConversion :
299
		case IProblem.UnboxingConversion :
329
		case IProblem.UnboxingConversion :
Lines 426-431 Link Here
426
			
456
			
427
		case IProblem.MethodCanBePotentiallyStatic:
457
		case IProblem.MethodCanBePotentiallyStatic:
428
			return CompilerOptions.MethodCanBePotentiallyStatic;
458
			return CompilerOptions.MethodCanBePotentiallyStatic;
459
460
		case IProblem.UnclosedCloseable:
461
		case IProblem.UnclosedCloseableAtExit:
462
			return CompilerOptions.UnclosedCloseable;
463
		case IProblem.PotentiallyUnclosedCloseable:
464
		case IProblem.PotentiallyUnclosedCloseableAtExit:
465
			return CompilerOptions.PotentiallyUnclosedCloseable;
466
		case IProblem.ExplicitlyClosedAutoCloseable:
467
			return CompilerOptions.ExplicitlyClosedAutoCloseable;
429
				
468
				
430
		case IProblem.RedundantSpecificationOfTypeArguments:
469
		case IProblem.RedundantSpecificationOfTypeArguments:
431
			return CompilerOptions.RedundantSpecificationOfTypeArguments;
470
			return CompilerOptions.RedundantSpecificationOfTypeArguments;
Lines 461-466 Link Here
461
			case CompilerOptions.ParameterAssignment :
500
			case CompilerOptions.ParameterAssignment :
462
			case CompilerOptions.MethodCanBeStatic :
501
			case CompilerOptions.MethodCanBeStatic :
463
			case CompilerOptions.MethodCanBePotentiallyStatic :
502
			case CompilerOptions.MethodCanBePotentiallyStatic :
503
			case CompilerOptions.ExplicitlyClosedAutoCloseable :
464
				return CategorizedProblem.CAT_CODE_STYLE;
504
				return CategorizedProblem.CAT_CODE_STYLE;
465
505
466
			case CompilerOptions.MaskedCatchBlock :
506
			case CompilerOptions.MaskedCatchBlock :
Lines 482-487 Link Here
482
			case CompilerOptions.ShouldImplementHashcode :
522
			case CompilerOptions.ShouldImplementHashcode :
483
			case CompilerOptions.DeadCode :
523
			case CompilerOptions.DeadCode :
484
			case CompilerOptions.UnusedObjectAllocation :
524
			case CompilerOptions.UnusedObjectAllocation :
525
			case CompilerOptions.UnclosedCloseable :
526
			case CompilerOptions.PotentiallyUnclosedCloseable :
485
				return CategorizedProblem.CAT_POTENTIAL_PROGRAMMING_PROBLEM;
527
				return CategorizedProblem.CAT_POTENTIAL_PROGRAMMING_PROBLEM;
486
			
528
			
487
			case CompilerOptions.OverriddenPackageDefaultMethod :
529
			case CompilerOptions.OverriddenPackageDefaultMethod :
Lines 527-533 Link Here
527
			case CompilerOptions.ForbiddenReference :
569
			case CompilerOptions.ForbiddenReference :
528
			case CompilerOptions.DiscouragedReference :
570
			case CompilerOptions.DiscouragedReference :
529
				return CategorizedProblem.CAT_RESTRICTION;
571
				return CategorizedProblem.CAT_RESTRICTION;
530
			
572
573
			case CompilerOptions.NullSpecViolation :
574
			case CompilerOptions.PotentialNullSpecViolation :
575
			case CompilerOptions.NullSpecInsufficientInfo :
576
				return CategorizedProblem.CAT_POTENTIAL_PROGRAMMING_PROBLEM;
577
			case CompilerOptions.RedundantNullAnnotation :
578
				return CategorizedProblem.CAT_UNNECESSARY_CODE;
579
531
			default:
580
			default:
532
				break categorizeOnIrritant;
581
				break categorizeOnIrritant;
533
		}
582
		}
Lines 2849-2860 Link Here
2849
					expression.sourceStart,
2898
					expression.sourceStart,
2850
					expression.sourceEnd);
2899
					expression.sourceEnd);
2851
		} else {
2900
		} else {
2852
			this.handle(
2901
			if (this.options.sourceLevel < ClassFileConstants.JDK1_5 && testType.isEnum()) {
2853
				IProblem.IncorrectSwitchType,
2902
				this.handle(
2854
				new String[] {new String(testType.readableName())},
2903
						IProblem.SwitchOnEnumNotBelow15,
2855
				new String[] {new String(testType.shortReadableName())},
2904
						new String[] {new String(testType.readableName())},
2856
				expression.sourceStart,
2905
						new String[] {new String(testType.shortReadableName())},
2857
				expression.sourceEnd);
2906
						expression.sourceStart,
2907
						expression.sourceEnd);
2908
			} else {
2909
				this.handle(
2910
						IProblem.IncorrectSwitchType,
2911
						new String[] {new String(testType.readableName())},
2912
						new String[] {new String(testType.shortReadableName())},
2913
						expression.sourceStart,
2914
						expression.sourceEnd);
2915
			}
2858
		}
2916
		}
2859
	} else {
2917
	} else {
2860
		this.handle(
2918
		this.handle(
Lines 3214-3219 Link Here
3214
				        typesAsString(shownConstructor, true),
3272
				        typesAsString(shownConstructor, true),
3215
				        new String(shownConstructor.declaringClass.shortReadableName()),
3273
				        new String(shownConstructor.declaringClass.shortReadableName()),
3216
				        typesAsString(targetConstructor, true) },
3274
				        typesAsString(targetConstructor, true) },
3275
				sourceStart,
3276
				sourceEnd);
3277
			return;
3278
		case ProblemReasons.VarargsElementTypeNotVisible :
3279
			problemConstructor = (ProblemMethodBinding) targetConstructor;
3280
			shownConstructor = problemConstructor.closestMatch;
3281
			TypeBinding varargsElementType = shownConstructor.parameters[shownConstructor.parameters.length - 1].leafComponentType();
3282
			this.handle(
3283
				IProblem.VarargsElementTypeNotVisibleForConstructor,
3284
				new String[] {
3285
						new String(shownConstructor.declaringClass.sourceName()),
3286
						typesAsString(shownConstructor, false),
3287
						new String(shownConstructor.declaringClass.readableName()),
3288
						new String(varargsElementType.readableName())
3289
				},
3290
				new String[] {
3291
						new String(shownConstructor.declaringClass.sourceName()),
3292
						typesAsString(shownConstructor, true),
3293
						new String(shownConstructor.declaringClass.shortReadableName()),
3294
						new String(varargsElementType.shortReadableName())
3295
				},
3217
				sourceStart,
3296
				sourceStart,
3218
				sourceEnd);
3297
				sourceEnd);
3219
			return;
3298
			return;
Lines 3700-3705 Link Here
3700
				        typesAsString(shownMethod, true),
3779
				        typesAsString(shownMethod, true),
3701
				        new String(shownMethod.declaringClass.shortReadableName()),
3780
				        new String(shownMethod.declaringClass.shortReadableName()),
3702
				        typesAsString(method, true) },
3781
				        typesAsString(method, true) },
3782
				(int) (messageSend.nameSourcePosition >>> 32),
3783
				(int) messageSend.nameSourcePosition);
3784
			return;
3785
		case ProblemReasons.VarargsElementTypeNotVisible: // https://bugs.eclipse.org/bugs/show_bug.cgi?id=346042
3786
			problemMethod = (ProblemMethodBinding) method;
3787
			if (problemMethod.closestMatch != null) {
3788
			    shownMethod = problemMethod.closestMatch.original();
3789
		    }
3790
			TypeBinding varargsElementType = shownMethod.parameters[shownMethod.parameters.length - 1].leafComponentType();
3791
			this.handle(
3792
				IProblem.VarargsElementTypeNotVisible,
3793
				new String[] {
3794
				        new String(shownMethod.selector),
3795
				        typesAsString(shownMethod, false),
3796
				        new String(shownMethod.declaringClass.readableName()),
3797
				        new String(varargsElementType.readableName())
3798
				},
3799
				new String[] {
3800
				        new String(shownMethod.selector),
3801
				        typesAsString(shownMethod, true),
3802
				        new String(shownMethod.declaringClass.shortReadableName()),
3803
				        new String(varargsElementType.shortReadableName())
3804
				},
3703
				(int) (messageSend.nameSourcePosition >>> 32),
3805
				(int) (messageSend.nameSourcePosition >>> 32),
3704
				(int) messageSend.nameSourcePosition);
3806
				(int) messageSend.nameSourcePosition);
3705
			return;
3807
			return;
Lines 7497-7503 Link Here
7497
7599
7498
	int severity = computeSeverity(IProblem.UnusedPrivateConstructor);
7600
	int severity = computeSeverity(IProblem.UnusedPrivateConstructor);
7499
	if (severity == ProblemSeverities.Ignore) return;
7601
	if (severity == ProblemSeverities.Ignore) return;
7500
7602
	
7603
	if (excludeDueToAnnotation(constructorDecl.annotations)) return;
7604
	
7501
	MethodBinding constructor = constructorDecl.binding;
7605
	MethodBinding constructor = constructorDecl.binding;
7502
	this.handle(
7606
	this.handle(
7503
			IProblem.UnusedPrivateConstructor,
7607
			IProblem.UnusedPrivateConstructor,
Lines 7543-7548 Link Here
7543
			}
7647
			}
7544
		}
7648
		}
7545
	}
7649
	}
7650
	if (excludeDueToAnnotation(fieldDecl.annotations)) return;
7546
	this.handle(
7651
	this.handle(
7547
			IProblem.UnusedPrivateField,
7652
			IProblem.UnusedPrivateField,
7548
		new String[] {
7653
		new String[] {
Lines 7596-7605 Link Here
7596
			&& CharOperation.equals(method.selector, TypeConstants.WRITEREPLACE)) {
7701
			&& CharOperation.equals(method.selector, TypeConstants.WRITEREPLACE)) {
7597
		return;
7702
		return;
7598
	}
7703
	}
7599
	if ((method.tagBits & (TagBits.AnnotationPostConstruct | TagBits.AnnotationPreDestroy)) != 0) {
7704
	if (excludeDueToAnnotation(methodDecl.annotations)) return;
7600
		// PostConstruct and PreDestroy method are ignored
7705
	
7601
		return;
7602
	}
7603
	this.handle(
7706
	this.handle(
7604
			IProblem.UnusedPrivateMethod,
7707
			IProblem.UnusedPrivateMethod,
7605
		new String[] {
7708
		new String[] {
Lines 7616-7625 Link Here
7616
		methodDecl.sourceStart,
7719
		methodDecl.sourceStart,
7617
		methodDecl.sourceEnd);
7720
		methodDecl.sourceEnd);
7618
}
7721
}
7722
7723
/**
7724
 * Returns true if a private member should not be warned as unused if
7725
 * annotated with a non-standard annotation.
7726
 * https://bugs.eclipse.org/bugs/show_bug.cgi?id=365437
7727
 */
7728
private boolean excludeDueToAnnotation(Annotation[] annotations) {
7729
	int annotationsLen = 0;
7730
	if (annotations != null) {
7731
		annotationsLen = annotations.length;
7732
	} else {
7733
		return false;
7734
	}
7735
	if (annotationsLen == 0) return false;
7736
	for (int i = 0; i < annotationsLen; i++) {
7737
		TypeBinding resolvedType = annotations[i].resolvedType;
7738
		if (resolvedType != null) {
7739
			switch (resolvedType.id) {
7740
				case TypeIds.T_JavaLangSuppressWarnings:
7741
				case TypeIds.T_JavaLangDeprecated:
7742
				case TypeIds.T_JavaLangSafeVarargs:
7743
				case TypeIds.T_ConfiguredAnnotationNonNull:
7744
				case TypeIds.T_ConfiguredAnnotationNullable:
7745
				case TypeIds.T_ConfiguredAnnotationNonNullByDefault:
7746
					break;
7747
				default:
7748
					// non-standard annotation found, don't warn
7749
					return true;
7750
			}
7751
		}
7752
	}
7753
	return false;
7754
}
7619
public void unusedPrivateType(TypeDeclaration typeDecl) {
7755
public void unusedPrivateType(TypeDeclaration typeDecl) {
7620
	int severity = computeSeverity(IProblem.UnusedPrivateType);
7756
	int severity = computeSeverity(IProblem.UnusedPrivateType);
7621
	if (severity == ProblemSeverities.Ignore) return;
7757
	if (severity == ProblemSeverities.Ignore) return;
7622
7758
	if (excludeDueToAnnotation(typeDecl.annotations)) return;
7623
	ReferenceBinding type = typeDecl.binding;
7759
	ReferenceBinding type = typeDecl.binding;
7624
	this.handle(
7760
	this.handle(
7625
			IProblem.UnusedPrivateType,
7761
			IProblem.UnusedPrivateType,
Lines 7931-7934 Link Here
7931
			location.sourceEnd);
8067
			location.sourceEnd);
7932
    }
8068
    }
7933
}
8069
}
7934
}
8070
public void potentiallyUnclosedCloseable(FakedTrackingVariable trackVar, ASTNode location) {
8071
	String[] args = { String.valueOf(trackVar.name) };
8072
	if (location == null) {
8073
		this.handle(
8074
			IProblem.PotentiallyUnclosedCloseable,
8075
			args,
8076
			args,
8077
			trackVar.sourceStart,
8078
			trackVar.sourceEnd);
8079
	} else {
8080
		this.handle(
8081
			IProblem.PotentiallyUnclosedCloseableAtExit,
8082
			args,
8083
			args,
8084
			location.sourceStart,
8085
			location.sourceEnd);
8086
	}
8087
}
8088
public void unclosedCloseable(FakedTrackingVariable trackVar, ASTNode location) {
8089
	String[] args = { String.valueOf(trackVar.name) };
8090
	if (location == null) {
8091
		this.handle(
8092
			IProblem.UnclosedCloseable,
8093
			args,
8094
			args,
8095
			trackVar.sourceStart,
8096
			trackVar.sourceEnd);
8097
	} else {
8098
		this.handle(
8099
			IProblem.UnclosedCloseableAtExit,
8100
			args,
8101
			args,
8102
			location.sourceStart,
8103
			location.sourceEnd);
8104
	}
8105
}
8106
public void explicitlyClosedAutoCloseable(FakedTrackingVariable trackVar) {
8107
	String[] args = { String.valueOf(trackVar.name) };
8108
	this.handle(
8109
		IProblem.ExplicitlyClosedAutoCloseable,
8110
		args,
8111
		args,
8112
		trackVar.sourceStart,
8113
		trackVar.sourceEnd);	
8114
}
8115
8116
public void nullityMismatch(Expression expression, TypeBinding requiredType, int nullStatus, char[][] annotationName) {
8117
	int problemId = IProblem.RequiredNonNullButProvidedUnknown;
8118
	if ((nullStatus & FlowInfo.NULL) != 0)
8119
		problemId = IProblem.RequiredNonNullButProvidedNull;
8120
	if ((nullStatus & FlowInfo.POTENTIALLY_NULL) != 0)
8121
		problemId = IProblem.RequiredNonNullButProvidedPotentialNull;
8122
	String[] arguments = new String[] {
8123
			String.valueOf(CharOperation.concatWith(annotationName, '.')),
8124
			String.valueOf(requiredType.readableName())
8125
	};
8126
	String[] argumentsShort = new String[] {
8127
			String.valueOf(annotationName[annotationName.length-1]),
8128
			String.valueOf(requiredType.shortReadableName())
8129
	};
8130
	this.handle(
8131
		problemId,
8132
		arguments,
8133
		argumentsShort,
8134
		expression.sourceStart,
8135
		expression.sourceEnd);
8136
}
8137
public void illegalRedefinitionToNonNullParameter(Argument argument, ReferenceBinding declaringClass, char[][] inheritedAnnotationName) {
8138
	int sourceStart = argument.type.sourceStart;
8139
	if (argument.annotations != null) {
8140
		for (int i=0; i<argument.annotations.length; i++) {
8141
			Annotation annotation = argument.annotations[i];
8142
			if (   annotation.resolvedType.id == TypeIds.T_ConfiguredAnnotationNullable
8143
				|| annotation.resolvedType.id == TypeIds.T_ConfiguredAnnotationNonNull)
8144
			{
8145
				sourceStart = annotation.sourceStart;
8146
				break;
8147
			}
8148
		}
8149
	}
8150
	if (inheritedAnnotationName == null) {
8151
		this.handle(
8152
			IProblem.IllegalDefinitionToNonNullParameter, 
8153
			new String[] { new String(argument.name), new String(declaringClass.readableName()) },
8154
			new String[] { new String(argument.name), new String(declaringClass.shortReadableName()) },
8155
			sourceStart,
8156
			argument.type.sourceEnd);
8157
	} else {
8158
		this.handle(
8159
			IProblem.IllegalRedefinitionToNonNullParameter, 
8160
			new String[] { new String(argument.name), new String(declaringClass.readableName()), CharOperation.toString(inheritedAnnotationName)},
8161
			new String[] { new String(argument.name), new String(declaringClass.shortReadableName()), new String(inheritedAnnotationName[inheritedAnnotationName.length-1])},
8162
			sourceStart,
8163
			argument.type.sourceEnd);
8164
	}
8165
}
8166
public void parameterLackingNullAnnotation(Argument argument, ReferenceBinding declaringClass, boolean needNonNull, char[][] inheritedAnnotationName) {
8167
	this.handle(
8168
		needNonNull ? IProblem.ParameterLackingNonNullAnnotation : IProblem.ParameterLackingNullableAnnotation, 
8169
		new String[] { new String(argument.name), new String(declaringClass.readableName()), CharOperation.toString(inheritedAnnotationName)},
8170
		new String[] { new String(argument.name), new String(declaringClass.shortReadableName()), new String(inheritedAnnotationName[inheritedAnnotationName.length-1])},
8171
		argument.type.sourceStart,
8172
		argument.type.sourceEnd);
8173
}
8174
public void illegalReturnRedefinition(AbstractMethodDeclaration abstractMethodDecl,
8175
									  MethodBinding inheritedMethod, char[][] nonNullAnnotationName)
8176
{
8177
	MethodDeclaration methodDecl = (MethodDeclaration) abstractMethodDecl;
8178
	StringBuffer methodSignature = new StringBuffer();
8179
	methodSignature
8180
		.append(inheritedMethod.declaringClass.readableName())
8181
		.append('.')
8182
		.append(inheritedMethod.readableName());
8183
8184
	StringBuffer shortSignature = new StringBuffer();
8185
	shortSignature
8186
		.append(inheritedMethod.declaringClass.shortReadableName())
8187
		.append('.')
8188
		.append(inheritedMethod.shortReadableName());
8189
	int sourceStart = methodDecl.returnType.sourceStart;
8190
	Annotation[] annotations = methodDecl.annotations;
8191
	Annotation annotation = findAnnotation(annotations, TypeIds.T_ConfiguredAnnotationNullable);
8192
	if (annotation != null) {
8193
		sourceStart = annotation.sourceStart;
8194
	}
8195
	this.handle(
8196
		IProblem.IllegalReturnNullityRedefinition, 
8197
		new String[] { methodSignature.toString(), CharOperation.toString(nonNullAnnotationName)},
8198
		new String[] { shortSignature.toString(), new String(nonNullAnnotationName[nonNullAnnotationName.length-1])},
8199
		sourceStart,
8200
		methodDecl.returnType.sourceEnd);
8201
}
8202
public void messageSendPotentialNullReference(MethodBinding method, ASTNode location) {
8203
	String[] arguments = new String[] {new String(method.readableName())};
8204
	this.handle(
8205
		IProblem.PotentialNullMessageSendReference,
8206
		arguments,
8207
		arguments,
8208
		location.sourceStart,
8209
		location.sourceEnd);
8210
}
8211
public void messageSendRedundantCheckOnNonNull(MethodBinding method, ASTNode location) {
8212
	String[] arguments = new String[] {new String(method.readableName())  };
8213
	this.handle(
8214
		IProblem.RedundantNullCheckOnNonNullMessageSend,
8215
		arguments,
8216
		arguments,
8217
		location.sourceStart,
8218
		location.sourceEnd);
8219
}
8220
8221
public void cannotImplementIncompatibleNullness(MethodBinding currentMethod, MethodBinding inheritedMethod) {
8222
	int sourceStart = 0, sourceEnd = 0;
8223
	if (this.referenceContext instanceof TypeDeclaration) {
8224
		sourceStart = ((TypeDeclaration) this.referenceContext).sourceStart;
8225
		sourceEnd =   ((TypeDeclaration) this.referenceContext).sourceEnd;
8226
	}
8227
	String[] problemArguments = {
8228
			new String(currentMethod.readableName()),
8229
			new String(currentMethod.declaringClass.readableName()),
8230
			new String(inheritedMethod.declaringClass.readableName())
8231
		};
8232
	String[] messageArguments = {
8233
			new String(currentMethod.shortReadableName()),
8234
			new String(currentMethod.declaringClass.shortReadableName()),
8235
			new String(inheritedMethod.declaringClass.shortReadableName())
8236
		};
8237
	this.handle(
8238
			IProblem.CannotImplementIncompatibleNullness,
8239
			problemArguments,
8240
			messageArguments,
8241
			sourceStart,
8242
			sourceEnd);
8243
}
8244
8245
public void nullAnnotationIsRedundant(AbstractMethodDeclaration sourceMethod, int i) {
8246
	int sourceStart, sourceEnd;
8247
	if (i == -1) {
8248
		MethodDeclaration methodDecl = (MethodDeclaration) sourceMethod;
8249
		Annotation annotation = findAnnotation(methodDecl.annotations, TypeIds.T_ConfiguredAnnotationNonNull);
8250
		sourceStart = annotation != null ? annotation.sourceStart : methodDecl.returnType.sourceStart;
8251
		sourceEnd = methodDecl.returnType.sourceEnd;
8252
	} else {
8253
		Argument arg = sourceMethod.arguments[i];
8254
		sourceStart = arg.declarationSourceStart;
8255
		sourceEnd = arg.sourceEnd;
8256
	}
8257
	this.handle(IProblem.RedundantNullAnnotation, ProblemHandler.NoArgument, ProblemHandler.NoArgument, sourceStart, sourceEnd);
8258
}
8259
8260
public void nullDefaultAnnotationIsRedundant(ASTNode location, Annotation[] annotations, Binding outer) {
8261
	Annotation annotation = findAnnotation(annotations, TypeIds.T_ConfiguredAnnotationNonNullByDefault);
8262
	int start = annotation != null ? annotation.sourceStart : location.sourceStart;
8263
	int end = annotation != null ? annotation.sourceEnd : location.sourceStart;
8264
	String[] args = NoArgument;
8265
	String[] shortArgs = NoArgument;
8266
	if (outer != null) {
8267
		args = new String[] { new String(outer.readableName()) };
8268
		shortArgs = new String[] { new String(outer.shortReadableName()) };
8269
	}
8270
	int problemId = IProblem.RedundantNullDefaultAnnotation;
8271
	if (outer instanceof PackageBinding) {
8272
		problemId = IProblem.RedundantNullDefaultAnnotationPackage;
8273
	} else if (outer instanceof ReferenceBinding) {
8274
		problemId = IProblem.RedundantNullDefaultAnnotationType;
8275
	} else if (outer instanceof MethodBinding) {
8276
		problemId = IProblem.RedundantNullDefaultAnnotationMethod;
8277
	}
8278
	this.handle(problemId, args, shortArgs, start, end);
8279
}
8280
8281
public void contradictoryNullAnnotations(Annotation annotation) {
8282
	// when this error is triggered we can safely assume that both annotations have been configured
8283
	char[][] nonNullAnnotationName = this.options.nonNullAnnotationName;
8284
	char[][] nullableAnnotationName = this.options.nullableAnnotationName;
8285
	String[] arguments = {
8286
		new String(CharOperation.concatWith(nonNullAnnotationName, '.')),
8287
		new String(CharOperation.concatWith(nullableAnnotationName, '.'))
8288
	};
8289
	String[] shortArguments = {
8290
			new String(nonNullAnnotationName[nonNullAnnotationName.length-1]),
8291
			new String(nullableAnnotationName[nullableAnnotationName.length-1])
8292
		};
8293
	this.handle(IProblem.ContradictoryNullAnnotations, arguments, shortArguments, annotation.sourceStart, annotation.sourceEnd);
8294
}
8295
8296
public void illegalAnnotationForBaseType(TypeReference type, Annotation[] annotations, char[] annotationName, long nullAnnotationTagBit)
8297
{
8298
	int typeId = (nullAnnotationTagBit == TagBits.AnnotationNullable) 
8299
			? TypeIds.T_ConfiguredAnnotationNullable : TypeIds.T_ConfiguredAnnotationNonNull;
8300
	String[] args = new String[] { new String(annotationName), new String(type.getLastToken()) };
8301
	Annotation annotation = findAnnotation(annotations, typeId);
8302
	int start = annotation != null ? annotation.sourceStart : type.sourceStart;
8303
	this.handle(IProblem.IllegalAnnotationForBaseType,
8304
			args,
8305
			args,
8306
			start,
8307
			type.sourceEnd);
8308
}
8309
8310
private Annotation findAnnotation(Annotation[] annotations, int typeId) {
8311
	if (annotations != null) {
8312
		// should have a @NonNull/@Nullable annotation, search for it:
8313
		int length = annotations.length;
8314
		for (int j=0; j<length; j++) {
8315
			if (annotations[j].resolvedType != null && annotations[j].resolvedType.id == typeId) {
8316
				return annotations[j];
8317
			}
8318
		}
8319
	}
8320
	return null;
8321
}
8322
}
(-)a/org.eclipse.jdt.core/compiler/org/eclipse/jdt/internal/compiler/problem/messages.properties (-3 / +37 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
14
#							bug 186342 - [compiler][null] Using annotations for null checking
15
#							bug 365662 - [compiler][null] warn on contradictory and redundant null annotations
16
#							bug 365531 - [compiler][null] investigate alternative strategy for internally encoding nullness defaults
12
###############################################################################
17
###############################################################################
13
0 = {0}
18
0 = {0}
14
1 = super cannot be used in java.lang.Object
19
1 = super cannot be used in java.lang.Object
Lines 143-149 Link Here
143
162 = Cannot return from within an initializer
148
162 = Cannot return from within an initializer
144
163 = Initializer does not complete normally
149
163 = Initializer does not complete normally
145
164 = Expression must return a value
150
164 = Expression must return a value
146
165 = Unreachable catch block for {0}. Only more specific exceptions are thrown and handled by previous catch block(s).
151
165 = Unreachable catch block for {0}. Only more specific exceptions are thrown and they are handled by previous catch block(s).
147
166 = The default case is already defined
152
166 = The default case is already defined
148
167 = Unreachable catch block for {0}. This exception is never thrown from the try statement body
153
167 = Unreachable catch block for {0}. This exception is never thrown from the try statement body
149
168 = Unhandled exception type {0}
154
168 = Unhandled exception type {0}
Lines 287-293 Link Here
287
343 = Illegal modifier for the interface field {0}.{1}; only public, static & final are permitted
292
343 = Illegal modifier for the interface field {0}.{1}; only public, static & final are permitted
288
344 = The field {0} can only set one of public / protected / private
293
344 = The field {0} can only set one of public / protected / private
289
345 = The field {0} can be either final or volatile, not both
294
345 = The field {0} can be either final or volatile, not both
290
346 = The field {0} cannot be declared static; static fields can only be declared in static or top level types
295
346 = The field {0} cannot be declared static in a non-static inner type, unless initialized with a constant expression
291
296
292
###[obsolete] 350 = {2} cannot be resolved (or is not a valid type) for the field {1}.{0}
297
###[obsolete] 350 = {2} cannot be resolved (or is not a valid type) for the field {1}.{0}
293
###[obsolete] 351 = The type {2} is not visible for the field {1}.{0}
298
###[obsolete] 351 = The type {2} is not visible for the field {1}.{0}
Lines 615-620 Link Here
615
804 = @SafeVarargs annotation cannot be applied to fixed arity method {0}
620
804 = @SafeVarargs annotation cannot be applied to fixed arity method {0}
616
805 = @SafeVarargs annotation cannot be applied to non-final instance method {0}
621
805 = @SafeVarargs annotation cannot be applied to non-final instance method {0}
617
806 = Type safety: Potential heap pollution via varargs parameter {0}
622
806 = Type safety: Potential heap pollution via varargs parameter {0}
623
807 = The method {0}({1}) of type {2} is not applicable as the formal varargs element type {3} is not accessible here
624
808 = The constructor {0}({1}) of type {2} is not applicable as the formal varargs element type {3} is not accessible here
618
625
619
### GENERIC JAVADOC
626
### GENERIC JAVADOC
620
850 = Bound mismatch: The generic method {0}({1}) of type {2} is not applicable for the arguments ({3}). The inferred type {4} is not a valid substitute for the bounded parameter <{5} extends {6}>
627
850 = Bound mismatch: The generic method {0}({1}) of type {2} is not applicable for the arguments ({3}). The inferred type {4} is not a valid substitute for the bounded parameter <{5} extends {6}>
Lines 644-649 Link Here
644
882 = Unhandled exception type {0} thrown by automatic close() invocation on {1}
651
882 = Unhandled exception type {0} thrown by automatic close() invocation on {1}
645
883 = '<>' operator is not allowed for source level below 1.7
652
883 = '<>' operator is not allowed for source level below 1.7
646
884 = Redundant specification of type arguments <{0}>
653
884 = Redundant specification of type arguments <{0}>
654
885 = Potential resource leak: ''{0}'' may not be closed
655
886 = Potential resource leak: ''{0}'' may not be closed at this location
656
887 = Resource leak: ''{0}'' is never closed
657
888 = Resource leak: ''{0}'' is not closed at this location
658
889 = Resource ''{0}'' should be managed by try-with-resource
659
890 = Cannot switch on an enum value for source level below 1.5. Only convertible int values are permitted
660
661
### NULL ANNOTATIONS
662
910 = Type mismatch: required ''@{0} {1}'' but the provided value is null
663
911 = Type mismatch: required ''@{0} {1}'' but the provided value can be null
664
912 = Potential type mismatch: required ''@{0} {1}'' but nullness of the provided value is unknown
665
#913 removed
666
914 = The return type is incompatible with the @{1} return from {0}
667
915 = Illegal redefinition of parameter {0}, inherited method from {1} declares this parameter as @{2}
668
916 = Illegal redefinition of parameter {0}, inherited method from {1} does not constrain this parameter
669
917 = Missing non-null annotation: inherited method from {1} declares this parameter as @{2}
670
918 = Missing nullable annotation: inherited method from {1} declares this parameter as @{2}
671
919 = Potential null pointer access: The method {0} may return null
672
920 = Redundant null check: The method {0} cannot return null
673
921 = The method {0} from {1} cannot implement the corresponding method from {2} due to incompatible nullness constraints
674
922 = The nullness annotation is redundant with a default that applies to this location
675
923 = The nullness annotation @{0} is not applicable for the primitive type {1}
676
925 = Nullness default is redundant with the global default
677
926 = Nullness default is redundant with a default specified for the enclosing package {0}
678
927 = Nullness default is redundant with a default specified for the enclosing type {0}
679
928 = Nullness default is redundant with a default specified for the enclosing method {0}
680
929 = Contradictory null specification; only one of @{0} and @{1} can be specified at any location
647
681
648
### ELABORATIONS
682
### ELABORATIONS
649
## Access restrictions
683
## Access restrictions
(-)a/org.eclipse.jdt.core/dom/org/eclipse/jdt/core/dom/AST.java (-24 / +19 lines)
Lines 1-5 Link Here
1
/*******************************************************************************
1
/*******************************************************************************
2
 * Copyright (c) 2000, 2011 IBM Corporation and others.
2
 * Copyright (c) 2000, 2012 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 102-107 Link Here
102
102
103
	/**
103
	/**
104
	 * Constant for indicating the AST API that handles JLS2.
104
	 * Constant for indicating the AST API that handles JLS2.
105
	 * <p>
105
	 * This API is capable of handling all constructs
106
	 * This API is capable of handling all constructs
106
	 * in the Java language as described in the Java Language
107
	 * in the Java language as described in the Java Language
107
     * Specification, Second Edition (JLS2).
108
     * Specification, Second Edition (JLS2).
Lines 109-114 Link Here
109
     * Java language, and the JLS2 API can be used to manipulate
110
     * Java language, and the JLS2 API can be used to manipulate
110
     * programs written in all versions of the Java language
111
     * programs written in all versions of the Java language
111
     * up to and including J2SE 1.4.
112
     * up to and including J2SE 1.4.
113
     * </p>
112
     *
114
     *
113
	 * @since 3.0
115
	 * @since 3.0
114
	 * @deprecated Clients should use the {@link #JLS4} AST API instead.
116
	 * @deprecated Clients should use the {@link #JLS4} AST API instead.
Lines 124-129 Link Here
124
	
126
	
125
	/**
127
	/**
126
	 * Constant for indicating the AST API that handles JLS3.
128
	 * Constant for indicating the AST API that handles JLS3.
129
	 * <p>
127
	 * This API is capable of handling all constructs in the
130
	 * This API is capable of handling all constructs in the
128
	 * Java language as described in the Java Language
131
	 * Java language as described in the Java Language
129
	 * Specification, Third Edition (JLS3).
132
	 * Specification, Third Edition (JLS3).
Lines 131-151 Link Here
131
     * Java language, and the JLS3 API can be used to manipulate
134
     * Java language, and the JLS3 API can be used to manipulate
132
     * programs written in all versions of the Java language
135
     * programs written in all versions of the Java language
133
     * up to and including J2SE 5 (aka JDK 1.5).
136
     * up to and including J2SE 5 (aka JDK 1.5).
137
     * </p>
134
     *
138
     *
135
	 * @since 3.1
139
	 * @since 3.1
136
	 */
140
	 */
137
	public static final int JLS3 = 3;
141
	public static final int JLS3 = 3;
138
142
139
	/**
143
	/**
140
	 * Constant for indicating the AST API that handles JLS4.
144
	 * Constant for indicating the AST API that handles JLS4 (aka JLS7).
145
	 * <p>
141
	 * This API is capable of handling all constructs in the
146
	 * This API is capable of handling all constructs in the
142
	 * Java language as described in the Java Language
147
	 * Java language as described in the Java Language
143
	 * Specification, Third Edition (JLS3) plus all the new language
148
	 * Specification, Java SE 7 Edition (JLS7) as specified by JSR336.
144
	 * features described in the JSR334.
145
	 * JLS4 is a superset of all earlier versions of the
149
	 * JLS4 is a superset of all earlier versions of the
146
	 * Java language, and the JLS4 API can be used to manipulate
150
	 * Java language, and the JLS4 API can be used to manipulate
147
	 * programs written in all versions of the Java language
151
	 * programs written in all versions of the Java language
148
	 * up to and including J2SE 7 (aka JDK 1.7).
152
	 * up to and including Java SE 7 (aka JDK 1.7).
153
	 * </p>
149
	 *
154
	 *
150
	 * @since 3.7.1
155
	 * @since 3.7.1
151
	 */
156
	 */
Lines 163-169 Link Here
163
	 * into a compilation unit. This method is not intended to be called by clients.
168
	 * into a compilation unit. This method is not intended to be called by clients.
164
	 * </p>
169
	 * </p>
165
	 *
170
	 *
166
 	 * @param level the API level; one of the LEVEL constants
171
 	 * @param level the API level; one of the <code>JLS*</code> level constants
167
	 * @param compilationUnitDeclaration an internal AST node for a compilation unit declaration
172
	 * @param compilationUnitDeclaration an internal AST node for a compilation unit declaration
168
	 * @param source the string of the Java compilation unit
173
	 * @param source the string of the Java compilation unit
169
	 * @param options compiler options
174
	 * @param options compiler options
Lines 194-200 Link Here
194
	 * into a compilation unit. This method is not intended to be called by clients.
199
	 * into a compilation unit. This method is not intended to be called by clients.
195
	 * </p>
200
	 * </p>
196
	 *
201
	 *
197
 	 * @param level the API level; one of the LEVEL constants
202
 	 * @param level the API level; one of the <code>JLS*</code> level constants
198
	 * @param compilationUnitDeclaration an internal AST node for a compilation unit declaration
203
	 * @param compilationUnitDeclaration an internal AST node for a compilation unit declaration
199
	 * @param options compiler options
204
	 * @param options compiler options
200
	 * @param workingCopy the working copy that the AST is created from
205
	 * @param workingCopy the working copy that the AST is created from
Lines 245-255 Link Here
245
     * AST level in all cases, even when dealing with source of earlier JDK versions like 1.3 or 1.4.
250
     * AST level in all cases, even when dealing with source of earlier JDK versions like 1.3 or 1.4.
246
     * </p>
251
     * </p>
247
     *
252
     *
248
 	 * @param level the API level; one of the LEVEL constants
253
 	 * @param level the API level; one of the <code>JLS*</code> level constants
249
	 * @return new AST instance following the specified set of API rules.
254
	 * @return new AST instance following the specified set of API rules.
250
	 * @exception IllegalArgumentException if:
255
	 * @exception IllegalArgumentException if:
251
	 * <ul>
256
	 * <ul>
252
	 * <li>the API level is not one of the LEVEL constants</li>
257
	 * <li>the API level is not one of the <code>JLS*</code> level constants</li>
253
	 * </ul>
258
	 * </ul>
254
     * @since 3.0
259
     * @since 3.0
255
	 */
260
	 */
Lines 632-638 Link Here
632
	 * Creates a new Java abstract syntax tree
637
	 * Creates a new Java abstract syntax tree
633
     * (AST) following the specified set of API rules.
638
     * (AST) following the specified set of API rules.
634
     *
639
     *
635
 	 * @param level the API level; one of the JLS* level constants
640
 	 * @param level the API level; one of the <code>JLS*</code> level constants
636
     * @since 3.0
641
     * @since 3.0
637
	 */
642
	 */
638
	private AST(int level) {
643
	private AST(int level) {
Lines 727-733 Link Here
727
	/**
732
	/**
728
	 * Return the API level supported by this AST.
733
	 * Return the API level supported by this AST.
729
	 *
734
	 *
730
	 * @return level the API level; one of the <code>JLS*</code>LEVEL
735
	 * @return level the API level; one of the <code>JLS*</code> level constants
731
     * declared on <code>AST</code>; assume this set is open-ended
736
     * declared on <code>AST</code>; assume this set is open-ended
732
     * @since 3.0
737
     * @since 3.0
733
	 */
738
	 */
Lines 1060-1066 Link Here
1060
	 * <ul>
1065
	 * <ul>
1061
	 * <li>the node belongs to a different AST</li>
1066
	 * <li>the node belongs to a different AST</li>
1062
	 * <li>the node already has a parent</li>
1067
	 * <li>the node already has a parent</li>
1063
	 * <li>a cycle in would be created</li>
1064
	 * </ul>
1068
	 * </ul>
1065
	 */
1069
	 */
1066
	public ArrayType newArrayType(Type componentType) {
1070
	public ArrayType newArrayType(Type componentType) {
Lines 1071-1098 Link Here
1071
1075
1072
	/**
1076
	/**
1073
	 * Creates and returns a new unparented array type node with the given
1077
	 * Creates and returns a new unparented array type node with the given
1074
	 * element type and number of dimensions.
1078
	 * element type and number of (additional) dimensions.
1075
	 * <p>
1079
	 * <p>
1076
	 * Note that if the element type passed in is an array type, the
1080
	 * Note that if the element type passed in is an array type, the
1077
	 * element type of the result will not be the same as what was passed in.
1081
	 * element type of the result will not be the same as what was passed in.
1078
	 * </p>
1082
	 * </p>
1079
	 *
1083
	 *
1080
	 * @param elementType the element type (never an array type)
1084
	 * @param elementType the element type (can be an array type)
1081
	 * @param dimensions the number of dimensions, a positive number
1085
	 * @param dimensions the number of dimensions, a positive number
1082
	 * @return a new unparented array type node
1086
	 * @return a new unparented array type node
1083
	 * @exception IllegalArgumentException if:
1087
	 * @exception IllegalArgumentException if:
1084
	 * <ul>
1088
	 * <ul>
1085
	 * <li>the node belongs to a different AST</li>
1089
	 * <li>the node belongs to a different AST</li>
1086
	 * <li>the node already has a parent</li>
1090
	 * <li>the node already has a parent</li>
1087
	 * <li>a cycle in would be created</li>
1088
	 * <li>the element type is null</li>
1091
	 * <li>the element type is null</li>
1089
	 * <li>the element type is an array type</li>
1090
	 * <li>the number of dimensions is lower than 1</li>
1092
	 * <li>the number of dimensions is lower than 1</li>
1091
	 * <li>the number of dimensions is greater than 1000</li>
1093
	 * <li>the number of dimensions is greater than 1000</li>
1092
	 * </ul>
1094
	 * </ul>
1093
	 */
1095
	 */
1094
	public ArrayType newArrayType(Type elementType, int dimensions) {
1096
	public ArrayType newArrayType(Type elementType, int dimensions) {
1095
		if (elementType == null || elementType.isArrayType()) {
1097
		if (elementType == null) {
1096
			throw new IllegalArgumentException();
1098
			throw new IllegalArgumentException();
1097
		}
1099
		}
1098
		if (dimensions < 1 || dimensions > 1000) {
1100
		if (dimensions < 1 || dimensions > 1000) {
Lines 1386-1392 Link Here
1386
	 * <ul>
1388
	 * <ul>
1387
	 * <li>the node belongs to a different AST</li>
1389
	 * <li>the node belongs to a different AST</li>
1388
	 * <li>the node already has a parent</li>
1390
	 * <li>the node already has a parent</li>
1389
	 * <li>a cycle in would be created</li>
1390
	 * </ul>
1391
	 * </ul>
1391
	 */
1392
	 */
1392
	public ExpressionStatement newExpressionStatement(Expression expression) {
1393
	public ExpressionStatement newExpressionStatement(Expression expression) {
Lines 1426-1432 Link Here
1426
	 * <ul>
1427
	 * <ul>
1427
	 * <li>the node belongs to a different AST</li>
1428
	 * <li>the node belongs to a different AST</li>
1428
	 * <li>the node already has a parent</li>
1429
	 * <li>the node already has a parent</li>
1429
	 * <li>a cycle in would be created</li>
1430
	 * <li>the given fragment is null</li>
1430
	 * <li>the given fragment is null</li>
1431
	 * </ul>
1431
	 * </ul>
1432
	 */
1432
	 */
Lines 2271-2277 Link Here
2271
	 * <ul>
2271
	 * <ul>
2272
	 * <li>the node belongs to a different AST</li>
2272
	 * <li>the node belongs to a different AST</li>
2273
	 * <li>the node already has a parent</li>
2273
	 * <li>the node already has a parent</li>
2274
	 * <li>a cycle in would be created</li>
2275
	 * </ul>
2274
	 * </ul>
2276
	 * @since 3.0
2275
	 * @since 3.0
2277
	 */
2276
	 */
Lines 2302-2308 Link Here
2302
	 * <ul>
2301
	 * <ul>
2303
	 * <li>the node belongs to a different AST</li>
2302
	 * <li>the node belongs to a different AST</li>
2304
	 * <li>the node already has a parent</li>
2303
	 * <li>the node already has a parent</li>
2305
	 * <li>a cycle in would be created</li>
2306
	 * </ul>
2304
	 * </ul>
2307
	 */
2305
	 */
2308
	public TypeDeclarationStatement
2306
	public TypeDeclarationStatement
Lines 2355-2363 Link Here
2355
	 * <ul>
2353
	 * <ul>
2356
	 * <li>the node belongs to a different AST</li>
2354
	 * <li>the node belongs to a different AST</li>
2357
	 * <li>the node already has a parent</li>
2355
	 * <li>the node already has a parent</li>
2358
	 * <li>a cycle in would be created</li>
2359
	 * <li>the given fragment is null</li>
2356
	 * <li>the given fragment is null</li>
2360
	 * <li>a cycle in would be created</li>
2361
	 * </ul>
2357
	 * </ul>
2362
	 */
2358
	 */
2363
	public VariableDeclarationExpression
2359
	public VariableDeclarationExpression
Lines 2402-2408 Link Here
2402
	 * <ul>
2398
	 * <ul>
2403
	 * <li>the node belongs to a different AST</li>
2399
	 * <li>the node belongs to a different AST</li>
2404
	 * <li>the node already has a parent</li>
2400
	 * <li>the node already has a parent</li>
2405
	 * <li>a cycle in would be created</li>
2406
	 * <li>the variable declaration fragment is null</li>
2401
	 * <li>the variable declaration fragment is null</li>
2407
	 * </ul>
2402
	 * </ul>
2408
	 */
2403
	 */
(-)a/org.eclipse.jdt.core/dom/org/eclipse/jdt/core/dom/ASTParser.java (-5 / +5 lines)
Lines 1-5 Link Here
1
/*******************************************************************************
1
/*******************************************************************************
2
 * Copyright (c) 2004, 2011 IBM Corporation and others.
2
 * Copyright (c) 2004, 2012 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 117-124 Link Here
117
	 * Creates a new object for creating a Java abstract syntax tree
117
	 * Creates a new object for creating a Java abstract syntax tree
118
     * (AST) following the specified set of API rules.
118
     * (AST) following the specified set of API rules.
119
     *
119
     *
120
 	 * @param level the API level; one of the LEVEL constants
120
 	 * @param level the API level; one of the <code>.JLS*</code> level constants
121
     * declared on <code>AST</code>
121
     * declared on {@link AST}
122
	 * @return new ASTParser instance
122
	 * @return new ASTParser instance
123
	 */
123
	 */
124
	public static ASTParser newParser(int level) {
124
	public static ASTParser newParser(int level) {
Lines 213-220 Link Here
213
	 * N.B. This constructor is package-private.
213
	 * N.B. This constructor is package-private.
214
	 * </p>
214
	 * </p>
215
	 *
215
	 *
216
	 * @param level the API level; one of the LEVEL constants
216
	 * @param level the API level; one of the <code>JLS*</code> level constants
217
	 * declared on <code>AST</code>
217
	 * declared on {@link AST}
218
	 */
218
	 */
219
	ASTParser(int level) {
219
	ASTParser(int level) {
220
		switch(level) {
220
		switch(level) {
(-)a/org.eclipse.jdt.core/dom/org/eclipse/jdt/core/dom/CompilationUnit.java (-2 / +2 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 867-873 Link Here
867
867
868
	/**
868
	/**
869
	 * Enables the recording of changes to this compilation
869
	 * Enables the recording of changes to this compilation
870
	 * unit and its descendents. The compilation unit must have
870
	 * unit and its descendants. The compilation unit must have
871
	 * been created by <code>ASTParser</code> and still be in
871
	 * been created by <code>ASTParser</code> and still be in
872
	 * its original state. Once recording is on,
872
	 * its original state. Once recording is on,
873
	 * arbitrary changes to the subtree rooted at this compilation
873
	 * arbitrary changes to the subtree rooted at this compilation
(-)a/org.eclipse.jdt.core/dom/org/eclipse/jdt/core/dom/CompilationUnitResolver.java (-5 / +13 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 363858 - [dom] early throwing of AbortCompilation causes NPE in CompilationUnitResolver
10
 *******************************************************************************/
11
 *******************************************************************************/
11
package org.eclipse.jdt.core.dom;
12
package org.eclipse.jdt.core.dom;
12
13
Lines 99-104 Link Here
99
	DefaultBindingResolver.BindingTables bindingTables;
100
	DefaultBindingResolver.BindingTables bindingTables;
100
101
101
	boolean hasCompilationAborted;
102
	boolean hasCompilationAborted;
103
	CategorizedProblem abortProblem;
102
104
103
	private IProgressMonitor monitor;
105
	private IProgressMonitor monitor;
104
	
106
	
Lines 364-369 Link Here
364
			removeUnresolvedBindings(unit);
366
			removeUnresolvedBindings(unit);
365
		}
367
		}
366
		this.hasCompilationAborted = true;
368
		this.hasCompilationAborted = true;
369
		this.abortProblem = abortException.problem;
367
	}
370
	}
368
371
369
	public static void parse(ICompilationUnit[] compilationUnits, ASTRequestor astRequestor, int apiLevel, Map options, int flags, IProgressMonitor monitor) {
372
	public static void parse(ICompilationUnit[] compilationUnits, ASTRequestor astRequestor, int apiLevel, Map options, int flags, IProgressMonitor monitor) {
Lines 689-699 Link Here
689
				// the bindings could not be resolved due to missing types in name environment
692
				// the bindings could not be resolved due to missing types in name environment
690
				// see https://bugs.eclipse.org/bugs/show_bug.cgi?id=86541
693
				// see https://bugs.eclipse.org/bugs/show_bug.cgi?id=86541
691
				CompilationUnitDeclaration unitDeclaration = parse(sourceUnit, nodeSearcher, options, flags);
694
				CompilationUnitDeclaration unitDeclaration = parse(sourceUnit, nodeSearcher, options, flags);
692
				final int problemCount = unit.compilationResult.problemCount;
695
				if (unit != null) {
693
				if (problemCount != 0) {
696
					final int problemCount = unit.compilationResult.problemCount;
694
					unitDeclaration.compilationResult.problems = new CategorizedProblem[problemCount];
697
					if (problemCount != 0) {
695
					System.arraycopy(unit.compilationResult.problems, 0, unitDeclaration.compilationResult.problems, 0, problemCount);
698
						unitDeclaration.compilationResult.problems = new CategorizedProblem[problemCount];
696
					unitDeclaration.compilationResult.problemCount = problemCount;
699
						System.arraycopy(unit.compilationResult.problems, 0, unitDeclaration.compilationResult.problems, 0, problemCount);
700
						unitDeclaration.compilationResult.problemCount = problemCount;
701
					}
702
				} else if (resolver.abortProblem != null) {
703
					unitDeclaration.compilationResult.problemCount = 1;
704
					unitDeclaration.compilationResult.problems = new CategorizedProblem[] { resolver.abortProblem };
697
				}
705
				}
698
				return unitDeclaration;
706
				return unitDeclaration;
699
			}
707
			}
(-)a/org.eclipse.jdt.core/dom/org/eclipse/jdt/core/dom/DefaultBindingResolver.java (-1 / +1 lines)
Lines 1384-1390 Link Here
1384
			org.eclipse.jdt.internal.compiler.ast.ASTNode node = (org.eclipse.jdt.internal.compiler.ast.ASTNode) this.newAstToOldAst.get(pkg);
1384
			org.eclipse.jdt.internal.compiler.ast.ASTNode node = (org.eclipse.jdt.internal.compiler.ast.ASTNode) this.newAstToOldAst.get(pkg);
1385
			if (node instanceof ImportReference) {
1385
			if (node instanceof ImportReference) {
1386
				ImportReference importReference = (ImportReference) node;
1386
				ImportReference importReference = (ImportReference) node;
1387
				Binding binding = this.scope.getTypeOrPackage(CharOperation.subarray(importReference.tokens, 0, importReference.tokens.length));
1387
				Binding binding = this.scope.getOnlyPackage(CharOperation.subarray(importReference.tokens, 0, importReference.tokens.length));
1388
				if ((binding != null) && (binding.isValidBinding())) {
1388
				if ((binding != null) && (binding.isValidBinding())) {
1389
					if (binding instanceof ReferenceBinding) {
1389
					if (binding instanceof ReferenceBinding) {
1390
						// this only happens if a type name has the same name as its package
1390
						// this only happens if a type name has the same name as its package
(-)a/org.eclipse.jdt.core/dom/org/eclipse/jdt/core/dom/TryStatement.java (-1 / +1 lines)
Lines 1-5 Link Here
1
/*******************************************************************************
1
/*******************************************************************************
2
 * Copyright (c) 2000, 2011 IBM Corporation and others.
2
 * Copyright (c) 2000, 2012 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
(-)a/org.eclipse.jdt.core/dom/org/eclipse/jdt/core/dom/rewrite/ASTRewrite.java (-3 / +4 lines)
Lines 1-5 Link Here
1
/*******************************************************************************
1
/*******************************************************************************
2
 * Copyright (c) 2004, 2010 IBM Corporation and others.
2
 * Copyright (c) 2004, 2012 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 692-700 Link Here
692
692
693
	/**
693
	/**
694
	 * Creates and returns a placeholder node for the new locations of the given node.
694
	 * Creates and returns a placeholder node for the new locations of the given node.
695
	 * After obtaining a placeholder, the node should then to be removed or replaced.
695
	 * After obtaining a placeholder, the node must be removed or replaced.
696
	 * The placeholder node can either be inserted as new or used to replace an
696
	 * The placeholder node can either be inserted as new or used to replace an
697
	 * existing node. When the document is rewritten, the source code for the given
697
	 * existing node. The placeholder must be used somewhere in the AST and must not be dropped
698
	 * by subsequent modifications. When the document is rewritten, the source code for the given
698
	 * node is inserted into the output document at the position corresponding to the
699
	 * node is inserted into the output document at the position corresponding to the
699
	 * placeholder (indentation is adjusted).
700
	 * placeholder (indentation is adjusted).
700
	 *
701
	 *
(-)a/org.eclipse.jdt.core/dom/org/eclipse/jdt/core/dom/rewrite/ListRewrite.java (-14 / +14 lines)
Lines 1-5 Link Here
1
/*******************************************************************************
1
/*******************************************************************************
2
 * Copyright (c) 2004, 2009 IBM Corporation and others.
2
 * Copyright (c) 2004, 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 145-151 Link Here
145
145
146
	/**
146
	/**
147
	 * Inserts the given node into the list after the given element.
147
	 * Inserts the given node into the list after the given element.
148
	 * The existing node must be in the list, either as an original or as a new
148
	 * The existing node <code>previousElement</code> must be in the list, either as an original or as a new
149
	 * node that has been inserted.
149
	 * node that has been inserted.
150
	 * The inserted node must either be brand new (not part of the original AST)
150
	 * The inserted node must either be brand new (not part of the original AST)
151
	 * or a placeholder node (for example, one created by
151
	 * or a placeholder node (for example, one created by
Lines 156-175 Link Here
156
     * a note that this node has been inserted into the list.
156
     * a note that this node has been inserted into the list.
157
	 *
157
	 *
158
	 * @param node the node to insert
158
	 * @param node the node to insert
159
	 * @param element the element after which the given node is to be inserted
159
	 * @param previousElement the element after which the given node is to be inserted
160
	 * @param editGroup the edit group in which to collect the corresponding
160
	 * @param editGroup the edit group in which to collect the corresponding
161
	 * text edits, or <code>null</code> if ungrouped
161
	 * text edits, or <code>null</code> if ungrouped
162
	 * @throws IllegalArgumentException if the node or element is null,
162
	 * @throws IllegalArgumentException if the node or element is null,
163
	 * or if the node is not part of this rewriter's AST, or if the inserted node
163
	 * or if the node is not part of this rewriter's AST, or if the inserted node
164
	 * is not a new node (or placeholder), or if <code>element</code> is not a member
164
	 * is not a new node (or placeholder), or if <code>previousElement</code> is not a member
165
	 * of the list (original or new), or if the described modification is
165
	 * of the list (original or new), or if the described modification is
166
	 * otherwise invalid
166
	 * otherwise invalid
167
	 */
167
	 */
168
	public void insertAfter(ASTNode node, ASTNode element, TextEditGroup editGroup) {
168
	public void insertAfter(ASTNode node, ASTNode previousElement, TextEditGroup editGroup) {
169
		if (node == null || element == null) {
169
		if (node == null || previousElement == null) {
170
			throw new IllegalArgumentException();
170
			throw new IllegalArgumentException();
171
		}
171
		}
172
		int index= getEvent().getIndex(element, ListRewriteEvent.BOTH);
172
		int index= getEvent().getIndex(previousElement, ListRewriteEvent.BOTH);
173
		if (index == -1) {
173
		if (index == -1) {
174
			throw new IllegalArgumentException("Node does not exist"); //$NON-NLS-1$
174
			throw new IllegalArgumentException("Node does not exist"); //$NON-NLS-1$
175
		}
175
		}
Lines 178-184 Link Here
178
178
179
	/**
179
	/**
180
	 * Inserts the given node into the list before the given element.
180
	 * Inserts the given node into the list before the given element.
181
	 * The existing node must be in the list, either as an original or as a new
181
	 * The existing node <code>nextElement</code> must be in the list, either as an original or as a new
182
	 * node that has been inserted.
182
	 * node that has been inserted.
183
	 * The inserted node must either be brand new (not part of the original AST)
183
	 * The inserted node must either be brand new (not part of the original AST)
184
	 * or a placeholder node (for example, one created by
184
	 * or a placeholder node (for example, one created by
Lines 189-208 Link Here
189
     * a note that this node has been inserted into the list.
189
     * a note that this node has been inserted into the list.
190
	 *
190
	 *
191
	 * @param node the node to insert
191
	 * @param node the node to insert
192
	 * @param element the element before which the given node is to be inserted
192
	 * @param nextElement the element before which the given node is to be inserted
193
	 * @param editGroup the edit group in which to collect the corresponding
193
	 * @param editGroup the edit group in which to collect the corresponding
194
	 * text edits, or <code>null</code> if ungrouped
194
	 * text edits, or <code>null</code> if ungrouped
195
	 * @throws IllegalArgumentException if the node or element is null,
195
	 * @throws IllegalArgumentException if the node or next element is null,
196
	 * or if the node is not part of this rewriter's AST, or if the inserted node
196
	 * or if the node is not part of this rewriter's AST, or if the inserted node
197
	 * is not a new node (or placeholder), or if <code>element</code> is not a member
197
	 * is not a new node (or placeholder), or if <code>nextElement</code> is not a member
198
	 * of the list (original or new), or if the described modification is
198
	 * of the list (original or new), or if the described modification is
199
	 * otherwise invalid
199
	 * otherwise invalid
200
	 */
200
	 */
201
	public void insertBefore(ASTNode node, ASTNode element, TextEditGroup editGroup) {
201
	public void insertBefore(ASTNode node, ASTNode nextElement, TextEditGroup editGroup) {
202
		if (node == null || element == null) {
202
		if (node == null || nextElement == null) {
203
			throw new IllegalArgumentException();
203
			throw new IllegalArgumentException();
204
		}
204
		}
205
		int index= getEvent().getIndex(element, ListRewriteEvent.BOTH);
205
		int index= getEvent().getIndex(nextElement, ListRewriteEvent.BOTH);
206
		if (index == -1) {
206
		if (index == -1) {
207
			throw new IllegalArgumentException("Node does not exist"); //$NON-NLS-1$
207
			throw new IllegalArgumentException("Node does not exist"); //$NON-NLS-1$
208
		}
208
		}
(-)a/org.eclipse.jdt.core/dom/org/eclipse/jdt/internal/core/dom/NaiveASTFlattener.java (-3 / +3 lines)
Lines 1-5 Link Here
1
/*******************************************************************************
1
/*******************************************************************************
2
 * Copyright (c) 2000, 2011 IBM Corporation and others.
2
 * Copyright (c) 2000, 2012 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 1528-1536 Link Here
1528
	public boolean visit(TryStatement node) {
1528
	public boolean visit(TryStatement node) {
1529
		printIndent();
1529
		printIndent();
1530
		this.buffer.append("try ");//$NON-NLS-1$
1530
		this.buffer.append("try ");//$NON-NLS-1$
1531
		List resources = node.resources();
1532
		if (node.getAST().apiLevel() >= AST.JLS4) {
1531
		if (node.getAST().apiLevel() >= AST.JLS4) {
1533
			if (!node.resources().isEmpty()) {
1532
			List resources = node.resources();
1533
			if (!resources.isEmpty()) {
1534
				this.buffer.append('(');
1534
				this.buffer.append('(');
1535
				for (Iterator it = resources.iterator(); it.hasNext(); ) {
1535
				for (Iterator it = resources.iterator(); it.hasNext(); ) {
1536
					VariableDeclarationExpression variable = (VariableDeclarationExpression) it.next();
1536
					VariableDeclarationExpression variable = (VariableDeclarationExpression) it.next();
(-)a/org.eclipse.jdt.core/dom/org/eclipse/jdt/internal/core/dom/rewrite/ASTRewriteAnalyzer.java (-9 / +13 lines)
Lines 881-890 Link Here
881
						insertedPrefix = getLineDelimiter() + this.formatter.createIndentString(indent) + insertedPrefix.trim() + ' ';
881
						insertedPrefix = getLineDelimiter() + this.formatter.createIndentString(indent) + insertedPrefix.trim() + ' ';
882
					}
882
					}
883
					doTextInsert(offset, insertedPrefix, editGroup);
883
					doTextInsert(offset, insertedPrefix, editGroup);
884
					String lineInPrefix= getCurrentLine(prefix, prefix.length());
884
					int lineStart= getCurrentLineStart(prefix, prefix.length());
885
					if (prefix.length() != lineInPrefix.length()) {
885
					if (lineStart != 0) {
886
						// prefix contains a new line: update the indent to the one used in the prefix
886
						// prefix contains a new line: update the indent to the one used in the prefix
887
						indent= this.formatter.computeIndentUnits(lineInPrefix);
887
						indent= this.formatter.computeIndentUnits(prefix.substring(lineStart));
888
					}
888
					}
889
					doTextInsert(offset, replacingNode, indent, true, editGroup);
889
					doTextInsert(offset, replacingNode, indent, true, editGroup);
890
					doTextInsert(offset, strings[1], editGroup);
890
					doTextInsert(offset, strings[1], editGroup);
Lines 1316-1322 Link Here
1316
				}
1316
				}
1317
				currPos= offset;
1317
				currPos= offset;
1318
			} else {
1318
			} else {
1319
				String destIndentString=  this.formatter.getIndentString(getCurrentLine(formatted, offset));
1319
				// If in the first line, there are cases (eg: catch clause) where the line will not be prefixed with 
1320
				// proper indentation - see https://bugs.eclipse.org/bugs/show_bug.cgi?id=350285
1321
				int lineOffset = getCurrentLineStart(formatted, offset);
1322
				String destIndentString = (lineOffset == 0)
1323
						? this.formatter.createIndentString(initialIndentLevel)
1324
						: this.formatter.getIndentString(formatted.substring(lineOffset, offset));
1320
				if (data instanceof CopyPlaceholderData) { // replace with a copy/move target
1325
				if (data instanceof CopyPlaceholderData) { // replace with a copy/move target
1321
					CopySourceInfo copySource= ((CopyPlaceholderData) data).copySource;
1326
					CopySourceInfo copySource= ((CopyPlaceholderData) data).copySource;
1322
					int srcIndentLevel= getIndent(copySource.getNode().getStartPosition());
1327
					int srcIndentLevel= getIndent(copySource.getNode().getStartPosition());
Lines 1349-1365 Link Here
1349
		return offset < formatted.length() && !IndentManipulation.isLineDelimiterChar(formatted.charAt(offset));
1354
		return offset < formatted.length() && !IndentManipulation.isLineDelimiterChar(formatted.charAt(offset));
1350
	}
1355
	}
1351
1356
1352
	private String getCurrentLine(String str, int pos) {
1357
	private int getCurrentLineStart(String str, int pos) {
1353
		for (int i= pos - 1; i>= 0; i--) {
1358
		for (int i= pos - 1; i>= 0; i--) {
1354
			char ch= str.charAt(i);
1359
			char ch= str.charAt(i);
1355
			if (IndentManipulation.isLineDelimiterChar(ch)) {
1360
			if (IndentManipulation.isLineDelimiterChar(ch)) {
1356
				return str.substring(i + 1, pos);
1361
				return i+1;
1357
			}
1362
			}
1358
		}
1363
		}
1359
		return str.substring(0, pos);
1364
		return 0;
1360
	}
1365
	}
1361
1366
	
1362
1363
	private void rewriteModifiers(ASTNode parent, StructuralPropertyDescriptor property, int offset) {
1367
	private void rewriteModifiers(ASTNode parent, StructuralPropertyDescriptor property, int offset) {
1364
		RewriteEvent event= getEvent(parent, property);
1368
		RewriteEvent event= getEvent(parent, property);
1365
		if (event == null || event.getChangeKind() != RewriteEvent.REPLACED) {
1369
		if (event == null || event.getChangeKind() != RewriteEvent.REPLACED) {
(-)a/org.eclipse.jdt.core/dom/org/eclipse/jdt/internal/core/dom/rewrite/ImportRewriteAnalyzer.java (-6 / +32 lines)
Lines 758-766 Link Here
758
						} else if (doStarImport && !currDecl.isOnDemand()) {
758
						} else if (doStarImport && !currDecl.isOnDemand()) {
759
							String simpleName = currDecl.getTypeQualifiedName();
759
							String simpleName = currDecl.getTypeQualifiedName();
760
							if (simpleName.indexOf('.') != -1) {
760
							if (simpleName.indexOf('.') != -1) {
761
								//If there is '.' in a Simple typename it is safe to assume that we are working with a Nested import
761
								String str= getNewImportString(currDecl.getElementName(), isStatic, lineDelim);
762
								String str= getNewImportString(currDecl.getElementName(), isStatic, lineDelim);
762
								if (stringsToInsert.indexOf(str) == -1) {
763
								String nextedStarImport = getNestedStarImport(
763
									stringsToInsert.add(str);
764
										lineDelim, str);
765
								if (stringsToInsert.indexOf(nextedStarImport) == -1) {
766
									stringsToInsert.add(nextedStarImport);
764
								}
767
								}
765
							}
768
							}
766
						}
769
						}
Lines 770-775 Link Here
770
						stringsToInsert.clear();
773
						stringsToInsert.clear();
771
						currPos= offset + region.getLength();
774
						currPos= offset + region.getLength();
772
					} else if (doStarImport && !currDecl.isOnDemand()) {
775
					} else if (doStarImport && !currDecl.isOnDemand()) {
776
						//If there is '.' in a Simple typename it is safe to assume that we are working with a Nested import
773
						String simpleName = currDecl.getTypeQualifiedName();
777
						String simpleName = currDecl.getTypeQualifiedName();
774
						if (simpleName.indexOf('.') != -1) {
778
						if (simpleName.indexOf('.') != -1) {
775
							IRegion rangeBefore = currDecl.getPrecedingCommentRange();
779
							IRegion rangeBefore = currDecl.getPrecedingCommentRange();
Lines 782-789 Link Here
782
								trailingComment = buffer.getText(rangeAfter.getOffset(), rangeAfter.getLength());
786
								trailingComment = buffer.getText(rangeAfter.getOffset(), rangeAfter.getLength());
783
							}
787
							}
784
							String str= getNewImportString(currDecl.getElementName(), isStatic, trailingComment, lineDelim);
788
							String str= getNewImportString(currDecl.getElementName(), isStatic, trailingComment, lineDelim);
785
							if (stringsToInsert.indexOf(str) == -1) {
789
							String nextedStarImport = getNestedStarImport(
786
								stringsToInsert.add(str);
790
									lineDelim, str);
791
							if (stringsToInsert.indexOf(nextedStarImport) == -1) {
792
								stringsToInsert.add(nextedStarImport);
787
							}
793
							}
788
						}
794
						}
789
					}
795
					}
Lines 977-983 Link Here
977
		for (int i= 0; i < nImports; i++) {
983
		for (int i= 0; i < nImports; i++) {
978
			ImportDeclEntry curr= packageEntry.getImportAt(i);
984
			ImportDeclEntry curr= packageEntry.getImportAt(i);
979
			String simpleName = curr.getTypeQualifiedName();
985
			String simpleName = curr.getTypeQualifiedName();
980
			if (simpleName.indexOf('.') != -1) {
986
			if (simpleName.indexOf('.') != -1 &&!isStarImportAdded) {
981
				// member type imports - we preserve it
987
				// member type imports - we preserve it
982
				IRegion rangeBefore = curr.getPrecedingCommentRange();
988
				IRegion rangeBefore = curr.getPrecedingCommentRange();
983
				if (rangeBefore != null) {
989
				if (rangeBefore != null) {
Lines 988-994 Link Here
988
				if (rangeAfter != null) {
994
				if (rangeAfter != null) {
989
					trailingComment = buffer.getText(rangeAfter.getOffset(), rangeAfter.getLength());
995
					trailingComment = buffer.getText(rangeAfter.getOffset(), rangeAfter.getLength());
990
				}
996
				}
991
				allImports.add(getNewImportString(curr.getElementName(), isStatic, trailingComment, lineDelim));
997
				String starImportString = getNestedImports(packageEntry.getName(),
998
						simpleName);
999
				allImports.add(getNewImportString(starImportString, isStatic, trailingComment, lineDelim));
1000
				isStarImportAdded=true;
992
			} else if (!isStarImportAdded) {
1001
			} else if (!isStarImportAdded) {
993
				String starImportString= packageEntry.getName() + ".*"; //$NON-NLS-1$
1002
				String starImportString= packageEntry.getName() + ".*"; //$NON-NLS-1$
994
				allImports.add(getNewImportString(starImportString, isStatic, lineDelim));
1003
				allImports.add(getNewImportString(starImportString, isStatic, lineDelim));
Lines 1016-1021 Link Here
1016
		}
1025
		}
1017
		return (String[]) allImports.toArray(new String[allImports.size()]);
1026
		return (String[]) allImports.toArray(new String[allImports.size()]);
1018
	}
1027
	}
1028
	
1029
	private String getNestedStarImport(String lineDelim, String str) {
1030
		StringBuffer buff=new StringBuffer();
1031
		buff.append(str.substring(0, str.lastIndexOf('.')));
1032
		buff.append(".*;");//$NON-NLS-1$
1033
		buff.append(lineDelim);
1034
		return buff.toString();
1035
	}
1036
	
1037
	private String getNestedImports(String packageEntry,String simpleName) {
1038
		StringBuffer starImportString= new StringBuffer();
1039
		starImportString.append(packageEntry);
1040
		starImportString.append(".");//$NON-NLS-1$
1041
		starImportString.append(simpleName.substring(0, simpleName.lastIndexOf('.')));
1042
		starImportString.append(".*"); //$NON-NLS-1$
1043
		return starImportString.toString();
1044
	}
1019
1045
1020
	private static int getFirstTypeBeginPos(CompilationUnit root) {
1046
	private static int getFirstTypeBeginPos(CompilationUnit root) {
1021
		List types= root.types();
1047
		List types= root.types();
(-)a/org.eclipse.jdt.core/eval/org/eclipse/jdt/internal/eval/CodeSnippetSkeleton.java (-1 / +5 lines)
Lines 1-5 Link Here
1
/*******************************************************************************
1
/*******************************************************************************
2
 * Copyright (c) 2000, 2009 IBM Corporation and others.
2
 * Copyright (c) 2000, 2011 IBM Corporation and others.
3
 * All rights reserved. This program and the accompanying materials
3
 * All rights reserved. This program and the accompanying materials
4
 * are made available under the terms of the Eclipse Public License v1.0
4
 * are made available under the terms of the Eclipse Public License v1.0
5
 * which accompanies this distribution, and is available at
5
 * which accompanies this distribution, and is available at
Lines 7-12 Link Here
7
 *
7
 *
8
 * Contributors:
8
 * Contributors:
9
 *     IBM Corporation - initial API and implementation
9
 *     IBM Corporation - initial API and implementation
10
 *     Stephan Herrmann - Contribution for bug 186342 - [compiler][null] Using annotations for null checking
10
 *******************************************************************************/
11
 *******************************************************************************/
11
package org.eclipse.jdt.internal.eval;
12
package org.eclipse.jdt.internal.eval;
12
13
Lines 64-69 Link Here
64
		public IBinaryAnnotation[] getParameterAnnotations(int index) {
65
		public IBinaryAnnotation[] getParameterAnnotations(int index) {
65
			return null;
66
			return null;
66
		}
67
		}
68
		public int getAnnotatedParametersCount() {
69
			return 0;
70
		}
67
		public char[] getSelector() {
71
		public char[] getSelector() {
68
			return this.selector;
72
			return this.selector;
69
		}
73
		}
(-)a/org.eclipse.jdt.core/eval/org/eclipse/jdt/internal/eval/EvaluationContext.java (-1 / +7 lines)
Lines 1-5 Link Here
1
/*******************************************************************************
1
/*******************************************************************************
2
 * Copyright (c) 2000, 2011 IBM Corporation and others.
2
 * Copyright (c) 2000, 2012 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 156-161 Link Here
156
		}
156
		}
157
		public char[][] getPackageName() {
157
		public char[][] getPackageName() {
158
			return null;
158
			return null;
159
		}
160
		public boolean ignoreOptionalProblems() {
161
			return false;
159
		}
162
		}
160
	};
163
	};
161
164
Lines 601-606 Link Here
601
		public char[][] getPackageName() {
604
		public char[][] getPackageName() {
602
			return null;
605
			return null;
603
		}
606
		}
607
		public boolean ignoreOptionalProblems() {
608
			return false;
609
		}
604
	};
610
	};
605
	SelectionEngine engine = new SelectionEngine(environment, mapper.getSelectionRequestor(requestor), options, owner);
611
	SelectionEngine engine = new SelectionEngine(environment, mapper.getSelectionRequestor(requestor), options, owner);
606
	engine.select(sourceUnit, mapper.startPosOffset + selectionSourceStart, mapper.startPosOffset + selectionSourceEnd);
612
	engine.select(sourceUnit, mapper.startPosOffset + selectionSourceStart, mapper.startPosOffset + selectionSourceEnd);
(-)a/org.eclipse.jdt.core/eval/org/eclipse/jdt/internal/eval/Evaluator.java (-1 / +4 lines)
Lines 1-5 Link Here
1
/*******************************************************************************
1
/*******************************************************************************
2
 * Copyright (c) 2000, 2009 IBM Corporation and others.
2
 * Copyright (c) 2000, 2012 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 141-146 Link Here
141
		public char[][] getPackageName() {
141
		public char[][] getPackageName() {
142
			return null;
142
			return null;
143
		}
143
		}
144
		public boolean ignoreOptionalProblems() {
145
			return false;
146
		}
144
	}});
147
	}});
145
	if (compilerRequestor.hasErrors) {
148
	if (compilerRequestor.hasErrors) {
146
		return null;
149
		return null;
(-)a/org.eclipse.jdt.core/formatter/org/eclipse/jdt/internal/formatter/CodeFormatterVisitor.java (-9 / +4 lines)
Lines 109-115 Link Here
109
import org.eclipse.jdt.internal.compiler.ast.Wildcard;
109
import org.eclipse.jdt.internal.compiler.ast.Wildcard;
110
import org.eclipse.jdt.internal.compiler.classfmt.ClassFileConstants;
110
import org.eclipse.jdt.internal.compiler.classfmt.ClassFileConstants;
111
import org.eclipse.jdt.internal.compiler.impl.CompilerOptions;
111
import org.eclipse.jdt.internal.compiler.impl.CompilerOptions;
112
import org.eclipse.jdt.internal.compiler.impl.Constant;
113
import org.eclipse.jdt.internal.compiler.lookup.BlockScope;
112
import org.eclipse.jdt.internal.compiler.lookup.BlockScope;
114
import org.eclipse.jdt.internal.compiler.lookup.ClassScope;
113
import org.eclipse.jdt.internal.compiler.lookup.ClassScope;
115
import org.eclipse.jdt.internal.compiler.lookup.CompilationUnitScope;
114
import org.eclipse.jdt.internal.compiler.lookup.CompilationUnitScope;
Lines 3670-3677 Link Here
3670
		if (numberOfParens > 0) {
3669
		if (numberOfParens > 0) {
3671
			manageOpeningParenthesizedExpression(doubleLiteral, numberOfParens);
3670
			manageOpeningParenthesizedExpression(doubleLiteral, numberOfParens);
3672
		}
3671
		}
3673
		Constant constant = doubleLiteral.constant;
3672
		if (isNextToken(TerminalTokens.TokenNameMINUS)) {
3674
		if (constant != null && constant.doubleValue() < 0) {
3675
			this.scribe.printNextToken(TerminalTokens.TokenNameMINUS);
3673
			this.scribe.printNextToken(TerminalTokens.TokenNameMINUS);
3676
		}
3674
		}
3677
		this.scribe.printNextToken(TerminalTokens.TokenNameDoubleLiteral);
3675
		this.scribe.printNextToken(TerminalTokens.TokenNameDoubleLiteral);
Lines 3895-3902 Link Here
3895
		if (numberOfParens > 0) {
3893
		if (numberOfParens > 0) {
3896
			manageOpeningParenthesizedExpression(floatLiteral, numberOfParens);
3894
			manageOpeningParenthesizedExpression(floatLiteral, numberOfParens);
3897
		}
3895
		}
3898
		Constant constant = floatLiteral.constant;
3896
		if (isNextToken(TerminalTokens.TokenNameMINUS)) {
3899
		if (constant != null && floatLiteral.constant.floatValue() < 0) {
3900
			this.scribe.printNextToken(TerminalTokens.TokenNameMINUS);
3897
			this.scribe.printNextToken(TerminalTokens.TokenNameMINUS);
3901
		}
3898
		}
3902
		this.scribe.printNextToken(TerminalTokens.TokenNameFloatingPointLiteral);
3899
		this.scribe.printNextToken(TerminalTokens.TokenNameFloatingPointLiteral);
Lines 4209-4216 Link Here
4209
		if (numberOfParens > 0) {
4206
		if (numberOfParens > 0) {
4210
			manageOpeningParenthesizedExpression(intLiteral, numberOfParens);
4207
			manageOpeningParenthesizedExpression(intLiteral, numberOfParens);
4211
		}
4208
		}
4212
		Constant constant = intLiteral.constant;
4209
		if (isNextToken(TerminalTokens.TokenNameMINUS)) {
4213
		if (constant != null && constant.intValue() < 0) {
4214
			this.scribe.printNextToken(TerminalTokens.TokenNameMINUS);
4210
			this.scribe.printNextToken(TerminalTokens.TokenNameMINUS);
4215
		}
4211
		}
4216
		this.scribe.printNextToken(TerminalTokens.TokenNameIntegerLiteral);
4212
		this.scribe.printNextToken(TerminalTokens.TokenNameIntegerLiteral);
Lines 4260-4267 Link Here
4260
		if (numberOfParens > 0) {
4256
		if (numberOfParens > 0) {
4261
			manageOpeningParenthesizedExpression(longLiteral, numberOfParens);
4257
			manageOpeningParenthesizedExpression(longLiteral, numberOfParens);
4262
		}
4258
		}
4263
		Constant constant = longLiteral.constant;
4259
		if (isNextToken(TerminalTokens.TokenNameMINUS)) {
4264
		if (constant != null && constant.longValue() < 0) {
4265
			this.scribe.printNextToken(TerminalTokens.TokenNameMINUS);
4260
			this.scribe.printNextToken(TerminalTokens.TokenNameMINUS);
4266
		}
4261
		}
4267
		this.scribe.printNextToken(TerminalTokens.TokenNameLongLiteral);
4262
		this.scribe.printNextToken(TerminalTokens.TokenNameLongLiteral);
(-)a/org.eclipse.jdt.core/grammar/java.g (-6 / +10 lines)
Lines 1234-1261 Link Here
1234
/.$putCase consumeAllocationHeader(); $break ./
1234
/.$putCase consumeAllocationHeader(); $break ./
1235
/:$readableName AllocationHeader:/
1235
/:$readableName AllocationHeader:/
1236
1236
1237
ClassInstanceCreationExpression ::= 'new' OnlyTypeArguments ClassType '(' ArgumentListopt ')' UnqualifiedClassBodyopt
1237
ClassInstanceCreationExpression ::= 'new' OnlyTypeArguments ClassType EnterInstanceCreationArgumentList '(' ArgumentListopt ')' UnqualifiedClassBodyopt
1238
/.$putCase consumeClassInstanceCreationExpressionWithTypeArguments(); $break ./
1238
/.$putCase consumeClassInstanceCreationExpressionWithTypeArguments(); $break ./
1239
1239
1240
ClassInstanceCreationExpression ::= 'new' ClassType '(' ArgumentListopt ')' UnqualifiedClassBodyopt
1240
ClassInstanceCreationExpression ::= 'new' ClassType EnterInstanceCreationArgumentList '(' ArgumentListopt ')' UnqualifiedClassBodyopt
1241
/.$putCase consumeClassInstanceCreationExpression(); $break ./
1241
/.$putCase consumeClassInstanceCreationExpression(); $break ./
1242
--1.1 feature
1242
--1.1 feature
1243
1243
1244
ClassInstanceCreationExpression ::= Primary '.' 'new' OnlyTypeArguments ClassType '(' ArgumentListopt ')' QualifiedClassBodyopt
1244
ClassInstanceCreationExpression ::= Primary '.' 'new' OnlyTypeArguments ClassType EnterInstanceCreationArgumentList '(' ArgumentListopt ')' QualifiedClassBodyopt
1245
/.$putCase consumeClassInstanceCreationExpressionQualifiedWithTypeArguments() ; $break ./
1245
/.$putCase consumeClassInstanceCreationExpressionQualifiedWithTypeArguments() ; $break ./
1246
1246
1247
ClassInstanceCreationExpression ::= Primary '.' 'new' ClassType '(' ArgumentListopt ')' QualifiedClassBodyopt
1247
ClassInstanceCreationExpression ::= Primary '.' 'new' ClassType EnterInstanceCreationArgumentList '(' ArgumentListopt ')' QualifiedClassBodyopt
1248
/.$putCase consumeClassInstanceCreationExpressionQualified() ; $break ./
1248
/.$putCase consumeClassInstanceCreationExpressionQualified() ; $break ./
1249
1249
1250
--1.1 feature
1250
--1.1 feature
1251
ClassInstanceCreationExpression ::= ClassInstanceCreationExpressionName 'new' ClassType '(' ArgumentListopt ')' QualifiedClassBodyopt
1251
ClassInstanceCreationExpression ::= ClassInstanceCreationExpressionName 'new' ClassType EnterInstanceCreationArgumentList '(' ArgumentListopt ')' QualifiedClassBodyopt
1252
/.$putCase consumeClassInstanceCreationExpressionQualified() ; $break ./
1252
/.$putCase consumeClassInstanceCreationExpressionQualified() ; $break ./
1253
/:$readableName ClassInstanceCreationExpression:/
1253
/:$readableName ClassInstanceCreationExpression:/
1254
1254
1255
ClassInstanceCreationExpression ::= ClassInstanceCreationExpressionName 'new' OnlyTypeArguments ClassType '(' ArgumentListopt ')' QualifiedClassBodyopt
1255
ClassInstanceCreationExpression ::= ClassInstanceCreationExpressionName 'new' OnlyTypeArguments ClassType EnterInstanceCreationArgumentList '(' ArgumentListopt ')' QualifiedClassBodyopt
1256
/.$putCase consumeClassInstanceCreationExpressionQualifiedWithTypeArguments() ; $break ./
1256
/.$putCase consumeClassInstanceCreationExpressionQualifiedWithTypeArguments() ; $break ./
1257
/:$readableName ClassInstanceCreationExpression:/
1257
/:$readableName ClassInstanceCreationExpression:/
1258
1258
1259
EnterInstanceCreationArgumentList ::= $empty
1260
/.$putCase consumeEnterInstanceCreationArgumentList(); $break ./
1261
/:$readableName EnterInstanceCreationArgumentList:/
1262
1259
ClassInstanceCreationExpressionName ::= Name '.'
1263
ClassInstanceCreationExpressionName ::= Name '.'
1260
/.$putCase consumeClassInstanceCreationExpressionName() ; $break ./
1264
/.$putCase consumeClassInstanceCreationExpressionName() ; $break ./
1261
/:$readableName ClassInstanceCreationExpressionName:/
1265
/:$readableName ClassInstanceCreationExpressionName:/
(-)a/org.eclipse.jdt.core/model/org/eclipse/jdt/core/IClasspathAttribute.java (-1 / +42 lines)
Lines 1-5 Link Here
1
/*******************************************************************************
1
/*******************************************************************************
2
 * Copyright (c) 2005, 2010 IBM Corporation and others.
2
 * Copyright (c) 2005, 2012 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 58-63 Link Here
58
	 * @since 3.1
58
	 * @since 3.1
59
	 */
59
	 */
60
	String JAVADOC_LOCATION_ATTRIBUTE_NAME = "javadoc_location"; //$NON-NLS-1$
60
	String JAVADOC_LOCATION_ATTRIBUTE_NAME = "javadoc_location"; //$NON-NLS-1$
61
	
62
	/**
63
	 * Constant for the name of the index location attribute.
64
	 * 
65
	 * <p>The value for this attribute has to be the string representation of a URL.
66
	 * It should point to an existing index file in a folder or a jar. The URL can also be of platform protocol.</p>
67
	 * 
68
	 * @since 3.8
69
	 */
70
	String INDEX_LOCATION_ATTRIBUTE_NAME = "index_location"; //$NON-NLS-1$
71
72
	/**
73
	 * Constant for the name of the encoding to be used for source attachments.
74
	 * 
75
	 * <p>The value of this attribute has to be a string representation of a valid encoding. The encoding
76
	 * for a source attachment is determined in the following order: </p>
77
	 *
78
	 * <ul>
79
	 * <li>	Encoding explicitly set on the source file (java or zip), i.e. <code>org.eclipse.core.resources.IFile#getCharset(false)</code> </li>
80
	 * <li>	Encoding set on the corresponding classpath entry </li>
81
	 * <li> If the source attachment is a folder, then the encoding determined by the file content if detectable </li>
82
	 * <li> If the source attachment is in the workspace, then the encoding of the enclosing resources</li>
83
	 * </ul>
84
	 *
85
	 * @see org.eclipse.core.resources.IFile#getCharset()
86
	 * @since 3.8
87
	 */
88
	String SOURCE_ATTACHMENT_ENCODING = "source_encoding"; //$NON-NLS-1$
89
90
	/**
91
	 * Constant for the name of the ignore optional compile problems attribute.
92
	 * This attribute is valid only for classpath entries describing source folders.
93
	 * The possible values for this attribute are <code>"true"</code> or
94
	 * <code>"false"</code>. When not present, <code>"false"</code> is assumed.
95
	 * If the value of this attribute is <code>"true"</code>, all optional problems
96
	 * from the source folder described by this classpath entry will not be reported
97
	 * by the compiler.
98
	 *
99
	 * @since 3.8
100
	 */
101
	String IGNORE_OPTIONAL_PROBLEMS = "ignore_optional_problems"; //$NON-NLS-1$
61
102
62
	/**
103
	/**
63
	 * Constant for the name of the optional attribute. The possible values
104
	 * Constant for the name of the optional attribute. The possible values
(-)a/org.eclipse.jdt.core/model/org/eclipse/jdt/core/IJavaModelMarker.java (-1 / +10 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 114-117 Link Here
114
	 * @since 2.0
114
	 * @since 2.0
115
	 */
115
	 */
116
	String CLASSPATH_FILE_FORMAT = "classpathFileFormat"; //$NON-NLS-1$
116
	String CLASSPATH_FILE_FORMAT = "classpathFileFormat"; //$NON-NLS-1$
117
	
118
	/**
119
	 * Output overlapping another source attribute (value <code>"outputOverlappingSource"</code>). 
120
	 * Used only on buildpath problem markers. The value of this attribute is 
121
	 * either "true" or "false".
122
	 * 
123
	 * @since 3.6.4
124
	 */
125
	String OUTPUT_OVERLAPPING_SOURCE = "outputOverlappingSource"; //$NON-NLS-1$
117
}
126
}
(-)a/org.eclipse.jdt.core/model/org/eclipse/jdt/core/IJavaModelStatusConstants.java (+7 lines)
Lines 345-348 Link Here
345
	 * @since 3.7
345
	 * @since 3.7
346
	 */
346
	 */
347
	public static final int CANNOT_RETRIEVE_ATTACHED_JAVADOC_TIMEOUT = 1012;
347
	public static final int CANNOT_RETRIEVE_ATTACHED_JAVADOC_TIMEOUT = 1012;
348
	
349
	/**
350
	 * <p>Status constant indicating that the default or specific output folder is overlapping
351
	 * with another source location. </p>
352
	 * @since 3.6.4
353
	 */
354
	public static final int OUTPUT_LOCATION_OVERLAPPING_ANOTHER_SOURCE = 1013;
348
}
355
}
(-)a/org.eclipse.jdt.core/model/org/eclipse/jdt/core/JavaConventions.java (-5 / +7 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 581-591 Link Here
581
	 *   <li> The project output location path cannot be null, must be absolute and located inside the project.
581
	 *   <li> The project output location path cannot be null, must be absolute and located inside the project.
582
	 *   <li> Specific output locations (specified on source entries) can be null, if not they must be located inside the project,
582
	 *   <li> Specific output locations (specified on source entries) can be null, if not they must be located inside the project,
583
	 *   <li> A project entry cannot refer to itself directly (that is, a project cannot prerequisite itself).
583
	 *   <li> A project entry cannot refer to itself directly (that is, a project cannot prerequisite itself).
584
     *   <li> Classpath entries or output locations cannot coincidate or be nested in each other, except for the following scenarii listed below:
584
     *   <li> Classpath entries or output locations cannot coincide or be nested in each other, except for the following scenarios listed below:
585
	 *      <ul><li> A source folder can coincidate with its own output location, in which case this output can then contain library archives.
585
	 *      <ul><li> A source folder can coincide with its own output location, in which case this output can then contain library archives.
586
	 *                     However, a specific output location cannot coincidate with any library or a distinct source folder than the one referring to it. </li>
586
	 *                     However, a specific output location cannot coincide with any library or a distinct source folder than the one referring to it.<br>
587
	 *                     Note: Since 3.8, this behavior can be overridden by configuring {@link JavaCore#CORE_OUTPUT_LOCATION_OVERLAPPING_ANOTHER_SOURCE}
588
	 *                     </li>
587
	 *              <li> A source/library folder can be nested in any source folder as long as the nested folder is excluded from the enclosing one. </li>
589
	 *              <li> A source/library folder can be nested in any source folder as long as the nested folder is excluded from the enclosing one. </li>
588
	 * 			<li> An output location can be nested in a source folder, if the source folder coincidates with the project itself, or if the output
590
	 * 			<li> An output location can be nested in a source folder, if the source folder coincides with the project itself, or if the output
589
	 * 					location is excluded from the source folder.
591
	 * 					location is excluded from the source folder.
590
	 *      </ul>
592
	 *      </ul>
591
	 * </ul>
593
	 * </ul>
(-)a/org.eclipse.jdt.core/model/org/eclipse/jdt/core/JavaCore.java (-1 / +295 lines)
Lines 1-5 Link Here
1
/*******************************************************************************
1
/*******************************************************************************
2
 * Copyright (c) 2000, 2011 IBM Corporation and others.
2
 * Copyright (c) 2000, 2012 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 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
90
 *     								COMPILER_ANNOTATION_NULL_ANALYSIS
91
 *     								COMPILER_NULLABLE_ANNOTATION_NAME
92
 *     								COMPILER_NONNULL_ANNOTATION_NAME
93
 *     								COMPILER_PB_NULL_SPECIFICATION_VIOLATION
94
 *     								COMPILER_PB_POTENTIAL_NULL_SPECIFICATION_VIOLATION
95
 *     								COMPILER_PB_NULL_SPECIFICATION_INSUFFICIENT_INFO
86
 *******************************************************************************/
96
 *******************************************************************************/
87
97
88
package org.eclipse.jdt.core;
98
package org.eclipse.jdt.core;
Lines 1357-1362 Link Here
1357
	 */
1367
	 */
1358
	public static final String COMPILER_PB_POTENTIALLY_MISSING_STATIC_ON_METHOD = PLUGIN_ID + ".compiler.problem.reportMethodCanBePotentiallyStatic"; //$NON-NLS-1$
1368
	public static final String COMPILER_PB_POTENTIALLY_MISSING_STATIC_ON_METHOD = PLUGIN_ID + ".compiler.problem.reportMethodCanBePotentiallyStatic"; //$NON-NLS-1$
1359
	/**
1369
	/**
1370
	 * Compiler option ID: Reporting a resource that is not closed properly.
1371
	 * <p>When enabled, the compiler will issue an error or a warning if
1372
	 *    a local variable holds a value of type <code>java.lang.AutoCloseable</code> (compliance>=1.7) 
1373
	 *    or a value of type <code>java.io.Closeable</code> (compliance<=1.6) and if
1374
	 *    flow analysis shows that the method <code>close()</code> is not invoked locally on that value.
1375
	 * <dl>
1376
	 * <dt>Option id:</dt><dd><code>"org.eclipse.jdt.core.compiler.problem.reportUnclosedCloseable"</code></dd>
1377
	 * <dt>Possible values:</dt><dd><code>{ "error", "warning", "ignore" }</code></dd>
1378
	 * <dt>Default:</dt><dd><code>"warning"</code></dd>
1379
	 * </dl>
1380
	 * @since 3.8
1381
	 * @category CompilerOptionID
1382
	 */
1383
	public static final String COMPILER_PB_UNCLOSED_CLOSEABLE = PLUGIN_ID + ".compiler.problem.unclosedCloseable"; //$NON-NLS-1$
1384
	/**
1385
	 * Compiler option ID: Reporting a resource that may not be closed properly.
1386
	 * <p>When enabled, the compiler will issue an error or a warning if
1387
	 *    a local variable holds a value of type <code>java.lang.AutoCloseable</code> (compliance>=1.7) 
1388
	 *    or a value of type <code>java.io.Closeable</code> (compliance<=1.6) and if
1389
	 *    flow analysis shows that the method <code>close()</code> is 
1390
	 *    not invoked locally on that value for all execution paths.
1391
	 * <dl>
1392
	 * <dt>Option id:</dt><dd><code>"org.eclipse.jdt.core.compiler.problem.reportPotentiallyUnclosedCloseable"</code></dd>
1393
	 * <dt>Possible values:</dt><dd><code>{ "error", "warning", "ignore" }</code></dd>
1394
	 * <dt>Default:</dt><dd><code>"ignore"</code></dd>
1395
	 * </dl>
1396
	 * @since 3.8
1397
	 * @category CompilerOptionID
1398
	 */
1399
	public static final String COMPILER_PB_POTENTIALLY_UNCLOSED_CLOSEABLE = PLUGIN_ID + ".compiler.problem.potentiallyUnclosedCloseable"; //$NON-NLS-1$
1400
	/**
1401
	 * Compiler option ID: Reporting a resource that is not managed by try-with-resources.
1402
	 * <p>When enabled, the compiler will issue an error or a warning if a local variable 
1403
	 * 	  holds a value of type <code>java.lang.AutoCloseable</code>, and if the method
1404
	 *    <code>close()</code> is explicitly invoked on that resource, but the resource is
1405
	 *    not managed by a try-with-resources block.
1406
	 * <dl>
1407
	 * <dt>Option id:</dt><dd><code>"org.eclipse.jdt.core.compiler.problem.reportPotentiallyUnclosedCloseable"</code></dd>
1408
	 * <dt>Possible values:</dt><dd><code>{ "error", "warning", "ignore" }</code></dd>
1409
	 * <dt>Default:</dt><dd><code>"ignore"</code></dd>
1410
	 * </dl>
1411
	 * @since 3.8
1412
	 * @category CompilerOptionID
1413
	 */
1414
	public static final String COMPILER_PB_EXPLICITLY_CLOSED_AUTOCLOSEABLE = PLUGIN_ID + ".compiler.problem.explicitlyClosedAutoCloseable"; //$NON-NLS-1$
1415
	/**
1416
	 * Compiler option ID: Annotation-based Null Analysis.
1417
	 * <p>This option controls whether the compiler will use null annotations for
1418
	 *    improved analysis of (potential) null references.</p>
1419
	 * <p>When enabled, the compiler will interpret the annotation types defined using
1420
	 *    {@link #COMPILER_NONNULL_ANNOTATION_NAME} and {@link #COMPILER_NULLABLE_ANNOTATION_NAME}
1421
	 *    as specifying whether or not a given type includes the value <code>null</code>.</p>
1422
	 * <p>The effect of these analyses is further controlled by the options
1423
	 *    {@link #COMPILER_PB_NULL_SPECIFICATION_VIOLATION},
1424
	 *    {@link #COMPILER_PB_POTENTIAL_NULL_SPECIFICATION_VIOLATION} and
1425
	 *    {@link #COMPILER_PB_NULL_SPECIFICATION_INSUFFICIENT_INFO}.
1426
	 * </p>
1427
	 * <dl>
1428
	 * <dt>Option id:</dt><dd><code>"org.eclipse.jdt.core.compiler.annotation.nullanalysis"</code></dd>
1429
	 * <dt>Possible values:</dt><dd><code>{ "disabled", "enabled" }</code></dd>
1430
	 * <dt>Default:</dt><dd><code>"disabled"</code></dd>
1431
	 * </dl>
1432
	 * @since 3.8
1433
	 * @category CompilerOptionID
1434
	 */
1435
	public static final String COMPILER_ANNOTATION_NULL_ANALYSIS = PLUGIN_ID + ".compiler.annotation.nullanalysis"; //$NON-NLS-1$
1436
	/**
1437
	 * Compiler option ID: Name of Annotation Type for Nullable Types.
1438
	 * <p>This option defines a fully qualified Java type name that the compiler may use
1439
	 *    to perform special null analysis.</p>
1440
	 * <p>If the annotation specified by this option is applied to a type in a method
1441
	 *    signature or variable declaration, this will be interpreted as a specification
1442
	 *    that <code>null</code> is a legal value in that position. Currently supported
1443
	 *    positions are: method parameters, method return type and local variables.</p>
1444
	 * <p>If a value whose type
1445
	 *    is annotated with this annotation is dereferenced without checking for null,
1446
	 *    the compiler will trigger a diagnostic as further controlled by
1447
	 *    {@link #COMPILER_PB_POTENTIAL_NULL_REFERENCE}.</p>
1448
	 * <p>The compiler may furthermore check adherence to the null specification as
1449
	 *    further controlled by {@link #COMPILER_PB_NULL_SPECIFICATION_VIOLATION},
1450
	 *    {@link #COMPILER_PB_POTENTIAL_NULL_SPECIFICATION_VIOLATION} and
1451
	 *    {@link #COMPILER_PB_NULL_SPECIFICATION_INSUFFICIENT_INFO}.</p>
1452
	 * <p>This option only has an effect if the option {@link #COMPILER_ANNOTATION_NULL_ANALYSIS} is enabled.</p>
1453
	 * <dl>
1454
	 * <dt>Option id:</dt><dd><code>"org.eclipse.jdt.core.compiler.annotation.nullable"</code></dd>
1455
	 * <dt>Possible values:</dt><dd>any legal, fully qualified Java type name; must resolve to an annotation type.</dd>
1456
	 * <dt>Default:</dt><dd><code>"org.eclipse.jdt.annotation.Nullable"</code></dd>
1457
	 * </dl>
1458
	 * @since 3.8
1459
	 * @category CompilerOptionID
1460
	 */
1461
	public static final String COMPILER_NULLABLE_ANNOTATION_NAME = PLUGIN_ID + ".compiler.annotation.nullable"; //$NON-NLS-1$
1462
	/**
1463
	 * Compiler option ID: Name of Annotation Type for Non-Null Types.
1464
	 * <p>This option defines a fully qualified Java type name that the compiler may use
1465
	 *    to perform special null analysis.</p>
1466
	 * <p>If the annotation specified by this option is applied to a type in a method
1467
	 *    signature or variable declaration, this will be interpreted as a specification
1468
	 *    that <code>null</code> is <b>not</b> a legal value in that position. Currently
1469
	 *    supported positions are: method parameters, method return type and local variables.</p>
1470
	 * <p>For values declared with this annotation, the compiler will never trigger a null
1471
	 *    reference diagnostic (as controlled by {@link #COMPILER_PB_POTENTIAL_NULL_REFERENCE}
1472
	 *    and {@link #COMPILER_PB_NULL_REFERENCE}), because the assumption is made that null
1473
	 *    will never occur at runtime in these positions.</p>
1474
	 * <p>The compiler may furthermore check adherence to the null specification as further
1475
	 *    controlled by {@link #COMPILER_PB_NULL_SPECIFICATION_VIOLATION},
1476
	 *    {@link #COMPILER_PB_POTENTIAL_NULL_SPECIFICATION_VIOLATION} and
1477
	 *    {@link #COMPILER_PB_NULL_SPECIFICATION_INSUFFICIENT_INFO}.</p>
1478
	 * <p>This option only has an effect if the option {@link #COMPILER_ANNOTATION_NULL_ANALYSIS} is enabled.</p>
1479
	 * <dl>
1480
	 * <dt>Option id:</dt><dd><code>"org.eclipse.jdt.core.compiler.annotation.nonnull"</code></dd>
1481
	 * <dt>Possible values:</dt><dd>any legal, fully qualified Java type name; must resolve to an annotation type.</dd>
1482
	 * <dt>Default:</dt><dd><code>"org.eclipse.jdt.annotation.NonNull"</code></dd>
1483
	 * </dl>
1484
	 * @since 3.8
1485
	 * @category CompilerOptionID
1486
	 */
1487
	public static final String COMPILER_NONNULL_ANNOTATION_NAME = PLUGIN_ID + ".compiler.annotation.nonnull"; //$NON-NLS-1$
1488
	/**
1489
	 * Compiler option ID: Name of Annotation Type to specify a nullness default for unannotated types.
1490
	 * <p>This option defines a fully qualified Java type name that the compiler may use
1491
	 *    to perform special null analysis.</p>
1492
	 * <p>If the annotation is applied without an argument, all unannotated types in method signatures
1493
	 *    within the annotated element will be treated as if they were specified with the non-null annotation
1494
	 *    (see {@link #COMPILER_NONNULL_ANNOTATION_NAME}).</p>
1495
	 * <p>If the annotation is applied with the constant <code>false</code> as its argument
1496
	 *    all corresponding defaults at outer scopes will be canceled for the annotated element.
1497
	 *    This includes defaults specified using this annotation type or a default defined using
1498
	 *    the compiler option {@link #COMPILER_NONNULL_IS_DEFAULT}.</p>
1499
	 * <p>This option only has an effect if the option {@link #COMPILER_ANNOTATION_NULL_ANALYSIS} is enabled.</p>
1500
	 * <dl>
1501
	 * <dt>Option id:</dt><dd><code>"org.eclipse.jdt.core.compiler.annotation.nonnullbydefault"</code></dd>
1502
	 * <dt>Possible values:</dt><dd>any legal, fully qualified Java type name; must resolve to an annotation type.
1503
	 *     That annotation type should have exactly one boolean parameter.</dd>
1504
	 * <dt>Default:</dt><dd><code>"org.eclipse.jdt.annotation.NonNullByDefault"</code></dd>
1505
	 * </dl>
1506
	 * @since 3.8
1507
	 * @category CompilerOptionID
1508
	 */
1509
	public static final String COMPILER_NONNULL_BY_DEFAULT_ANNOTATION_NAME = PLUGIN_ID + ".compiler.annotation.nonnullbydefault"; //$NON-NLS-1$
1510
	/**
1511
	 * Compiler option ID: Globally specify non-null as the assumed default for unannotated types.
1512
	 * <p>When enabled, this option globally achieves the same effect 
1513
	 *    as specifying {@link #COMPILER_NONNULL_ANNOTATION_NAME} does for individual elements.</p>
1514
	 * <p>This option only has an effect if the option {@link #COMPILER_ANNOTATION_NULL_ANALYSIS} is enabled.</p>
1515
	 * <dl>
1516
	 * <dt>Option id:</dt><dd><code>"org.eclipse.jdt.core.compiler.annotation.nonnullisdefault"</code></dd>
1517
	 * <dt>Possible values:</dt><dd><code>{ "disabled", "enabled" }</code>.</dd>
1518
	 * <dt>Default:</dt><dd><code>"disabled"</code></dd>
1519
	 * </dl>
1520
	 * @since 3.8
1521
	 * @category CompilerOptionID
1522
	 */
1523
	public static final String COMPILER_NONNULL_IS_DEFAULT = PLUGIN_ID + ".compiler.annotation.nonnullisdefault"; //$NON-NLS-1$
1524
	/**
1525
	 * Compiler option ID: Reporting Violations of Null Specifications.
1526
	 * <p>Depending on this option, the compiler will issue either an error or a warning
1527
	 *    whenever one of the following situations is detected:
1528
	 *    <ol>
1529
	 *    <li>A method declared with a nonnull annotation returns an expression	that is
1530
	 *          statically known to evaluate to a null value.</li>
1531
	 *    <li>An expression that is statically known to evaluate to a null value is	passed
1532
	 *        as an argument in a method call where the corresponding parameter of the called
1533
	 *        method is declared with a nonnull annotation.</li>
1534
	 *    <li>An expression that is statically known to evaluate to a null value is	assigned
1535
	 *        to a local variable that is declared with a nonnull annotation.</li>
1536
	 *    <li>A method that overrides an inherited method declared with a nonnull annotation
1537
	 *        tries to relax that contract by specifying a nullable annotation
1538
	 *        (prohibition of contravariant return).</li>
1539
	 *    <li>A method that overrides an inherited method which has a nullable declaration
1540
	 *        for at least one of its parameters, tries to tighten that null contract by
1541
	 *        specifying a nonnull annotation for its corresponding parameter
1542
	 *        (prohibition of covariant parameters).</li>
1543
	 *    </ol>
1544
	 * </p>
1545
	 * <p>The compiler options {@link #COMPILER_NONNULL_ANNOTATION_NAME} and
1546
	 *    {@link #COMPILER_NULLABLE_ANNOTATION_NAME} control which annotations the compiler
1547
	 *    shall interpret as nonnull or nullable annotations, respectively.
1548
	 * </p>
1549
	 * <p>This option only has an effect if the option {@link #COMPILER_ANNOTATION_NULL_ANALYSIS} is enabled.</p>
1550
	 * <dl>
1551
	 * <dt>Option id:</dt><dd><code>"org.eclipse.jdt.core.compiler.problem.nullSpecViolation"</code></dd>
1552
	 * <dt>Possible values:</dt><dd><code>{ "error", "warning" }</code></dd>
1553
	 * <dt>Default:</dt><dd><code>"error"</code></dd>
1554
	 * </dl>
1555
	 * @since 3.8
1556
	 * @category CompilerOptionID
1557
	 */
1558
	public static final String COMPILER_PB_NULL_SPECIFICATION_VIOLATION = PLUGIN_ID + ".compiler.problem.nullSpecViolation"; //$NON-NLS-1$
1559
	/**
1560
	 * Compiler option ID: Reporting Violations of Null Specifications with Potential Null Value.
1561
	 * <p>When enabled, the compiler will issue an error or a warning whenever one of the
1562
	 *    following situations is detected:
1563
	 *    <ol>
1564
	 *    <li>A method declared with a nonnull annotation returns an expression that is
1565
	 *          statically known to evaluate to a null value on some flow.</li>
1566
	 *    <li>An expression that is statically known to evaluate to a null value on some flow
1567
	 *        is passed as an argument in a method call where the corresponding parameter of
1568
	 *        the called method is declared with a nonnull annotation.</li>
1569
	 *    <li>An expression that is statically known to evaluate to a null value on some flow
1570
	 *        is assigned to a local variable that is declared with a nonnull annotation.</li>
1571
	 *    </ol>
1572
	 * </p>
1573
	 * <p>The compiler options {@link #COMPILER_NONNULL_ANNOTATION_NAME} and
1574
	 *    {@link #COMPILER_NULLABLE_ANNOTATION_NAME} control which annotations the compiler
1575
	 *    shall interpret as nonnull or nullable annotations, respectively.
1576
	 * </p>
1577
	 * <p>This option only has an effect if the option {@link #COMPILER_ANNOTATION_NULL_ANALYSIS} is enabled.</p>
1578
	 * <dl>
1579
	 * <dt>Option id:</dt><dd><code>"org.eclipse.jdt.core.compiler.problem.potentialNullSpecViolation"</code></dd>
1580
	 * <dt>Possible values:</dt><dd><code>{ "error", "warning", "ignore" }</code></dd>
1581
	 * <dt>Default:</dt><dd><code>"error"</code></dd>
1582
	 * </dl>
1583
	 * @since 3.8
1584
	 * @category CompilerOptionID
1585
	 */
1586
	public static final String COMPILER_PB_POTENTIAL_NULL_SPECIFICATION_VIOLATION = PLUGIN_ID + ".compiler.problem.potentialNullSpecViolation"; //$NON-NLS-1$
1587
	/**
1588
	 * Compiler option ID: Reporting Insufficient Information for Analysing Adherence to Null Specifications.
1589
	 * <p>When enabled, the compiler will issue an error or a warning whenever one of the
1590
	 *    following situations is detected:
1591
	 *    <ol>
1592
	 *    <li>A method declared with a nonnull annotation returns an expression for which
1593
	 *        insufficient nullness information is available for statically proving that no
1594
	 *        flow will pass a null value at runtime.</li>
1595
	 *    <li>An expression for which insufficient nullness information is available for
1596
	 *        statically proving that it will never evaluate to a null value at runtime
1597
	 *        is passed as an argument in a method call where the corresponding parameter of
1598
	 *        the called method is declared with a nonnull annotation.</li>
1599
	 *    <li>An expression for which insufficient nullness information is available for
1600
	 *        statically proving that it will never evaluate to a null value at runtime
1601
	 *        is assigned to a local variable that is declared with a nonnull annotation.</li>
1602
	 *    </ol>
1603
	 *    Insufficient nullness information is usually a consequence of using other unannotated
1604
	 *    variables or methods.
1605
	 * </p>
1606
	 * <p>The compiler options {@link #COMPILER_NONNULL_ANNOTATION_NAME} and
1607
	 *    {@link #COMPILER_NULLABLE_ANNOTATION_NAME} control which annotations the compiler
1608
	 *    shall interpret as nonnull or nullable annotations, respectively.
1609
	 * </p>
1610
	 * <p>This option only has an effect if the option {@link #COMPILER_ANNOTATION_NULL_ANALYSIS} is enabled.</p>
1611
	 * <dl>
1612
	 * <dt>Option id:</dt><dd><code>"org.eclipse.jdt.core.compiler.problem.nullSpecInsufficientInfo"</code></dd>
1613
	 * <dt>Possible values:</dt><dd><code>{ "error", "warning", "ignore" }</code></dd>
1614
	 * <dt>Default:</dt><dd><code>"warning"</code></dd>
1615
	 * </dl>
1616
	 * @since 3.8
1617
	 * @category CompilerOptionID
1618
	 */
1619
	public static final String COMPILER_PB_NULL_SPECIFICATION_INSUFFICIENT_INFO = PLUGIN_ID + ".compiler.problem.nullSpecInsufficientInfo"; //$NON-NLS-1$
1620
	/**
1621
	 * Compiler option ID: Reporting Redundant Null Annotations.
1622
	 * <p>When enabled, the compiler will issue an error or a warning when a non-null annotation
1623
	 *    (see {@link #COMPILER_NONNULL_ANNOTATION_NAME})
1624
	 *    is applied although the same effect is already achieved by a default applicable at the
1625
	 *    current location. Such a default may be set by enabling the option
1626
	 *    {@link #COMPILER_NONNULL_IS_DEFAULT} or by using the annotation specified by the option
1627
	 *    {@link #COMPILER_NONNULL_BY_DEFAULT_ANNOTATION_NAME}.
1628
	 * </p>
1629
	 * <p>This option only has an effect if the option {@link #COMPILER_ANNOTATION_NULL_ANALYSIS} is enabled.</p>
1630
	 * <dl>
1631
	 * <dt>Option id:</dt><dd><code>"org.eclipse.jdt.core.compiler.problem.redundantNullAnnotation"</code></dd>
1632
	 * <dt>Possible values:</dt><dd><code>{ "error", "warning", "ignore" }</code></dd>
1633
	 * <dt>Default:</dt><dd><code>"warning"</code></dd>
1634
	 * </dl>
1635
	 * @since 3.8
1636
	 * @category CompilerOptionID
1637
	 */
1638
	public static final String COMPILER_PB_REDUNDANT_NULL_ANNOTATION = PLUGIN_ID + ".compiler.problem.redundantNullAnnotation"; //$NON-NLS-1$
1639
	/**
1360
	 * Compiler option ID: Setting Source Compatibility Mode.
1640
	 * 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
1641
	 * <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
1642
	 *    reserved for assertion support. Also note, than when toggling to 1.4 mode, the target VM
Lines 1828-1833 Link Here
1828
	 * @category CoreOptionID
2108
	 * @category CoreOptionID
1829
	 */
2109
	 */
1830
	public static final String CORE_ENABLE_CLASSPATH_MULTIPLE_OUTPUT_LOCATIONS = PLUGIN_ID + ".classpath.multipleOutputLocations"; //$NON-NLS-1$
2110
	public static final String CORE_ENABLE_CLASSPATH_MULTIPLE_OUTPUT_LOCATIONS = PLUGIN_ID + ".classpath.multipleOutputLocations"; //$NON-NLS-1$
2111
	/**
2112
	 * Core option ID: Reporting an output location overlapping another source location.
2113
	 * <p> Indicate the severity of the problem reported when a source entry's output location overlaps another
2114
	 * source entry. </p>
2115
	 * 
2116
	 * <dl>
2117
	 * <dt>Option id:</dt><dd><code>"org.eclipse.jdt.core.classpath.outputOverlappingAnotherSource"</code></dd>
2118
	 * <dt>Possible values:</dt><dd><code>{ "error", "warning", "ignore" }</code></dd>
2119
	 * <dt>Default:</dt><dd><code>"error"</code></dd>
2120
	 * </dl>
2121
	 * @since 3.6.4
2122
	 */
2123
	public static final String CORE_OUTPUT_LOCATION_OVERLAPPING_ANOTHER_SOURCE = PLUGIN_ID + ".classpath.outputOverlappingAnotherSource";  //$NON-NLS-1$
1831
	/**
2124
	/**
1832
	 * Core option ID: Set the timeout value for retrieving the method's parameter names from javadoc.
2125
	 * Core option ID: Set the timeout value for retrieving the method's parameter names from javadoc.
1833
	 * <p>Timeout in milliseconds to retrieve the method's parameter names from javadoc.
2126
	 * <p>Timeout in milliseconds to retrieve the method's parameter names from javadoc.
Lines 3684-3689 Link Here
3684
							try {
3977
							try {
3685
								if (JavaBuilder.DEBUG)
3978
								if (JavaBuilder.DEBUG)
3686
									System.out.println("Touching " + project.getElementName()); //$NON-NLS-1$
3979
									System.out.println("Touching " + project.getElementName()); //$NON-NLS-1$
3980
								new ClasspathValidation((JavaProject) project).validate(); // https://bugs.eclipse.org/bugs/show_bug.cgi?id=287164
3687
								project.getProject().touch(progressMonitor2);
3981
								project.getProject().touch(progressMonitor2);
3688
							} catch (CoreException e) {
3982
							} catch (CoreException e) {
3689
								// could not touch this project: ignore
3983
								// could not touch this project: ignore
(-)a/org.eclipse.jdt.core/model/org/eclipse/jdt/core/util/ByteCodeVisitorAdapter.java (-2 / +13 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 923-930 Link Here
923
		// default behavior is to do nothing
923
		// default behavior is to do nothing
924
	}
924
	}
925
	/**
925
	/**
926
	 * @see IBytecodeVisitor#_invokeinterface(int, int, byte, IConstantPoolEntry)
926
	 * @see IBytecodeVisitor#_invokedynamic(int, int, IConstantPoolEntry, IConstantPoolEntry)
927
	 * @since 3.6
927
	 * @since 3.6
928
	 * @deprecated This has been replaced with {@link IBytecodeVisitor#_invokedynamic(int, int, IConstantPoolEntry)}
928
	 */
929
	 */
929
	public void _invokedynamic(
930
	public void _invokedynamic(
930
			int pc,
931
			int pc,
Lines 934-939 Link Here
934
		// default behavior is to do nothing
935
		// default behavior is to do nothing
935
	}
936
	}
936
	/**
937
	/**
938
	 * @see IBytecodeVisitor#_invokedynamic(int, int, IConstantPoolEntry)
939
	 * @since 3.8
940
	 */
941
	public void _invokedynamic(
942
			int pc,
943
			int index,
944
			IConstantPoolEntry invokeDynamicEntry) {
945
		// default behavior is to do nothing
946
	}
947
	/**
937
	 * @see IBytecodeVisitor#_invokeinterface(int, int, byte, IConstantPoolEntry)
948
	 * @see IBytecodeVisitor#_invokeinterface(int, int, byte, IConstantPoolEntry)
938
	 */
949
	 */
939
	public void _invokeinterface(
950
	public void _invokeinterface(
(-)a/org.eclipse.jdt.core/model/org/eclipse/jdt/core/util/IAttributeNamesConstants.java (-1 / +7 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 140-143 Link Here
140
	 * @since 3.2
140
	 * @since 3.2
141
	 */
141
	 */
142
	char[] STACK_MAP = "StackMap".toCharArray(); //$NON-NLS-1$
142
	char[] STACK_MAP = "StackMap".toCharArray(); //$NON-NLS-1$
143
	
144
	/**
145
	 * "BootstrapMethods" attribute (added in cldc1.0).
146
	 * @since 3.8
147
	 */
148
	char[] BOOTSTRAP_METHODS = "BootstrapMethods".toCharArray(); //$NON-NLS-1$
143
}
149
}
(-)a/org.eclipse.jdt.core/model/org/eclipse/jdt/core/util/IBootstrapMethodsAttribute.java (+40 lines)
Added Link Here
1
/*******************************************************************************
2
 * Copyright (c) 2011 IBM Corporation and others.
3
 * All rights reserved. This program and the accompanying materials
4
 * are made available under the terms of the Eclipse Public License v1.0
5
 * which accompanies this distribution, and is available at
6
 * http://www.eclipse.org/legal/epl-v10.html
7
 *
8
 * Contributors:
9
 *     IBM Corporation - initial API and implementation
10
 *******************************************************************************/
11
package org.eclipse.jdt.core.util;
12
13
/**
14
 * Description of a bootstrap methods attribute as described in the JVM specifications.
15
 *
16
 * This interface may be implemented by clients.
17
 *
18
 * @since 3.8
19
 */
20
public interface IBootstrapMethodsAttribute extends IClassFileAttribute {
21
22
	/**
23
	 * Answer back the number of bootstrap methods of this entry as specified in
24
	 * the JVM specifications.
25
	 *
26
	 * @return the number of bootstrap methods of this entry as specified in
27
	 * the JVM specifications
28
	 */
29
	int getBootstrapMethodsLength();
30
31
	/**
32
	 * Answer back the bootstrap methods table of this entry as specified in
33
	 * the JVM specifications. Answer an empty array if none.
34
	 *
35
	 * @return the bootstrap methods table of this entry as specified in
36
	 * the JVM specifications. Answer an empty array if none
37
	 */
38
	IBootstrapMethodsEntry[] getBootstrapMethods();
39
40
}
(-)a/org.eclipse.jdt.core/model/org/eclipse/jdt/core/util/IBootstrapMethodsEntry.java (+24 lines)
Added Link Here
1
/*******************************************************************************
2
 * Copyright (c) 2011 IBM Corporation and others.
3
 * All rights reserved. This program and the accompanying materials
4
 * are made available under the terms of the Eclipse Public License v1.0
5
 * which accompanies this distribution, and is available at
6
 * http://www.eclipse.org/legal/epl-v10.html
7
 *
8
 * Contributors:
9
 *     IBM Corporation - initial API and implementation
10
 *******************************************************************************/
11
package org.eclipse.jdt.core.util;
12
13
/**
14
 * Description of a bootstrap method table entry as specified in the JVM specifications.
15
 *
16
 * This interface may be implemented by clients.
17
 *
18
 * @since 3.8
19
 */
20
public interface IBootstrapMethodsEntry {
21
22
	int getBootstrapMethodReference();
23
	int[] getBootstrapArguments();
24
}
(-)a/org.eclipse.jdt.core/model/org/eclipse/jdt/core/util/IBytecodeVisitor.java (-1 / +9 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 168-179 Link Here
168
		IConstantPoolEntry constantClass);
168
		IConstantPoolEntry constantClass);
169
	/**
169
	/**
170
	 * @since 3.6
170
	 * @since 3.6
171
	 * @deprecated This has been replaced with {@link #_invokedynamic(int, int, IConstantPoolEntry)}
171
	 */
172
	 */
172
	void _invokedynamic(
173
	void _invokedynamic(
173
			int pc,
174
			int pc,
174
			int index,
175
			int index,
175
			IConstantPoolEntry nameEntry,
176
			IConstantPoolEntry nameEntry,
176
			IConstantPoolEntry descriptorEntry);
177
			IConstantPoolEntry descriptorEntry);
178
	/**
179
	 * @since 3.8
180
	 */
181
	void _invokedynamic(
182
			int pc,
183
			int index,
184
			IConstantPoolEntry invokeDynamic);
177
	void _invokeinterface(
185
	void _invokeinterface(
178
		int pc,
186
		int pc,
179
		int index,
187
		int index,
(-)a/org.eclipse.jdt.core/model/org/eclipse/jdt/core/util/IConstantPool.java (-6 / +8 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 27-34 Link Here
27
	int getConstantPoolCount();
27
	int getConstantPoolCount();
28
28
29
	/**
29
	/**
30
	 * Answer back the type of the entry at the index @index
30
	 * Answer back the type of the entry at the given index in the constant pool.
31
	 * in the constant pool.
32
	 *
31
	 *
33
	 * @param index the index of the entry in the constant pool
32
	 * @param index the index of the entry in the constant pool
34
	 * @return the type of the entry at the index @index in the constant pool
33
	 * @return the type of the entry at the index @index in the constant pool
Lines 36-46 Link Here
36
	int getEntryKind(int index);
35
	int getEntryKind(int index);
37
36
38
	/**
37
	/**
39
	 * Answer back the entry at the index @index
38
	 * Answer back the entry at the given index in the constant pool.
40
	 * in the constant pool.
39
	 * 
40
	 * <p>The return value can be an instance of {@link IConstantPoolEntry2} if the value returned
41
	 * by {@link #getEntryKind(int)} is either {@link IConstantPoolConstant#CONSTANT_MethodHandle},
42
	 * {@link IConstantPoolConstant#CONSTANT_MethodType} or {@link IConstantPoolConstant#CONSTANT_InvokeDynamic}.</p>
41
	 *
43
	 *
42
	 * @param index the index of the entry in the constant pool
44
	 * @param index the index of the entry in the constant pool
43
	 * @return the entry at the index @index in the constant pool
45
	 * @return the entry at the given index in the constant pool
44
	 */
46
	 */
45
	IConstantPoolEntry decodeEntry(int index);
47
	IConstantPoolEntry decodeEntry(int index);
46
}
48
}
(-)a/org.eclipse.jdt.core/model/org/eclipse/jdt/core/util/IConstantPoolConstant.java (-1 / +70 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 29-34 Link Here
29
	int CONSTANT_Double = 6;
29
	int CONSTANT_Double = 6;
30
	int CONSTANT_NameAndType = 12;
30
	int CONSTANT_NameAndType = 12;
31
	int CONSTANT_Utf8 = 1;
31
	int CONSTANT_Utf8 = 1;
32
	/**
33
	 * @since 3.8
34
	 */
35
	int CONSTANT_MethodHandle = 15;
36
	/**
37
	 * @since 3.8
38
	 */
39
	int CONSTANT_MethodType = 16;
40
	/**
41
	 * @since 3.8
42
	 */
43
	int CONSTANT_InvokeDynamic = 18;
32
44
33
	int CONSTANT_Methodref_SIZE = 5;
45
	int CONSTANT_Methodref_SIZE = 5;
34
	int CONSTANT_Class_SIZE = 3;
46
	int CONSTANT_Class_SIZE = 3;
Lines 41-45 Link Here
41
	int CONSTANT_String_SIZE = 3;
53
	int CONSTANT_String_SIZE = 3;
42
	int CONSTANT_Utf8_SIZE = 3;
54
	int CONSTANT_Utf8_SIZE = 3;
43
	int CONSTANT_NameAndType_SIZE = 5;
55
	int CONSTANT_NameAndType_SIZE = 5;
56
	/**
57
	 * @since 3.8
58
	 */
59
	int CONSTANT_MethodHandle_SIZE = 4;
60
	/**
61
	 * @since 3.8
62
	 */
63
	int CONSTANT_MethodType_SIZE = 3;
64
	/**
65
	 * @since 3.8
66
	 */
67
	int CONSTANT_InvokeDynamic_SIZE = 5;
44
68
69
	/**
70
	 * The constant is described at 5.4.3.5 in the Java 7 VM specification (part 3).
71
	 * @since 3.8
72
	 */
73
	int METHOD_TYPE_REF_GetField = 1;
74
	/**
75
	 * The constant is described at 5.4.3.5 in the Java 7 VM specification (part 3).
76
	 * @since 3.8
77
	 */
78
	int METHOD_TYPE_REF_GetStatic = 2;
79
	/**
80
	 * The constant is described at 5.4.3.5 in the Java 7 VM specification (part 3).
81
	 * @since 3.8
82
	 */
83
	int METHOD_TYPE_REF_PutField = 3;
84
	/**
85
	 * The constant is described at 5.4.3.5 in the Java 7 VM specification (part 3).
86
	 * @since 3.8
87
	 */
88
	int METHOD_TYPE_REF_PutStatic = 4;
89
	/**
90
	 * The constant is described at 5.4.3.5 in the Java 7 VM specification (part 3).
91
	 * @since 3.8
92
	 */
93
	int METHOD_TYPE_REF_InvokeVirtual = 5;
94
	/**
95
	 * The constant is described at 5.4.3.5 in the Java 7 VM specification (part 3).
96
	 * @since 3.8
97
	 */
98
	int METHOD_TYPE_REF_InvokeStatic = 6;
99
	/**
100
	 * The constant is described at 5.4.3.5 in the Java 7 VM specification (part 3).
101
	 * @since 3.8
102
	 */
103
	int METHOD_TYPE_REF_InvokeSpecial = 7;
104
	/**
105
	 * The constant is described at 5.4.3.5 in the Java 7 VM specification (part 3).
106
	 * @since 3.8
107
	 */
108
	int METHOD_TYPE_REF_NewInvokeSpecial = 8;
109
	/**
110
	 * The constant is described at 5.4.3.5 in the Java 7 VM specification (part 3).
111
	 * @since 3.8
112
	 */
113
	int METHOD_TYPE_REF_InvokeInterface = 9;
45
}
114
}
(-)a/org.eclipse.jdt.core/model/org/eclipse/jdt/core/util/IConstantPoolEntry.java (-10 / +47 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 32-37 Link Here
32
	 * The value is unspecified otherwise.
32
	 * The value is unspecified otherwise.
33
	 *
33
	 *
34
	 * @return the name index for a CONSTANT_Class type entry
34
	 * @return the name index for a CONSTANT_Class type entry
35
	 * @see IConstantPoolConstant#CONSTANT_Class
35
	 */
36
	 */
36
	int getClassInfoNameIndex();
37
	int getClassInfoNameIndex();
37
38
Lines 42-57 Link Here
42
	 *
43
	 *
43
	 * @return the class index for a CONSTANT_Fieldref,
44
	 * @return the class index for a CONSTANT_Fieldref,
44
	 * CONSTANT_Methodref, CONSTANT_InterfaceMethodref type entry
45
	 * CONSTANT_Methodref, CONSTANT_InterfaceMethodref type entry
46
	 * @see IConstantPoolConstant#CONSTANT_Fieldref
47
	 * @see IConstantPoolConstant#CONSTANT_Methodref
48
	 * @see IConstantPoolConstant#CONSTANT_InterfaceMethodref
45
	 */
49
	 */
46
	int getClassIndex();
50
	int getClassIndex();
47
51
48
	/**
52
	/**
49
	 * Returns the nameAndType index for a CONSTANT_Fieldref,
53
	 * Returns the nameAndType index for a CONSTANT_Fieldref,
50
	 * CONSTANT_Methodref, CONSTANT_InterfaceMethodref type entry.
54
	 * CONSTANT_Methodref, CONSTANT_InterfaceMethodref,
55
	 * CONSTANT_InvokeDynamic type entry.
51
	 * The value is unspecified otherwise.
56
	 * The value is unspecified otherwise.
52
	 *
57
	 *
53
	 * @return the nameAndType index for a CONSTANT_Fieldref,
58
	 * @return the nameAndType index for a CONSTANT_Fieldref,
54
	 * CONSTANT_Methodref, CONSTANT_InterfaceMethodref type entry
59
	 * CONSTANT_Methodref, CONSTANT_InterfaceMethodref,
60
	 * CONSTANT_InvokeDynamic type entry
61
	 * @see IConstantPoolConstant#CONSTANT_Fieldref
62
	 * @see IConstantPoolConstant#CONSTANT_Methodref
63
	 * @see IConstantPoolConstant#CONSTANT_InterfaceMethodref
64
	 * @see IConstantPoolConstant#CONSTANT_InvokeDynamic
55
	 */
65
	 */
56
	int getNameAndTypeIndex();
66
	int getNameAndTypeIndex();
57
67
Lines 60-65 Link Here
60
	 * The value is unspecified otherwise.
70
	 * The value is unspecified otherwise.
61
	 *
71
	 *
62
	 * @return the string index for a CONSTANT_String type entry
72
	 * @return the string index for a CONSTANT_String type entry
73
	 * @see IConstantPoolConstant#CONSTANT_String
63
	 */
74
	 */
64
	int getStringIndex();
75
	int getStringIndex();
65
76
Lines 68-73 Link Here
68
	 * Returns null otherwise.
79
	 * Returns null otherwise.
69
	 *
80
	 *
70
	 * @return the string value for a CONSTANT_String type entry
81
	 * @return the string value for a CONSTANT_String type entry
82
	 * @see IConstantPoolConstant#CONSTANT_String
71
	 */
83
	 */
72
	String getStringValue();
84
	String getStringValue();
73
85
Lines 76-81 Link Here
76
	 * The value is unspecified otherwise.
88
	 * The value is unspecified otherwise.
77
	 *
89
	 *
78
	 * @return the integer value for a CONSTANT_Integer type entry
90
	 * @return the integer value for a CONSTANT_Integer type entry
91
	 * @see IConstantPoolConstant#CONSTANT_Integer
79
	 */
92
	 */
80
	int getIntegerValue();
93
	int getIntegerValue();
81
94
Lines 84-89 Link Here
84
	 * The value is unspecified otherwise.
97
	 * The value is unspecified otherwise.
85
	 *
98
	 *
86
	 * @return the float value for a CONSTANT_Float type entry
99
	 * @return the float value for a CONSTANT_Float type entry
100
	 * @see IConstantPoolConstant#CONSTANT_Float
87
	 */
101
	 */
88
	float getFloatValue();
102
	float getFloatValue();
89
103
Lines 92-97 Link Here
92
	 * The value is unspecified otherwise.
106
	 * The value is unspecified otherwise.
93
	 *
107
	 *
94
	 * @return the double value for a CONSTANT_Double type entry
108
	 * @return the double value for a CONSTANT_Double type entry
109
	 * @see IConstantPoolConstant#CONSTANT_Double
95
	 */
110
	 */
96
	double getDoubleValue();
111
	double getDoubleValue();
97
112
Lines 100-105 Link Here
100
	 * The value is unspecified otherwise.
115
	 * The value is unspecified otherwise.
101
	 *
116
	 *
102
	 * @return the long value for a CONSTANT_Long type entry
117
	 * @return the long value for a CONSTANT_Long type entry
118
	 * @see IConstantPoolConstant#CONSTANT_Long
103
	 */
119
	 */
104
	long getLongValue();
120
	long getLongValue();
105
121
Lines 108-113 Link Here
108
	 * The value is unspecified otherwise.
124
	 * The value is unspecified otherwise.
109
	 *
125
	 *
110
	 * @return the descriptor index for a CONSTANT_NameAndType type entry
126
	 * @return the descriptor index for a CONSTANT_NameAndType type entry
127
	 * @see IConstantPoolConstant#CONSTANT_NameAndType
111
	 */
128
	 */
112
	int getNameAndTypeInfoDescriptorIndex();
129
	int getNameAndTypeInfoDescriptorIndex();
113
130
Lines 116-121 Link Here
116
	 * The value is unspecified otherwise.
133
	 * The value is unspecified otherwise.
117
	 *
134
	 *
118
	 * @return the name index for a CONSTANT_NameAndType type entry
135
	 * @return the name index for a CONSTANT_NameAndType type entry
136
	 * @see IConstantPoolConstant#CONSTANT_NameAndType
119
	 */
137
	 */
120
	int getNameAndTypeInfoNameIndex();
138
	int getNameAndTypeInfoNameIndex();
121
139
Lines 124-129 Link Here
124
	 * Returns null otherwise.
142
	 * Returns null otherwise.
125
	 *
143
	 *
126
	 * @return the class name for a CONSTANT_Class type entry
144
	 * @return the class name for a CONSTANT_Class type entry
145
	 * @see IConstantPoolConstant#CONSTANT_Class
127
	 */
146
	 */
128
	char[] getClassInfoName();
147
	char[] getClassInfoName();
129
148
Lines 134-139 Link Here
134
	 *
153
	 *
135
	 * @return the class name for a CONSTANT_Fieldref,
154
	 * @return the class name for a CONSTANT_Fieldref,
136
	 * CONSTANT_Methodref, CONSTANT_InterfaceMethodref type entry
155
	 * CONSTANT_Methodref, CONSTANT_InterfaceMethodref type entry
156
	 * @see IConstantPoolConstant#CONSTANT_Fieldref
157
	 * @see IConstantPoolConstant#CONSTANT_Methodref
158
	 * @see IConstantPoolConstant#CONSTANT_InterfaceMethodref
137
	 */
159
	 */
138
	char[] getClassName();
160
	char[] getClassName();
139
161
Lines 142-157 Link Here
142
	 * Returns null otherwise.
164
	 * Returns null otherwise.
143
	 *
165
	 *
144
	 * @return the field name for a CONSTANT_Fieldref type entry
166
	 * @return the field name for a CONSTANT_Fieldref type entry
167
	 * @see IConstantPoolConstant#CONSTANT_Fieldref
145
	 */
168
	 */
146
	char[] getFieldName();
169
	char[] getFieldName();
147
170
148
	/**
171
	/**
149
	 * Returns the field name for a CONSTANT_Methodref or CONSTANT_InterfaceMethodred
172
	 * Returns the field name for a CONSTANT_Methodref, CONSTANT_InterfaceMethodref
150
	 * type entry.
173
	 * or CONSTANT_InvokeDynamic type entry.
151
	 * Returns null otherwise.
174
	 * Returns null otherwise.
152
	 *
175
	 *
153
	 * @return the field name for a CONSTANT_Methodref or CONSTANT_InterfaceMethodred
176
	 * @return the method name for a CONSTANT_Methodref, CONSTANT_InterfaceMethodref
154
	 * type entry
177
	 * or CONSTANT_InvokeDynamic type entry
178
	 * @see IConstantPoolConstant#CONSTANT_Methodref
179
	 * @see IConstantPoolConstant#CONSTANT_InterfaceMethodref
180
	 * @see IConstantPoolConstant#CONSTANT_InvokeDynamic
155
	 */
181
	 */
156
	char[] getMethodName();
182
	char[] getMethodName();
157
183
Lines 162-179 Link Here
162
	 *
188
	 *
163
	 * @return the field descriptor value for a CONSTANT_Fieldref type entry. This value
189
	 * @return the field descriptor value for a CONSTANT_Fieldref type entry. This value
164
	 * is set only when decoding the CONSTANT_Fieldref entry
190
	 * is set only when decoding the CONSTANT_Fieldref entry
191
	 * @see IConstantPoolConstant#CONSTANT_Fieldref
165
	 */
192
	 */
166
	char[] getFieldDescriptor();
193
	char[] getFieldDescriptor();
167
194
168
	/**
195
	/**
169
	 * Returns the method descriptor value for a CONSTANT_Methodref or
196
	 * Returns the method descriptor value for a CONSTANT_Methodref or
170
	 * CONSTANT_InterfaceMethodref type entry. This value is set only when decoding the
197
	 * CONSTANT_InterfaceMethodref type entry. This value is set only when decoding the
171
	 * CONSTANT_Methodref or CONSTANT_InterfaceMethodref entry.
198
	 * CONSTANT_Methodref, CONSTANT_InterfaceMethodref, CONSTANT_MethodType
199
	 * or CONSTANT_InvokeDynamic entry.
200
	 * 
172
	 * Returns null otherwise.
201
	 * Returns null otherwise.
173
	 *
202
	 *
174
	 * @return the method descriptor value for a CONSTANT_Methodref or
203
	 * @return the method descriptor value for a CONSTANT_Methodref,
175
	 * CONSTANT_InterfaceMethodref type entry. This value is set only when decoding the
204
	 * CONSTANT_InterfaceMethodref type entry. This value is set only when decoding the
176
	 * CONSTANT_Methodref or CONSTANT_InterfaceMethodref entry
205
	 * CONSTANT_Methodref, CONSTANT_InterfaceMethodref, CONSTANT_MethodType
206
	 * or CONSTANT_InvokeDynamic entry
207
	 *
208
	 * @see IConstantPoolConstant#CONSTANT_Methodref
209
	 * @see IConstantPoolConstant#CONSTANT_InterfaceMethodref
210
	 * @see IConstantPoolConstant#CONSTANT_MethodType
211
	 * @see IConstantPoolConstant#CONSTANT_InvokeDynamic
177
	 */
212
	 */
178
	char[] getMethodDescriptor();
213
	char[] getMethodDescriptor();
179
214
Lines 184-189 Link Here
184
	 *
219
	 *
185
	 * @return the utf8 value for a CONSTANT_Utf8 type entry. This value is set only when
220
	 * @return the utf8 value for a CONSTANT_Utf8 type entry. This value is set only when
186
	 * decoding a UTF8 entry
221
	 * decoding a UTF8 entry
222
	 * @see IConstantPoolConstant#CONSTANT_Utf8
187
	 */
223
	 */
188
	char[] getUtf8Value();
224
	char[] getUtf8Value();
189
225
Lines 194-199 Link Here
194
	 *
230
	 *
195
	 * @return the utf8 length for a CONSTANT_Utf8 type entry. This value is set only when
231
	 * @return the utf8 length for a CONSTANT_Utf8 type entry. This value is set only when
196
	 * decoding a UTF8 entry
232
	 * decoding a UTF8 entry
233
	 * @see IConstantPoolConstant#CONSTANT_Utf8
197
	 */
234
	 */
198
	int getUtf8Length();
235
	int getUtf8Length();
199
}
236
}
(-)a/org.eclipse.jdt.core/model/org/eclipse/jdt/core/util/IConstantPoolEntry2.java (+59 lines)
Added Link Here
1
/*******************************************************************************
2
 * Copyright (c) 2011 IBM Corporation and others.
3
 * All rights reserved. This program and the accompanying materials
4
 * are made available under the terms of the Eclipse Public License v1.0
5
 * which accompanies this distribution, and is available at
6
 * http://www.eclipse.org/legal/epl-v10.html
7
 *
8
 * Contributors:
9
 *     IBM Corporation - initial API and implementation
10
 *******************************************************************************/
11
package org.eclipse.jdt.core.util;
12
13
/**
14
 * Description of the new constant pool entry as described in the JVM specifications
15
 * added for Java 7 support.
16
 * Its contents is initialized according to its kind.
17
 *
18
 * This interface may be implemented by clients.
19
 *
20
 * @since 3.8
21
 */
22
public interface IConstantPoolEntry2 extends IConstantPoolEntry {
23
	/**
24
	 * Returns the descriptor index. This value is set only when decoding a MethodType entry.
25
	 * The value is unspecified otherwise. The corresponding UTF8 value can be retrieved by using
26
	 * {@link #getMethodDescriptor()}.
27
	 *
28
	 * @return the descriptor index. This value is set only when decoding a MethodType entry.
29
	 * @see IConstantPoolConstant#CONSTANT_MethodType
30
	 */
31
	int getDescriptorIndex();
32
33
	/**
34
	 * Returns the reference kind. This value is set only when decoding a MethodHandle entry.
35
	 * The value is unspecified otherwise.
36
	 *
37
	 * @return the reference kind. This value is set only when decoding a MethodHandle entry.
38
	 * @see IConstantPoolConstant#CONSTANT_MethodHandle
39
	 */
40
	int getReferenceKind();
41
42
	/**
43
	 * Returns the reference index. This value is set only when decoding a MethodHandle entry.
44
	 * The value is unspecified otherwise.
45
	 *
46
	 * @return the reference kind. This value is set only when decoding a MethodHandle entry.
47
	 * @see IConstantPoolConstant#CONSTANT_MethodHandle
48
	 */
49
	int getReferenceIndex();
50
	
51
	/**
52
	 * Returns the bootstrap method attribute index. This value is set only when decoding a InvokeDynamic entry.
53
	 * The value is unspecified otherwise.
54
	 *
55
	 * @return the reference kind. This value is set only when decoding a MethodHandle entry.
56
	 * @see IConstantPoolConstant#CONSTANT_InvokeDynamic
57
	 */
58
	int getBootstrapMethodAttributeIndex();
59
}
(-)a/org.eclipse.jdt.core/model/org/eclipse/jdt/internal/compiler/DocumentElementParser.java (+3 lines)
Lines 623-628 Link Here
623
			arg.annotations = new Annotation[length],
623
			arg.annotations = new Annotation[length],
624
			0,
624
			0,
625
			length);
625
			length);
626
		RecoveredType currentRecoveryType = this.currentRecoveryType();
627
		if (currentRecoveryType != null)
628
			currentRecoveryType.annotationsConsumed(arg.annotations);
626
	}
629
	}
627
	pushOnAstStack(arg);
630
	pushOnAstStack(arg);
628
	this.intArrayPtr--;
631
	this.intArrayPtr--;
(-)a/org.eclipse.jdt.core/model/org/eclipse/jdt/internal/compiler/SourceJavadocParser.java (-5 / +5 lines)
Lines 1-5 Link Here
1
/*******************************************************************************
1
/*******************************************************************************
2
 * Copyright (c) 2000, 2009 IBM Corporation and others.
2
 * Copyright (c) 2000, 2011 IBM Corporation and others.
3
 * All rights reserved. This program and the accompanying materials
3
 * All rights reserved. This program and the accompanying materials
4
 * are made available under the terms of the Eclipse Public License v1.0
4
 * are made available under the terms of the Eclipse Public License v1.0
5
 * which accompanies this distribution, and is available at
5
 * which accompanies this distribution, and is available at
Lines 93-102 Link Here
93
		this.index++;
93
		this.index++;
94
		while (this.source[this.index] == 'u')
94
		while (this.source[this.index] == 'u')
95
			this.index++;
95
			this.index++;
96
		if (!(((c1 = ScannerHelper.getNumericValue(this.source[this.index++])) > 15 || c1 < 0)
96
		if (!(((c1 = ScannerHelper.getHexadecimalValue(this.source[this.index++])) > 15 || c1 < 0)
97
				|| ((c2 = ScannerHelper.getNumericValue(this.source[this.index++])) > 15 || c2 < 0)
97
				|| ((c2 = ScannerHelper.getHexadecimalValue(this.source[this.index++])) > 15 || c2 < 0)
98
				|| ((c3 = ScannerHelper.getNumericValue(this.source[this.index++])) > 15 || c3 < 0)
98
				|| ((c3 = ScannerHelper.getHexadecimalValue(this.source[this.index++])) > 15 || c3 < 0)
99
				|| ((c4 = ScannerHelper.getNumericValue(this.source[this.index++])) > 15 || c4 < 0))) {
99
				|| ((c4 = ScannerHelper.getHexadecimalValue(this.source[this.index++])) > 15 || c4 < 0))) {
100
			first = (char) (((c1 * 16 + c2) * 16 + c3) * 16 + c4);
100
			first = (char) (((c1 * 16 + c2) * 16 + c3) * 16 + c4);
101
		} else {
101
		} else {
102
			this.index = pos;
102
			this.index = pos;
(-)a/org.eclipse.jdt.core/model/org/eclipse/jdt/internal/compiler/parser/SourceTypeConverter.java (-2 / +11 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> - TypeConverters don't set enclosingType - https://bugs.eclipse.org/bugs/show_bug.cgi?id=320841
10
 *     Stephan Herrmann <stephan@cs.tu-berlin.de> - Contributions for
11
 *     								Bug 320841 - TypeConverters don't set enclosingType
12
 *     								Bug 353474 - type converters should include more annotations
11
 *******************************************************************************/
13
 *******************************************************************************/
12
package org.eclipse.jdt.internal.compiler.parser;
14
package org.eclipse.jdt.internal.compiler.parser;
13
15
Lines 28-33 Link Here
28
import org.eclipse.jdt.core.IAnnotation;
30
import org.eclipse.jdt.core.IAnnotation;
29
import org.eclipse.jdt.core.IImportDeclaration;
31
import org.eclipse.jdt.core.IImportDeclaration;
30
import org.eclipse.jdt.core.IJavaElement;
32
import org.eclipse.jdt.core.IJavaElement;
33
import org.eclipse.jdt.core.ILocalVariable;
31
import org.eclipse.jdt.core.ISourceRange;
34
import org.eclipse.jdt.core.ISourceRange;
32
import org.eclipse.jdt.core.JavaModelException;
35
import org.eclipse.jdt.core.JavaModelException;
33
import org.eclipse.jdt.core.Signature;
36
import org.eclipse.jdt.core.Signature;
Lines 373-378 Link Here
373
		char[][] argumentNames = methodInfo.getArgumentNames();
376
		char[][] argumentNames = methodInfo.getArgumentNames();
374
		int argumentCount = argumentTypeSignatures == null ? 0 : argumentTypeSignatures.length;
377
		int argumentCount = argumentTypeSignatures == null ? 0 : argumentTypeSignatures.length;
375
		if (argumentCount > 0) {
378
		if (argumentCount > 0) {
379
			ILocalVariable[] parameters = methodHandle.getParameters();
376
			long position = ((long) start << 32) + end;
380
			long position = ((long) start << 32) + end;
377
			method.arguments = new Argument[argumentCount];
381
			method.arguments = new Argument[argumentCount];
378
			for (int i = 0; i < argumentCount; i++) {
382
			for (int i = 0; i < argumentCount; i++) {
Lines 387-392 Link Here
387
						typeReference,
391
						typeReference,
388
						ClassFileConstants.AccDefault);
392
						ClassFileConstants.AccDefault);
389
				// do not care whether was final or not
393
				// do not care whether was final or not
394
				// convert 1.5 specific constructs only if compliance is 1.5 or above
395
				if (this.has1_5Compliance) {
396
					/* convert annotations */
397
					method.arguments[i].annotations = convertAnnotations(parameters[i]);
398
				}
390
			}
399
			}
391
		}
400
		}
392
401
(-)a/org.eclipse.jdt.core/model/org/eclipse/jdt/internal/core/BasicCompilationUnit.java (-1 / +4 lines)
Lines 1-5 Link Here
1
/*******************************************************************************
1
/*******************************************************************************
2
 * Copyright (c) 2000, 2009 IBM Corporation and others.
2
 * Copyright (c) 2000, 2012 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 133-138 Link Here
133
public char[][] getPackageName() {
133
public char[][] getPackageName() {
134
	return this.packageName;
134
	return this.packageName;
135
}
135
}
136
public boolean ignoreOptionalProblems() {
137
	return false;
138
}
136
public String toString(){
139
public String toString(){
137
	return "CompilationUnit: "+new String(this.fileName); //$NON-NLS-1$
140
	return "CompilationUnit: "+new String(this.fileName); //$NON-NLS-1$
138
}
141
}
(-)a/org.eclipse.jdt.core/model/org/eclipse/jdt/internal/core/BinaryMember.java (-7 / +1 lines)
Lines 1-5 Link Here
1
/*******************************************************************************
1
/*******************************************************************************
2
 * Copyright (c) 2000, 2011 IBM Corporation and others.
2
 * Copyright (c) 2000, 2012 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 86-97 Link Here
86
	}
86
	}
87
	if ((tagBits & TagBits.AnnotationSafeVarargs) != 0) {
87
	if ((tagBits & TagBits.AnnotationSafeVarargs) != 0) {
88
		annotations.add(getAnnotation(TypeConstants.JAVA_LANG_SAFEVARARGS));
88
		annotations.add(getAnnotation(TypeConstants.JAVA_LANG_SAFEVARARGS));
89
	}
90
	if ((tagBits & TagBits.AnnotationPostConstruct) != 0) {
91
		annotations.add(getAnnotation(TypeConstants.JAVAX_ANNOTATION_POSTCONSTRUCT));
92
	}
93
	if ((tagBits & TagBits.AnnotationPreDestroy) != 0) {
94
		annotations.add(getAnnotation(TypeConstants.JAVAX_ANNOTATION_PREDESTROY));
95
	}
89
	}
96
	// note that JAVA_LANG_SUPPRESSWARNINGS and JAVA_LANG_OVERRIDE cannot appear in binaries
90
	// note that JAVA_LANG_SUPPRESSWARNINGS and JAVA_LANG_OVERRIDE cannot appear in binaries
97
	return (IAnnotation[]) annotations.toArray(new IAnnotation[annotations.size()]);
91
	return (IAnnotation[]) annotations.toArray(new IAnnotation[annotations.size()]);
(-)a/org.eclipse.jdt.core/model/org/eclipse/jdt/internal/core/ClassFileInfo.java (-7 / +1 lines)
Lines 1-5 Link Here
1
/*******************************************************************************
1
/*******************************************************************************
2
 * Copyright (c) 2000, 2011 IBM Corporation and others.
2
 * Copyright (c) 2000, 2012 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 107-118 Link Here
107
	}
107
	}
108
	if ((tagBits & TagBits.AnnotationSafeVarargs) != 0) {
108
	if ((tagBits & TagBits.AnnotationSafeVarargs) != 0) {
109
		generateStandardAnnotation(javaElement, TypeConstants.JAVA_LANG_SAFEVARARGS, Annotation.NO_MEMBER_VALUE_PAIRS, newElements);
109
		generateStandardAnnotation(javaElement, TypeConstants.JAVA_LANG_SAFEVARARGS, Annotation.NO_MEMBER_VALUE_PAIRS, newElements);
110
	}
111
	if ((tagBits & TagBits.AnnotationPostConstruct) != 0) {
112
		generateStandardAnnotation(javaElement, TypeConstants.JAVAX_ANNOTATION_POSTCONSTRUCT, Annotation.NO_MEMBER_VALUE_PAIRS, newElements);
113
	}
114
	if ((tagBits & TagBits.AnnotationPreDestroy) != 0) {
115
		generateStandardAnnotation(javaElement, TypeConstants.JAVAX_ANNOTATION_PREDESTROY, Annotation.NO_MEMBER_VALUE_PAIRS, newElements);
116
	}
110
	}
117
	// note that JAVA_LANG_SUPPRESSWARNINGS and JAVA_LANG_OVERRIDE cannot appear in binaries
111
	// note that JAVA_LANG_SUPPRESSWARNINGS and JAVA_LANG_OVERRIDE cannot appear in binaries
118
}
112
}
(-)a/org.eclipse.jdt.core/model/org/eclipse/jdt/internal/core/ClassFileWorkingCopy.java (-14 / +12 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 337935 - Test failures when run as an IDE (org.eclipse.sdk.ide)
10
 *******************************************************************************/
11
 *******************************************************************************/
11
package org.eclipse.jdt.internal.core;
12
package org.eclipse.jdt.internal.core;
12
13
Lines 81-101 Link Here
81
protected IBuffer openBuffer(IProgressMonitor pm, Object info) throws JavaModelException {
82
protected IBuffer openBuffer(IProgressMonitor pm, Object info) throws JavaModelException {
82
83
83
	// create buffer
84
	// create buffer
84
	IBuffer buffer = this.owner.createBuffer(this);
85
	IBuffer buffer = BufferManager.createBuffer(this);
85
	if (buffer == null) return null;
86
86
87
	// set the buffer source
87
	// set the buffer source
88
	if (buffer.getCharacters() == null) {
88
	IBuffer classFileBuffer = this.classFile.getBuffer();
89
		IBuffer classFileBuffer = this.classFile.getBuffer();
89
	if (classFileBuffer != null) {
90
		if (classFileBuffer != null) {
90
		buffer.setContents(classFileBuffer.getCharacters());
91
			buffer.setContents(classFileBuffer.getCharacters());
91
	} else {
92
		} else {
92
		// Disassemble
93
			// Disassemble
93
		IClassFileReader reader = ToolFactory.createDefaultClassFileReader(this.classFile, IClassFileReader.ALL);
94
			IClassFileReader reader = ToolFactory.createDefaultClassFileReader(this.classFile, IClassFileReader.ALL);
94
		Disassembler disassembler = new Disassembler();
95
			Disassembler disassembler = new Disassembler();
95
		String contents = disassembler.disassemble(reader, Util.getLineSeparator("", getJavaProject()), ClassFileBytesDisassembler.WORKING_COPY); //$NON-NLS-1$
96
			String contents = disassembler.disassemble(reader, Util.getLineSeparator("", getJavaProject()), ClassFileBytesDisassembler.WORKING_COPY); //$NON-NLS-1$
96
		buffer.setContents(contents);
97
			buffer.setContents(contents);
98
		}
99
	}
97
	}
100
98
101
	// add buffer to buffer cache
99
	// add buffer to buffer cache
(-)a/org.eclipse.jdt.core/model/org/eclipse/jdt/internal/core/ClasspathChange.java (-4 / +13 lines)
Lines 10-15 Link Here
10
 *******************************************************************************/
10
 *******************************************************************************/
11
package org.eclipse.jdt.internal.core;
11
package org.eclipse.jdt.internal.core;
12
12
13
import java.net.URL;
13
import java.util.ArrayList;
14
import java.util.ArrayList;
14
import java.util.HashMap;
15
import java.util.HashMap;
15
import java.util.HashSet;
16
import java.util.HashSet;
Lines 335-341 Link Here
335
							boolean found = false;
336
							boolean found = false;
336
							for (int j = 0; j < accumulatedRoots.size(); j++) {
337
							for (int j = 0; j < accumulatedRoots.size(); j++) {
337
								IPackageFragmentRoot root = (IPackageFragmentRoot) accumulatedRoots.elementAt(j);
338
								IPackageFragmentRoot root = (IPackageFragmentRoot) accumulatedRoots.elementAt(j);
338
								if (!root.getPath().equals(oldRoot.getPath())) {
339
								if (root.getPath().equals(oldRoot.getPath())) {
339
									found = true;
340
									found = true;
340
									break;
341
									break;
341
								}
342
								}
Lines 511-517 Link Here
511
512
512
		for (int i = 0; i < newLength; i++) {
513
		for (int i = 0; i < newLength; i++) {
513
			int index = classpathContains(this.oldResolvedClasspath, newResolvedClasspath[i]);
514
			int index = classpathContains(this.oldResolvedClasspath, newResolvedClasspath[i]);
514
			if (index == -1) {
515
			if (index == -1 || newResolvedClasspath[i].getEntryKind() == IClasspathEntry.CPE_LIBRARY) {
515
				// remote projects are not indexed in this project
516
				// remote projects are not indexed in this project
516
				if (newResolvedClasspath[i].getEntryKind() == IClasspathEntry.CPE_PROJECT){
517
				if (newResolvedClasspath[i].getEntryKind() == IClasspathEntry.CPE_PROJECT){
517
					continue;
518
					continue;
Lines 519-524 Link Here
519
520
520
				// Request indexing
521
				// Request indexing
521
				int entryKind = newResolvedClasspath[i].getEntryKind();
522
				int entryKind = newResolvedClasspath[i].getEntryKind();
523
				URL newurl = ((ClasspathEntry)newResolvedClasspath[i]).getLibraryIndexLocation();
522
				switch (entryKind) {
524
				switch (entryKind) {
523
					case IClasspathEntry.CPE_LIBRARY:
525
					case IClasspathEntry.CPE_LIBRARY:
524
						boolean pathHasChanged = true;
526
						boolean pathHasChanged = true;
Lines 526-537 Link Here
526
						for (int j = 0; j < oldLength; j++) {
528
						for (int j = 0; j < oldLength; j++) {
527
							IClasspathEntry oldEntry = this.oldResolvedClasspath[j];
529
							IClasspathEntry oldEntry = this.oldResolvedClasspath[j];
528
							if (oldEntry.getPath().equals(newPath)) {
530
							if (oldEntry.getPath().equals(newPath)) {
529
								pathHasChanged = false;
531
								URL oldurl = ((ClasspathEntry)oldEntry).getLibraryIndexLocation();
532
								if (oldurl == null && newurl == null) {
533
									pathHasChanged = false;
534
								} else if (oldurl != null && newurl != null) {
535
									pathHasChanged = !(newurl.equals(oldurl));
536
								} else if (oldurl != null) {
537
									indexManager.removeIndex(newPath);
538
								}
530
								break;
539
								break;
531
							}
540
							}
532
						}
541
						}
533
						if (pathHasChanged) {
542
						if (pathHasChanged) {
534
							indexManager.indexLibrary(newPath, this.project.getProject());
543
							indexManager.indexLibrary(newPath, this.project.getProject(), newurl);
535
						}
544
						}
536
						break;
545
						break;
537
					case IClasspathEntry.CPE_SOURCE:
546
					case IClasspathEntry.CPE_SOURCE:
(-)a/org.eclipse.jdt.core/model/org/eclipse/jdt/internal/core/ClasspathEntry.java (-10 / +88 lines)
Lines 1-5 Link Here
1
/*******************************************************************************
1
/*******************************************************************************
2
 * Copyright (c) 2000, 2011 IBM Corporation and others.
2
 * Copyright (c) 2000, 2012 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
 *     Terry Parker <tparker@google.com> - DeltaProcessor misses state changes in archive files, see https://bugs.eclipse.org/bugs/show_bug.cgi?id=357425
10
 *******************************************************************************/
11
 *******************************************************************************/
11
package org.eclipse.jdt.internal.core;
12
package org.eclipse.jdt.internal.core;
12
13
Lines 16-21 Link Here
16
import java.io.InputStream;
17
import java.io.InputStream;
17
import java.io.OutputStreamWriter;
18
import java.io.OutputStreamWriter;
18
import java.io.UnsupportedEncodingException;
19
import java.io.UnsupportedEncodingException;
20
import java.net.MalformedURLException;
21
import java.net.URL;
19
import java.util.ArrayList;
22
import java.util.ArrayList;
20
import java.util.HashMap;
23
import java.util.HashMap;
21
import java.util.HashSet;
24
import java.util.HashSet;
Lines 1268-1273 Link Here
1268
		return false;
1271
		return false;
1269
	}
1272
	}
1270
1273
1274
	public String getSourceAttachmentEncoding() {
1275
		for (int i = 0, length = this.extraAttributes.length; i < length; i++) {
1276
			IClasspathAttribute attribute = this.extraAttributes[i];
1277
			if (IClasspathAttribute.SOURCE_ATTACHMENT_ENCODING.equals(attribute.getName()))
1278
				return attribute.getValue();
1279
		}
1280
		return null;
1281
	}
1282
	
1271
	/**
1283
	/**
1272
	 * Returns the kind of a <code>PackageFragmentRoot</code> from its <code>String</code> form.
1284
	 * Returns the kind of a <code>PackageFragmentRoot</code> from its <code>String</code> form.
1273
	 */
1285
	 */
Lines 1523-1528 Link Here
1523
1535
1524
		return JavaCore.getResolvedClasspathEntry(this);
1536
		return JavaCore.getResolvedClasspathEntry(this);
1525
	}
1537
	}
1538
	
1539
	/**
1540
	 * This function computes the URL of the index location for this classpath entry. It returns null if the URL is
1541
	 * invalid.
1542
	 */
1543
	public URL getLibraryIndexLocation() {
1544
		switch(getEntryKind()) {
1545
			case IClasspathEntry.CPE_LIBRARY :
1546
			case IClasspathEntry.CPE_VARIABLE :
1547
				break;
1548
			default :
1549
				return null;
1550
		}
1551
		if (this.extraAttributes == null) return null;
1552
		for (int i= 0; i < this.extraAttributes.length; i++) {
1553
			IClasspathAttribute attrib= this.extraAttributes[i];
1554
			if (IClasspathAttribute.INDEX_LOCATION_ATTRIBUTE_NAME.equals(attrib.getName())) {
1555
				String value = attrib.getValue();
1556
				try {
1557
					return new URL(value);
1558
				} catch (MalformedURLException e) {
1559
					return null;
1560
				}
1561
			}
1562
		}
1563
		return null;
1564
	}
1565
1566
	public boolean ignoreOptionalProblems() {
1567
		if (this.entryKind == IClasspathEntry.CPE_SOURCE) {
1568
			for (int i = 0; i < this.extraAttributes.length; i++) {
1569
				IClasspathAttribute attrib = this.extraAttributes[i];
1570
				if (IClasspathAttribute.IGNORE_OPTIONAL_PROBLEMS.equals(attrib.getName())) {
1571
					return "true".equals(attrib.getValue()); //$NON-NLS-1$
1572
				}
1573
			}
1574
		}
1575
		return false;
1576
	}
1526
1577
1527
	/**
1578
	/**
1528
	 * Validate a given classpath and output location for a project, using the following rules:
1579
	 * Validate a given classpath and output location for a project, using the following rules:
Lines 1776-1781 Link Here
1776
		// perform one separate iteration so as to not take precedence over previously checked scenarii (in particular should
1827
		// perform one separate iteration so as to not take precedence over previously checked scenarii (in particular should
1777
		// diagnose nesting source folder issue before this one, for example, [src]"Project/", [src]"Project/source/" and output="Project/" should
1828
		// diagnose nesting source folder issue before this one, for example, [src]"Project/", [src]"Project/source/" and output="Project/" should
1778
		// first complain about missing exclusion pattern
1829
		// first complain about missing exclusion pattern
1830
		IJavaModelStatus cachedStatus = null;
1779
		for (int i = 0 ; i < length; i++) {
1831
		for (int i = 0 ; i < length; i++) {
1780
			IClasspathEntry entry = classpath[i];
1832
			IClasspathEntry entry = classpath[i];
1781
			if (entry == null) continue;
1833
			if (entry == null) continue;
Lines 1788-1817 Link Here
1788
1840
1789
			if (kind == IClasspathEntry.CPE_SOURCE) {
1841
			if (kind == IClasspathEntry.CPE_SOURCE) {
1790
				IPath output = entry.getOutputLocation();
1842
				IPath output = entry.getOutputLocation();
1791
				if (output == null) continue; // 36465 - for 2.0 backward compatibility, only check specific output locations (the default can still coincidate)
1843
				if (output == null) output = projectOutputLocation; // if no specific output, still need to check using default output (this line would check default output)
1792
				// if (output == null) output = projectOutputLocation; // if no specific output, still need to check using default output (this line would check default output)
1793
				for (int j = 0; j < length; j++) {
1844
				for (int j = 0; j < length; j++) {
1794
					IClasspathEntry otherEntry = classpath[j];
1845
					IClasspathEntry otherEntry = classpath[j];
1795
					if (otherEntry == entry) continue;
1846
					if (otherEntry == entry) continue;
1796
1847
1797
					// Build some common strings for status message
1798
					boolean opStartsWithProject = projectName.equals(otherEntry.getPath().segment(0));
1799
					String otherPathMsg = opStartsWithProject ? otherEntry.getPath().removeFirstSegments(1).toString() : otherEntry.getPath().makeRelative().toString();
1800
1801
					switch (otherEntry.getEntryKind()) {
1848
					switch (otherEntry.getEntryKind()) {
1802
						case IClasspathEntry.CPE_SOURCE :
1849
						case IClasspathEntry.CPE_SOURCE :
1803
							if (otherEntry.getPath().equals(output)) {
1850
							// Bug 287164 : Report errors of overlapping output locations only if the user sets the corresponding preference.
1804
								return new JavaModelStatus(IJavaModelStatusConstants.INVALID_CLASSPATH, Messages.bind(Messages.classpath_cannotUseDistinctSourceFolderAsOutput, new String[] {entryPathMsg, otherPathMsg, projectName}));
1851
							// The check is required for backward compatibility with bug-fix 36465.
1852
							String option = javaProject.getOption(JavaCore.CORE_OUTPUT_LOCATION_OVERLAPPING_ANOTHER_SOURCE, true);
1853
							if (otherEntry.getPath().equals(output) 
1854
									&& !JavaCore.IGNORE.equals(option)) {
1855
								boolean opStartsWithProject = projectName.equals(otherEntry.getPath().segment(0));
1856
								String otherPathMsg = opStartsWithProject ? otherEntry.getPath().removeFirstSegments(1).toString() : otherEntry.getPath().makeRelative().toString();
1857
								if (JavaCore.ERROR.equals(option)) {
1858
									return new JavaModelStatus(IStatus.ERROR, IJavaModelStatusConstants.OUTPUT_LOCATION_OVERLAPPING_ANOTHER_SOURCE, 
1859
											Messages.bind(Messages.classpath_cannotUseDistinctSourceFolderAsOutput, new String[] {
1860
											entryPathMsg, otherPathMsg, projectName }));
1861
								}
1862
								if (cachedStatus == null) {
1863
									// Note that the isOK() is being overridden to return true. This is an exceptional scenario
1864
									cachedStatus = new JavaModelStatus(IStatus.OK, IJavaModelStatusConstants.OUTPUT_LOCATION_OVERLAPPING_ANOTHER_SOURCE, 
1865
										Messages.bind(Messages.classpath_cannotUseDistinctSourceFolderAsOutput, new String[] {
1866
										entryPathMsg, otherPathMsg, projectName })){
1867
										public boolean isOK() {
1868
											return true;
1869
										}
1870
									};
1871
								}
1805
							}
1872
							}
1806
							break;
1873
							break;
1807
						case IClasspathEntry.CPE_LIBRARY :
1874
						case IClasspathEntry.CPE_LIBRARY :
1808
							if (otherEntry.getPath().equals(output)) {
1875
							if (output != projectOutputLocation && otherEntry.getPath().equals(output)) {
1876
								boolean opStartsWithProject = projectName.equals(otherEntry.getPath().segment(0));
1877
								String otherPathMsg = opStartsWithProject ? otherEntry.getPath().removeFirstSegments(1).toString() : otherEntry.getPath().makeRelative().toString();
1809
								return new JavaModelStatus(IJavaModelStatusConstants.INVALID_CLASSPATH, Messages.bind(Messages.classpath_cannotUseLibraryAsOutput, new String[] {entryPathMsg, otherPathMsg, projectName}));
1878
								return new JavaModelStatus(IJavaModelStatusConstants.INVALID_CLASSPATH, Messages.bind(Messages.classpath_cannotUseLibraryAsOutput, new String[] {entryPathMsg, otherPathMsg, projectName}));
1810
							}
1879
							}
1811
					}
1880
					}
1812
				}
1881
				}
1813
			}
1882
			}
1814
		}
1883
		}
1884
1885
		// NOTE: The above code that checks for IJavaModelStatusConstants.OUTPUT_LOCATION_OVERLAPPING_ANOTHER_SOURCE, can be configured to return
1886
		// a WARNING status and hence should be at the end of this validation method. Any other code that might return a more severe ERROR should be 
1887
		// inserted before the mentioned code.
1888
		if (cachedStatus != null) return cachedStatus;
1889
1815
		return JavaModelStatus.VERIFIED_OK;
1890
		return JavaModelStatus.VERIFIED_OK;
1816
	}
1891
	}
1817
1892
Lines 1827-1832 Link Here
1827
	 * @return a java model status describing the problem related to this classpath entry if any, a status object with code <code>IStatus.OK</code> if the entry is fine
1902
	 * @return a java model status describing the problem related to this classpath entry if any, a status object with code <code>IStatus.OK</code> if the entry is fine
1828
	 */
1903
	 */
1829
	public static IJavaModelStatus validateClasspathEntry(IJavaProject project, IClasspathEntry entry, boolean checkSourceAttachment, boolean referredByContainer){
1904
	public static IJavaModelStatus validateClasspathEntry(IJavaProject project, IClasspathEntry entry, boolean checkSourceAttachment, boolean referredByContainer){
1905
		if (entry.getEntryKind() == IClasspathEntry.CPE_LIBRARY) {
1906
			JavaModelManager.getJavaModelManager().removeFromInvalidArchiveCache(entry.getPath());
1907
		}
1830
		IJavaModelStatus status = validateClasspathEntry(project, entry, null, checkSourceAttachment, referredByContainer);
1908
		IJavaModelStatus status = validateClasspathEntry(project, entry, null, checkSourceAttachment, referredByContainer);
1831
		// https://bugs.eclipse.org/bugs/show_bug.cgi?id=171136 and https://bugs.eclipse.org/bugs/show_bug.cgi?id=300136
1909
		// https://bugs.eclipse.org/bugs/show_bug.cgi?id=171136 and https://bugs.eclipse.org/bugs/show_bug.cgi?id=300136
1832
		// Ignore class path errors from optional entries.
1910
		// Ignore class path errors from optional entries.
(-)a/org.eclipse.jdt.core/model/org/eclipse/jdt/internal/core/ClasspathValidation.java (-5 / +9 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 12-17 Link Here
12
12
13
import org.eclipse.core.resources.IProject;
13
import org.eclipse.core.resources.IProject;
14
import org.eclipse.core.runtime.IPath;
14
import org.eclipse.core.runtime.IPath;
15
import org.eclipse.core.runtime.IStatus;
15
import org.eclipse.jdt.core.IClasspathEntry;
16
import org.eclipse.jdt.core.IClasspathEntry;
16
import org.eclipse.jdt.core.IJavaModelStatus;
17
import org.eclipse.jdt.core.IJavaModelStatus;
17
import org.eclipse.jdt.core.JavaModelException;
18
import org.eclipse.jdt.core.JavaModelException;
Lines 37-43 Link Here
37
			// project doesn't exist
38
			// project doesn't exist
38
			IProject resource = this.project.getProject();
39
			IProject resource = this.project.getProject();
39
			if (resource.isAccessible()) {
40
			if (resource.isAccessible()) {
40
				this.project.flushClasspathProblemMarkers(true/*flush cycle markers*/, true/*flush classpath format markers*/);
41
				this.project.flushClasspathProblemMarkers(true/*flush cycle markers*/, true/*flush classpath format markers*/, true /*flush overlapping output markers*/);
41
42
42
				// remove problems and tasks created  by the builder
43
				// remove problems and tasks created  by the builder
43
				JavaBuilder.removeProblemsAndTasksFor(resource);
44
				JavaBuilder.removeProblemsAndTasksFor(resource);
Lines 56-67 Link Here
56
		}
57
		}
57
58
58
		// update classpath format problems
59
		// update classpath format problems
59
		this.project.flushClasspathProblemMarkers(false/*cycle*/, true/*format*/);
60
		this.project.flushClasspathProblemMarkers(false/*cycle*/, true/*format*/, false/*overlapping*/);
60
		if (!status.isOK())
61
		if (!status.isOK())
61
			this.project.createClasspathProblemMarker(status);
62
			this.project.createClasspathProblemMarker(status);
62
63
64
		// update overlapping output problem markers 
65
		this.project.flushClasspathProblemMarkers(false/*cycle*/, false/*format*/, true/*overlapping*/);
66
		
63
		// update resolved classpath problems
67
		// update resolved classpath problems
64
		this.project.flushClasspathProblemMarkers(false/*cycle*/, false/*format*/);
68
		this.project.flushClasspathProblemMarkers(false/*cycle*/, false/*format*/, false/*overlapping*/);
65
69
66
		if (rawClasspath != JavaProject.INVALID_CLASSPATH && outputLocation != null) {
70
		if (rawClasspath != JavaProject.INVALID_CLASSPATH && outputLocation != null) {
67
		 	for (int i = 0; i < rawClasspath.length; i++) {
71
		 	for (int i = 0; i < rawClasspath.length; i++) {
Lines 71-77 Link Here
71
				}
75
				}
72
			 }
76
			 }
73
			status = ClasspathEntry.validateClasspath(this.project, rawClasspath, outputLocation);
77
			status = ClasspathEntry.validateClasspath(this.project, rawClasspath, outputLocation);
74
			if (!status.isOK())
78
			if (status.getCode() != IStatus.OK)
75
				this.project.createClasspathProblemMarker(status);
79
				this.project.createClasspathProblemMarker(status);
76
		 }
80
		 }
77
	}
81
	}
(-)a/org.eclipse.jdt.core/model/org/eclipse/jdt/internal/core/CompilationUnit.java (-1 / +4 lines)
Lines 1-5 Link Here
1
/*******************************************************************************
1
/*******************************************************************************
2
 * Copyright (c) 2000, 2010 IBM Corporation and others.
2
 * Copyright (c) 2000, 2012 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 1005-1010 Link Here
1005
	if (resource == null) return false;
1005
	if (resource == null) return false;
1006
	return ((CompilationUnitElementInfo)info).timestamp != resource.getModificationStamp();
1006
	return ((CompilationUnitElementInfo)info).timestamp != resource.getModificationStamp();
1007
}
1007
}
1008
public boolean ignoreOptionalProblems() {
1009
	return getPackageFragmentRoot().ignoreOptionalProblems();
1010
}
1008
/**
1011
/**
1009
 * @see IWorkingCopy#isBasedOn(IResource)
1012
 * @see IWorkingCopy#isBasedOn(IResource)
1010
 * @deprecated
1013
 * @deprecated
(-)a/org.eclipse.jdt.core/model/org/eclipse/jdt/internal/core/CompilationUnitProblemFinder.java (-3 / +4 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 91-98 Link Here
91
	 */
91
	 */
92
	public void accept(ISourceType[] sourceTypes, PackageBinding packageBinding, AccessRestriction accessRestriction) {
92
	public void accept(ISourceType[] sourceTypes, PackageBinding packageBinding, AccessRestriction accessRestriction) {
93
		// ensure to jump back to toplevel type for first one (could be a member)
93
		// ensure to jump back to toplevel type for first one (could be a member)
94
//		while (sourceTypes[0].getEnclosingType() != null)
94
		while (sourceTypes[0].getEnclosingType() != null) {
95
//			sourceTypes[0] = sourceTypes[0].getEnclosingType();
95
			sourceTypes[0] = sourceTypes[0].getEnclosingType();
96
		}
96
97
97
		CompilationResult result =
98
		CompilationResult result =
98
			new CompilationResult(sourceTypes[0].getFileName(), 1, 1, this.options.maxProblemsPerUnit);
99
			new CompilationResult(sourceTypes[0].getFileName(), 1, 1, this.options.maxProblemsPerUnit);
(-)a/org.eclipse.jdt.core/model/org/eclipse/jdt/internal/core/CompilationUnitStructureRequestor.java (+21 lines)
Lines 81-86 Link Here
81
	 */
81
	 */
82
	private HashtableOfObjectToInt occurenceCounts;
82
	private HashtableOfObjectToInt occurenceCounts;
83
83
84
	/*
85
	 * A table to store the occurrence count of anonymous types. The key will be the handle to the
86
	 * enclosing type of the anonymous.
87
	 */
88
	private HashtableOfObjectToInt localOccurrenceCounts;
89
84
	/**
90
	/**
85
	 * Stack of parent scope info objects. The info on the
91
	 * Stack of parent scope info objects. The info on the
86
	 * top of the stack is the parent of the next element found.
92
	 * top of the stack is the parent of the next element found.
Lines 128-133 Link Here
128
	this.unitInfo = unitInfo;
134
	this.unitInfo = unitInfo;
129
	this.newElements = newElements;
135
	this.newElements = newElements;
130
	this.occurenceCounts = new HashtableOfObjectToInt();
136
	this.occurenceCounts = new HashtableOfObjectToInt();
137
	this.localOccurrenceCounts = new HashtableOfObjectToInt(5);
131
}
138
}
132
/**
139
/**
133
 * @see ISourceElementRequestor
140
 * @see ISourceElementRequestor
Lines 707-712 Link Here
707
		this.occurenceCounts.put(handle, ++occurenceCount);
714
		this.occurenceCounts.put(handle, ++occurenceCount);
708
		handle.occurrenceCount = occurenceCount;
715
		handle.occurrenceCount = occurenceCount;
709
	}
716
	}
717
718
	// https://bugs.eclipse.org/bugs/show_bug.cgi?id=342393
719
	// For anonymous source types, the occurrence count should be in the context
720
	// of the enclosing type.
721
	if (handle instanceof SourceType && handle.getElementName().length() == 0) {
722
		Object key = handle.getParent().getAncestor(IJavaElement.TYPE);
723
		occurenceCount = this.localOccurrenceCounts.get(key);
724
		if (occurenceCount == -1)
725
			this.localOccurrenceCounts.put(key, 1);
726
		else {
727
			this.localOccurrenceCounts.put(key, ++occurenceCount);
728
			((SourceType)handle).localOccurrenceCount = occurenceCount;
729
		}
730
	}
710
}
731
}
711
protected IMemberValuePair getMemberValuePair(MemberValuePair memberValuePair) {
732
protected IMemberValuePair getMemberValuePair(MemberValuePair memberValuePair) {
712
	String memberName = new String(memberValuePair.name);
733
	String memberName = new String(memberValuePair.name);
(-)a/org.eclipse.jdt.core/model/org/eclipse/jdt/internal/core/CopyResourceElementsOperation.java (-6 / +17 lines)
Lines 266-285 Link Here
266
	 * <li>On a copy, the delta should be rooted in the dest project
266
	 * <li>On a copy, the delta should be rooted in the dest project
267
	 * <li>On a move, two deltas are generated<ul>
267
	 * <li>On a move, two deltas are generated<ul>
268
	 * 			<li>one rooted in the source project
268
	 * 			<li>one rooted in the source project
269
	 *			<li>one rooted in the destination project</ul></ul>
269
	 *			<li>one rooted in the destination project
270
	 * <li> When a CU is being overwritten, the delta on the destination will be of type F_CONTENT </ul></ul>
270
	 * If the operation is rooted in a single project, the delta is rooted in that project
271
	 * If the operation is rooted in a single project, the delta is rooted in that project
271
	 *
272
	 *
272
	 */
273
	 */
273
	protected void prepareDeltas(IJavaElement sourceElement, IJavaElement destinationElement, boolean isMove) {
274
	protected void prepareDeltas(IJavaElement sourceElement, IJavaElement destinationElement, boolean isMove, boolean overWriteCU) {
274
		if (Util.isExcluded(sourceElement) || Util.isExcluded(destinationElement)) return;
275
		if (Util.isExcluded(sourceElement) || Util.isExcluded(destinationElement)) return;
276
		
275
		IJavaProject destProject = destinationElement.getJavaProject();
277
		IJavaProject destProject = destinationElement.getJavaProject();
276
		if (isMove) {
278
		if (isMove) {
277
			IJavaProject sourceProject = sourceElement.getJavaProject();
279
			IJavaProject sourceProject = sourceElement.getJavaProject();
278
			getDeltaFor(sourceProject).movedFrom(sourceElement, destinationElement);
280
			getDeltaFor(sourceProject).movedFrom(sourceElement, destinationElement);
279
			getDeltaFor(destProject).movedTo(destinationElement, sourceElement);
281
			if (!overWriteCU) {
282
				getDeltaFor(destProject).movedTo(destinationElement, sourceElement);
283
				return;
284
			}
280
		} else {
285
		} else {
281
			getDeltaFor(destProject).added(destinationElement);
286
			if (!overWriteCU) {
287
				getDeltaFor(destProject).added(destinationElement);
288
				return;
289
			}
282
		}
290
		}
291
		getDeltaFor(destinationElement.getJavaProject()).changed(destinationElement, IJavaElementDelta.F_CONTENT);
283
	}
292
	}
284
	/**
293
	/**
285
	 * Copies/moves a compilation unit with the name <code>newCUName</code>
294
	 * Copies/moves a compilation unit with the name <code>newCUName</code>
Lines 357-368 Link Here
357
			}
366
			}
358
367
359
			// register the correct change deltas
368
			// register the correct change deltas
360
			prepareDeltas(source, destCU, isMove());
369
			boolean contentChanged = this.force && destFile.exists();
370
			prepareDeltas(source, destCU, isMove(), contentChanged);
371
			
361
			if (newCUName != null) {
372
			if (newCUName != null) {
362
				//the main type has been renamed
373
				//the main type has been renamed
363
				String oldName = Util.getNameWithoutJavaLikeExtension(source.getElementName());
374
				String oldName = Util.getNameWithoutJavaLikeExtension(source.getElementName());
364
				String newName = Util.getNameWithoutJavaLikeExtension(newCUName);
375
				String newName = Util.getNameWithoutJavaLikeExtension(newCUName);
365
				prepareDeltas(source.getType(oldName), destCU.getType(newName), isMove());
376
				prepareDeltas(source.getType(oldName), destCU.getType(newName), isMove(), false);
366
			}
377
			}
367
		} else {
378
		} else {
368
			if (!this.force) {
379
			if (!this.force) {
(-)a/org.eclipse.jdt.core/model/org/eclipse/jdt/internal/core/DeltaProcessor.java (-7 / +19 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
 *     Terry Parker <tparker@google.com> - DeltaProcessor exhibits O(N^2) behavior, see https://bugs.eclipse.org/bugs/show_bug.cgi?id=354332
11
 *     Terry Parker <tparker@google.com> - DeltaProcessor misses state changes in archive files, see https://bugs.eclipse.org/bugs/show_bug.cgi?id=357425
10
 *******************************************************************************/
12
 *******************************************************************************/
11
package org.eclipse.jdt.internal.core;
13
package org.eclipse.jdt.internal.core;
12
14
13
import java.io.File;
15
import java.io.File;
16
import java.net.URL;
14
import java.util.*;
17
import java.util.*;
15
18
16
import org.eclipse.core.resources.IContainer;
19
import org.eclipse.core.resources.IContainer;
Lines 953-958 Link Here
953
				// project does not exist -> ignore
956
				// project does not exist -> ignore
954
				continue;
957
				continue;
955
			}
958
			}
959
			boolean deltaContainsModifiedJar = false;
956
			for (int j = 0; j < entries.length; j++){
960
			for (int j = 0; j < entries.length; j++){
957
				if (entries[j].getEntryKind() == IClasspathEntry.CPE_LIBRARY) {
961
				if (entries[j].getEntryKind() == IClasspathEntry.CPE_LIBRARY) {
958
					IPath entryPath = entries[j].getPath();
962
					IPath entryPath = entries[j].getPath();
Lines 994-1001 Link Here
994
									// first remove the index so that it is forced to be re-indexed
998
									// first remove the index so that it is forced to be re-indexed
995
									this.manager.indexManager.removeIndex(entryPath);
999
									this.manager.indexManager.removeIndex(entryPath);
996
									// then index the jar
1000
									// then index the jar
997
									this.manager.indexManager.indexLibrary(entryPath, project.getProject());
1001
									this.manager.indexManager.indexLibrary(entryPath, project.getProject(), ((ClasspathEntry)entries[j]).getLibraryIndexLocation());
998
								} else {
1002
								} else {
1003
									URL indexLocation = ((ClasspathEntry)entries[j]).getLibraryIndexLocation();
1004
									if (indexLocation != null) { // force reindexing, this could be faster rather than maintaining the list
1005
										this.manager.indexManager.indexLibrary(entryPath, project.getProject(), indexLocation);
1006
									}
999
									externalArchivesStatus.put(entryPath, EXTERNAL_JAR_UNCHANGED);
1007
									externalArchivesStatus.put(entryPath, EXTERNAL_JAR_UNCHANGED);
1000
								}
1008
								}
1001
							} else {
1009
							} else {
Lines 1006-1012 Link Here
1006
									this.state.getExternalLibTimeStamps().put(entryPath, new Long(newTimeStamp));
1014
									this.state.getExternalLibTimeStamps().put(entryPath, new Long(newTimeStamp));
1007
									// index the new jar
1015
									// index the new jar
1008
									this.manager.indexManager.removeIndex(entryPath);
1016
									this.manager.indexManager.removeIndex(entryPath);
1009
									this.manager.indexManager.indexLibrary(entryPath, project.getProject());
1017
									this.manager.indexManager.indexLibrary(entryPath, project.getProject(), ((ClasspathEntry)entries[j]).getLibraryIndexLocation());
1010
								}
1018
								}
1011
							}
1019
							}
1012
						} else { // internal JAR
1020
						} else { // internal JAR
Lines 1022-1028 Link Here
1022
								System.out.println("- External JAR ADDED, affecting root: "+root.getElementName()); //$NON-NLS-1$
1030
								System.out.println("- External JAR ADDED, affecting root: "+root.getElementName()); //$NON-NLS-1$
1023
							}
1031
							}
1024
							elementAdded(root, null, null);
1032
							elementAdded(root, null, null);
1025
							javaProject.resetResolvedClasspath(); // in case it contains a chained jar
1033
							deltaContainsModifiedJar = true;
1026
							this.state.addClasspathValidation(javaProject); // see https://bugs.eclipse.org/bugs/show_bug.cgi?id=185733
1034
							this.state.addClasspathValidation(javaProject); // see https://bugs.eclipse.org/bugs/show_bug.cgi?id=185733
1027
							hasDelta = true;
1035
							hasDelta = true;
1028
						} else if (status == EXTERNAL_JAR_CHANGED) {
1036
						} else if (status == EXTERNAL_JAR_CHANGED) {
Lines 1031-1037 Link Here
1031
								System.out.println("- External JAR CHANGED, affecting root: "+root.getElementName()); //$NON-NLS-1$
1039
								System.out.println("- External JAR CHANGED, affecting root: "+root.getElementName()); //$NON-NLS-1$
1032
							}
1040
							}
1033
							contentChanged(root);
1041
							contentChanged(root);
1034
							javaProject.resetResolvedClasspath(); // in case it contains a chained jar
1042
							deltaContainsModifiedJar = true;
1035
							hasDelta = true;
1043
							hasDelta = true;
1036
						} else if (status == EXTERNAL_JAR_REMOVED) {
1044
						} else if (status == EXTERNAL_JAR_REMOVED) {
1037
							PackageFragmentRoot root = (PackageFragmentRoot) javaProject.getPackageFragmentRoot(entryPath.toString());
1045
							PackageFragmentRoot root = (PackageFragmentRoot) javaProject.getPackageFragmentRoot(entryPath.toString());
Lines 1039-1050 Link Here
1039
								System.out.println("- External JAR REMOVED, affecting root: "+root.getElementName()); //$NON-NLS-1$
1047
								System.out.println("- External JAR REMOVED, affecting root: "+root.getElementName()); //$NON-NLS-1$
1040
							}
1048
							}
1041
							elementRemoved(root, null, null);
1049
							elementRemoved(root, null, null);
1042
							javaProject.resetResolvedClasspath(); // in case it contains a chained jar
1050
							deltaContainsModifiedJar = true;
1043
							this.state.addClasspathValidation(javaProject); // see https://bugs.eclipse.org/bugs/show_bug.cgi?id=185733
1051
							this.state.addClasspathValidation(javaProject); // see https://bugs.eclipse.org/bugs/show_bug.cgi?id=185733
1044
							hasDelta = true;
1052
							hasDelta = true;
1045
						}
1053
						}
1046
					}
1054
					}
1047
				}
1055
				}
1056
			}
1057
			
1058
			if (deltaContainsModifiedJar) {
1059
				javaProject.resetResolvedClasspath();
1048
			}
1060
			}
1049
		}
1061
		}
1050
		// ensure the external file cache is reset so that if a .jar file is deleted but no longer on the classpath, it won't appear as changed next time it is added
1062
		// ensure the external file cache is reset so that if a .jar file is deleted but no longer on the classpath, it won't appear as changed next time it is added
Lines 2622-2634 Link Here
2622
					switch (delta.getKind()) {
2634
					switch (delta.getKind()) {
2623
						case IResourceDelta.ADDED:
2635
						case IResourceDelta.ADDED:
2624
							// index the new jar
2636
							// index the new jar
2625
							indexManager.indexLibrary(jarPath, root.getJavaProject().getProject());
2637
							indexManager.indexLibrary(jarPath, root.getJavaProject().getProject(), root.getIndexPath());
2626
							break;
2638
							break;
2627
						case IResourceDelta.CHANGED:
2639
						case IResourceDelta.CHANGED:
2628
							// first remove the index so that it is forced to be re-indexed
2640
							// first remove the index so that it is forced to be re-indexed
2629
							indexManager.removeIndex(jarPath);
2641
							indexManager.removeIndex(jarPath);
2630
							// then index the jar
2642
							// then index the jar
2631
							indexManager.indexLibrary(jarPath, root.getJavaProject().getProject());
2643
							indexManager.indexLibrary(jarPath, root.getJavaProject().getProject(), root.getIndexPath());
2632
							break;
2644
							break;
2633
						case IResourceDelta.REMOVED:
2645
						case IResourceDelta.REMOVED:
2634
							// the jar was physically removed: remove the index
2646
							// the jar was physically removed: remove the index
(-)a/org.eclipse.jdt.core/model/org/eclipse/jdt/internal/core/ExternalFoldersManager.java (-8 / +14 lines)
Lines 1-5 Link Here
1
/*******************************************************************************
1
/*******************************************************************************
2
 * Copyright (c) 2000, 2011 IBM Corporation and others.
2
 * Copyright (c) 2000, 2012 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 122-128 Link Here
122
		} while (result.exists());
122
		} while (result.exists());
123
		if (scheduleForCreation) {
123
		if (scheduleForCreation) {
124
			if (this.pendingFolders == null)
124
			if (this.pendingFolders == null)
125
				this.pendingFolders = new HashSet();
125
				this.pendingFolders = Collections.synchronizedSet(new HashSet());
126
			this.pendingFolders.add(externalFolderPath);
126
			this.pendingFolders.add(externalFolderPath);
127
		}
127
		}
128
		knownFolders.put(externalFolderPath, result);
128
		knownFolders.put(externalFolderPath, result);
Lines 166-181 Link Here
166
		catch(CoreException e) {
166
		catch(CoreException e) {
167
			throw new JavaModelException(e);
167
			throw new JavaModelException(e);
168
		}
168
		}
169
		Iterator iterator = this.pendingFolders.iterator();
169
		// https://bugs.eclipse.org/bugs/show_bug.cgi?id=368152
170
		while (iterator.hasNext()) {
170
		// To avoid race condition (from addFolder and removeFolder, load the map elements into an array and clear the map immediately.
171
			Object folderPath = iterator.next();
171
		// The createLinkFolder being in the synchronized block can cause a deadlock and hence keep it out of the synchronized block. 
172
		Object[] arrayOfFolders = null;
173
		synchronized (this.pendingFolders) {
174
			arrayOfFolders = this.pendingFolders.toArray();
175
			this.pendingFolders.clear();
176
		}
177
178
		for (int i=0; i < arrayOfFolders.length; i++) {
172
			try {
179
			try {
173
				createLinkFolder((IPath) folderPath, false, externalFoldersProject, monitor);
180
				createLinkFolder((IPath) arrayOfFolders[i], false, externalFoldersProject, monitor);
174
			} catch (CoreException e) {
181
			} catch (CoreException e) {
175
				Util.log(e, "Error while creating a link for external folder :" + folderPath); //$NON-NLS-1$
182
				Util.log(e, "Error while creating a link for external folder :" + arrayOfFolders[i]); //$NON-NLS-1$
176
			}
183
			}
177
		}
184
		}
178
		this.pendingFolders.clear();
179
	}
185
	}
180
	
186
	
181
	public void cleanUp(IProgressMonitor monitor) throws CoreException {
187
	public void cleanUp(IProgressMonitor monitor) throws CoreException {
(-)a/org.eclipse.jdt.core/model/org/eclipse/jdt/internal/core/JarPackageFragmentRoot.java (+12 lines)
Lines 10-15 Link Here
10
 *******************************************************************************/
10
 *******************************************************************************/
11
package org.eclipse.jdt.internal.core;
11
package org.eclipse.jdt.internal.core;
12
12
13
import java.net.URL;
13
import java.util.*;
14
import java.util.*;
14
import java.util.zip.ZipEntry;
15
import java.util.zip.ZipEntry;
15
import java.util.zip.ZipException;
16
import java.util.zip.ZipException;
Lines 292-295 Link Here
292
			return;
293
			return;
293
		super.toStringAncestors(buffer);
294
		super.toStringAncestors(buffer);
294
	}
295
	}
296
297
	public URL getIndexPath() {
298
		try {
299
			IClasspathEntry entry = ((JavaProject) getParent()).getClasspathEntryFor(getPath());
300
			if (entry != null) return ((ClasspathEntry)entry).getLibraryIndexLocation();	
301
		} catch (JavaModelException e) {
302
			// ignore exception
303
		}
304
		return null;
305
	}
306
295
}
307
}
(-)a/org.eclipse.jdt.core/model/org/eclipse/jdt/internal/core/JavaCorePreferenceInitializer.java (+1 lines)
Lines 58-63 Link Here
58
		defaultOptionsMap.put(JavaCore.CORE_INCOMPATIBLE_JDK_LEVEL, JavaCore.IGNORE);
58
		defaultOptionsMap.put(JavaCore.CORE_INCOMPATIBLE_JDK_LEVEL, JavaCore.IGNORE);
59
		defaultOptionsMap.put(JavaCore.CORE_ENABLE_CLASSPATH_EXCLUSION_PATTERNS, JavaCore.ENABLED);
59
		defaultOptionsMap.put(JavaCore.CORE_ENABLE_CLASSPATH_EXCLUSION_PATTERNS, JavaCore.ENABLED);
60
		defaultOptionsMap.put(JavaCore.CORE_ENABLE_CLASSPATH_MULTIPLE_OUTPUT_LOCATIONS, JavaCore.ENABLED);
60
		defaultOptionsMap.put(JavaCore.CORE_ENABLE_CLASSPATH_MULTIPLE_OUTPUT_LOCATIONS, JavaCore.ENABLED);
61
		defaultOptionsMap.put(JavaCore.CORE_OUTPUT_LOCATION_OVERLAPPING_ANOTHER_SOURCE, JavaCore.ERROR);
61
62
62
		// encoding setting comes from resource plug-in
63
		// encoding setting comes from resource plug-in
63
		optionNames.add(JavaCore.CORE_ENCODING);
64
		optionNames.add(JavaCore.CORE_ENCODING);
(-)a/org.eclipse.jdt.core/model/org/eclipse/jdt/internal/core/JavaModelCache.java (-5 / +15 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
 *     Terry Parker <tparker@google.com> (Google Inc.)  https://bugs.eclipse.org/365499
10
 *******************************************************************************/
11
 *******************************************************************************/
11
package org.eclipse.jdt.internal.core;
12
package org.eclipse.jdt.internal.core;
12
import java.util.HashMap;
13
import java.util.HashMap;
Lines 28-33 Link Here
28
	public static final int DEFAULT_OPENABLE_SIZE = 250; // average 6629 bytes per openable (includes children) -> maximum size : 662900*BASE_VALUE bytes
29
	public static final int DEFAULT_OPENABLE_SIZE = 250; // average 6629 bytes per openable (includes children) -> maximum size : 662900*BASE_VALUE bytes
29
	public static final int DEFAULT_CHILDREN_SIZE = 250*20; // average 20 children per openable
30
	public static final int DEFAULT_CHILDREN_SIZE = 250*20; // average 20 children per openable
30
	public static final String RATIO_PROPERTY = "org.eclipse.jdt.core.javamodelcache.ratio"; //$NON-NLS-1$
31
	public static final String RATIO_PROPERTY = "org.eclipse.jdt.core.javamodelcache.ratio"; //$NON-NLS-1$
32
	public static final String JAR_TYPE_RATIO_PROPERTY = "org.eclipse.jdt.core.javamodelcache.jartyperatio"; //$NON-NLS-1$
31
	
33
	
32
	public static final Object NON_EXISTING_JAR_TYPE_INFO = new Object();
34
	public static final Object NON_EXISTING_JAR_TYPE_INFO = new Object();
33
35
Lines 72-80 Link Here
72
	protected LRUCache jarTypeCache;
74
	protected LRUCache jarTypeCache;
73
75
74
public JavaModelCache() {
76
public JavaModelCache() {
75
	// set the size of the caches in function of the maximum amount of memory available
77
	// set the size of the caches as a function of the maximum amount of memory available
76
	double ratio = getMemoryRatio();
78
	double ratio = getMemoryRatio();
77
	// adjust the size of the openable cache in function of the RATIO_PROPERTY property
79
	// adjust the size of the openable cache using the RATIO_PROPERTY property
78
	double openableRatio = getOpenableRatio();
80
	double openableRatio = getOpenableRatio();
79
	this.projectCache = new HashMap(DEFAULT_PROJECT_SIZE); // NB: Don't use a LRUCache for projects as they are constantly reopened (e.g. during delta processing)
81
	this.projectCache = new HashMap(DEFAULT_PROJECT_SIZE); // NB: Don't use a LRUCache for projects as they are constantly reopened (e.g. during delta processing)
80
	if (VERBOSE) {
82
	if (VERBOSE) {
Lines 91-103 Link Here
91
}
93
}
92
94
93
private double getOpenableRatio() {
95
private double getOpenableRatio() {
94
	String property = System.getProperty(RATIO_PROPERTY);
96
	return getRatioForProperty(RATIO_PROPERTY);
97
}
98
99
private double getJarTypeRatio() {
100
	return getRatioForProperty(JAR_TYPE_RATIO_PROPERTY);
101
}
102
103
private double getRatioForProperty(String propertyName) {
104
	String property = System.getProperty(propertyName);
95
	if (property != null) {
105
	if (property != null) {
96
		try {
106
		try {
97
			return Double.parseDouble(property);
107
			return Double.parseDouble(property);
98
		} catch (NumberFormatException e) {
108
		} catch (NumberFormatException e) {
99
			// ignore
109
			// ignore
100
			Util.log(e, "Could not parse value for " + RATIO_PROPERTY + ": " + property); //$NON-NLS-1$ //$NON-NLS-2$
110
			Util.log(e, "Could not parse value for " + propertyName + ": " + property); //$NON-NLS-1$ //$NON-NLS-2$
101
		}
111
		}
102
	}
112
	}
103
	return 1.0;
113
	return 1.0;
Lines 249-255 Link Here
249
	}
259
	}
250
}
260
}
251
protected void resetJarTypeCache() {
261
protected void resetJarTypeCache() {
252
	this.jarTypeCache = new LRUCache((int) (DEFAULT_OPENABLE_SIZE * getMemoryRatio()));
262
	this.jarTypeCache = new LRUCache((int) (DEFAULT_OPENABLE_SIZE * getMemoryRatio() * getJarTypeRatio()));
253
}
263
}
254
public String toString() {
264
public String toString() {
255
	return toStringFillingRation(""); //$NON-NLS-1$
265
	return toStringFillingRation(""); //$NON-NLS-1$
(-)a/org.eclipse.jdt.core/model/org/eclipse/jdt/internal/core/JavaModelManager.java (-77 / +51 lines)
Lines 1-5 Link Here
1
/*******************************************************************************
1
/*******************************************************************************
2
 * Copyright (c) 2000, 2011 IBM Corporation and others.
2
 * Copyright (c) 2000, 2012 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 11-16 Link Here
11
 *                                                           before its contents
11
 *                                                           before its contents
12
 *                                                           (see https://bugs.eclipse.org/bugs/show_bug.cgi?id=102422)
12
 *                                                           (see https://bugs.eclipse.org/bugs/show_bug.cgi?id=102422)
13
 *     Stephan Herrmann - Contribution for Bug 346010 - [model] strange initialization dependency in OptionTests
13
 *     Stephan Herrmann - Contribution for Bug 346010 - [model] strange initialization dependency in OptionTests
14
 *     Terry Parker <tparker@google.com> - DeltaProcessor misses state changes in archive files, see https://bugs.eclipse.org/bugs/show_bug.cgi?id=357425
14
 *******************************************************************************/
15
 *******************************************************************************/
15
package org.eclipse.jdt.internal.core;
16
package org.eclipse.jdt.internal.core;
16
17
Lines 1412-1420 Link Here
1412
	public static boolean CP_RESOLVE_VERBOSE_ADVANCED = false;
1413
	public static boolean CP_RESOLVE_VERBOSE_ADVANCED = false;
1413
	public static boolean CP_RESOLVE_VERBOSE_FAILURE = false;
1414
	public static boolean CP_RESOLVE_VERBOSE_FAILURE = false;
1414
	public static boolean ZIP_ACCESS_VERBOSE = false;
1415
	public static boolean ZIP_ACCESS_VERBOSE = false;
1415
	// temporary debug flag to track failures of bug 302850
1416
	
1416
	public static boolean DEBUG_302850 = false;
1417
1418
	/**
1417
	/**
1419
	 * A cache of opened zip files per thread.
1418
	 * A cache of opened zip files per thread.
1420
	 * (for a given thread, the object value is a HashMap from IPath to java.io.ZipFile)
1419
	 * (for a given thread, the object value is a HashMap from IPath to java.io.ZipFile)
Lines 1481-1487 Link Here
1481
					propertyName.equals(JavaCore.CORE_ENABLE_CLASSPATH_MULTIPLE_OUTPUT_LOCATIONS) ||
1480
					propertyName.equals(JavaCore.CORE_ENABLE_CLASSPATH_MULTIPLE_OUTPUT_LOCATIONS) ||
1482
					propertyName.equals(JavaCore.CORE_INCOMPLETE_CLASSPATH) ||
1481
					propertyName.equals(JavaCore.CORE_INCOMPLETE_CLASSPATH) ||
1483
					propertyName.equals(JavaCore.CORE_CIRCULAR_CLASSPATH) ||
1482
					propertyName.equals(JavaCore.CORE_CIRCULAR_CLASSPATH) ||
1484
					propertyName.equals(JavaCore.CORE_INCOMPATIBLE_JDK_LEVEL)) {
1483
					propertyName.equals(JavaCore.CORE_INCOMPATIBLE_JDK_LEVEL) ||
1484
					propertyName.equals(JavaCore.CORE_OUTPUT_LOCATION_OVERLAPPING_ANOTHER_SOURCE)) {
1485
					JavaModelManager manager = JavaModelManager.getJavaModelManager();
1485
					JavaModelManager manager = JavaModelManager.getJavaModelManager();
1486
					IJavaModel model = manager.getJavaModel();
1486
					IJavaModel model = manager.getJavaModel();
1487
					IJavaProject[] projects;
1487
					IJavaProject[] projects;
Lines 2153-2165 Link Here
2153
		// return cached options if already computed
2153
		// return cached options if already computed
2154
		Hashtable cachedOptions; // use a local variable to avoid race condition (see https://bugs.eclipse.org/bugs/show_bug.cgi?id=256329 )
2154
		Hashtable cachedOptions; // use a local variable to avoid race condition (see https://bugs.eclipse.org/bugs/show_bug.cgi?id=256329 )
2155
		if ((cachedOptions = this.optionsCache) != null) {
2155
		if ((cachedOptions = this.optionsCache) != null) {
2156
			if (DEBUG_302850) checkTaskTags("Retrieving options from optionsCache", this.optionsCache); //$NON-NLS-1$
2157
			return new Hashtable(cachedOptions);
2156
			return new Hashtable(cachedOptions);
2158
		}
2157
		}
2159
		if (DEBUG_302850) System.out.println("optionsCache was null"); //$NON-NLS-1$
2160
		if (!Platform.isRunning()) {
2158
		if (!Platform.isRunning()) {
2161
			this.optionsCache = getDefaultOptionsNoInitialization();
2159
			this.optionsCache = getDefaultOptionsNoInitialization();
2162
			if (DEBUG_302850) checkTaskTags("Platform is not running", this.optionsCache); //$NON-NLS-1$
2163
			return new Hashtable(this.optionsCache);
2160
			return new Hashtable(this.optionsCache);
2164
		}
2161
		}
2165
		// init
2162
		// init
Lines 2175-2181 Link Here
2175
				options.put(propertyName, propertyValue);
2172
				options.put(propertyName, propertyValue);
2176
			}
2173
			}
2177
		}
2174
		}
2178
		if (DEBUG_302850) checkTaskTags("Options initialized from preferences", options); //$NON-NLS-1$
2179
2175
2180
		// set deprecated options using preferences service lookup
2176
		// set deprecated options using preferences service lookup
2181
		Iterator deprecatedEntries = this.deprecatedOptions.entrySet().iterator();
2177
		Iterator deprecatedEntries = this.deprecatedOptions.entrySet().iterator();
Lines 2201-2228 Link Here
2201
		addDeprecatedOptions(options);
2197
		addDeprecatedOptions(options);
2202
2198
2203
		Util.fixTaskTags(options);
2199
		Util.fixTaskTags(options);
2204
		if (DEBUG_302850) checkTaskTags("Retrieved options from preferences", options); //$NON-NLS-1$
2205
		// store built map in cache
2200
		// store built map in cache
2206
		this.optionsCache = new Hashtable(options);
2201
		this.optionsCache = new Hashtable(options);
2207
		if (DEBUG_302850) checkTaskTags("Stored optionsCache", this.optionsCache); //$NON-NLS-1$
2208
2209
		// return built map
2202
		// return built map
2210
		return options;
2203
		return options;
2211
	}
2212
2213
	// debugging bug 302850:
2214
	private void checkTaskTags(String msg, Hashtable someOptions) {
2215
		System.out.println(msg);
2216
		Object taskTags = someOptions.get(JavaCore.COMPILER_TASK_TAGS);
2217
		System.out.println("	+ Task tags:           " + taskTags); //$NON-NLS-1$
2218
		if (taskTags == null || "".equals(taskTags)) { //$NON-NLS-1$
2219
			System.out.println("	- option names: "+this.optionNames); //$NON-NLS-1$
2220
			System.out.println("	- Call stack:"); //$NON-NLS-1$
2221
			StackTraceElement[] elements = new Exception().getStackTrace();
2222
			for (int i=0,n=elements.length; i<n; i++) {
2223
				System.out.println("		+ "+elements[i]); //$NON-NLS-1$
2224
			}
2225
		}
2226
	}
2204
	}
2227
2205
2228
	// Do not modify without modifying getDefaultOptions()
2206
	// Do not modify without modifying getDefaultOptions()
Lines 2248-2254 Link Here
2248
		defaultOptionsMap.put(JavaCore.CORE_JAVA_BUILD_ORDER, JavaCore.IGNORE);
2226
		defaultOptionsMap.put(JavaCore.CORE_JAVA_BUILD_ORDER, JavaCore.IGNORE);
2249
		defaultOptionsMap.put(JavaCore.CORE_INCOMPLETE_CLASSPATH, JavaCore.ERROR);
2227
		defaultOptionsMap.put(JavaCore.CORE_INCOMPLETE_CLASSPATH, JavaCore.ERROR);
2250
		defaultOptionsMap.put(JavaCore.CORE_CIRCULAR_CLASSPATH, JavaCore.ERROR);
2228
		defaultOptionsMap.put(JavaCore.CORE_CIRCULAR_CLASSPATH, JavaCore.ERROR);
2251
		defaultOptionsMap.put(JavaCore.CORE_INCOMPATIBLE_JDK_LEVEL, JavaCore.IGNORE);
2229
		defaultOptionsMap.put(JavaCore.CORE_INCOMPATIBLE_JDK_LEVEL, JavaCore.IGNORE); 
2230
		defaultOptionsMap.put(JavaCore.CORE_OUTPUT_LOCATION_OVERLAPPING_ANOTHER_SOURCE, JavaCore.ERROR);
2252
		defaultOptionsMap.put(JavaCore.CORE_ENABLE_CLASSPATH_EXCLUSION_PATTERNS, JavaCore.ENABLED);
2231
		defaultOptionsMap.put(JavaCore.CORE_ENABLE_CLASSPATH_EXCLUSION_PATTERNS, JavaCore.ENABLED);
2253
		defaultOptionsMap.put(JavaCore.CORE_ENABLE_CLASSPATH_MULTIPLE_OUTPUT_LOCATIONS, JavaCore.ENABLED);
2232
		defaultOptionsMap.put(JavaCore.CORE_ENABLE_CLASSPATH_MULTIPLE_OUTPUT_LOCATIONS, JavaCore.ENABLED);
2254
2233
Lines 3084-3089 Link Here
3084
	
3063
	
3085
	public boolean isInvalidArchive(IPath path) {
3064
	public boolean isInvalidArchive(IPath path) {
3086
		return this.invalidArchives != null && this.invalidArchives.contains(path);
3065
		return this.invalidArchives != null && this.invalidArchives.contains(path);
3066
	}
3067
3068
	public void removeFromInvalidArchiveCache(IPath path) {
3069
		if (this.invalidArchives != null) {
3070
			this.invalidArchives.remove(path);
3071
		}
3087
	}
3072
	}
3088
3073
3089
	public void setClasspathBeingResolved(IJavaProject project, boolean classpathIsResolved) {
3074
	public void setClasspathBeingResolved(IJavaProject project, boolean classpathIsResolved) {
Lines 4827-4883 Link Here
4827
	}
4812
	}
4828
4813
4829
	public void setOptions(Hashtable newOptions) {
4814
	public void setOptions(Hashtable newOptions) {
4830
		
4815
		Hashtable cachedValue = newOptions == null ? null : new Hashtable(newOptions);
4831
		if (DEBUG_302850) {
4816
		IEclipsePreferences defaultPreferences = getDefaultPreferences();
4832
			System.out.println("Entering in JavaModelManager.setOptions():"); //$NON-NLS-1$
4817
		IEclipsePreferences instancePreferences = getInstancePreferences();
4833
			System.out.println(new CompilerOptions(newOptions).toString());
4818
4834
			System.out.println("	- Call stack:"); //$NON-NLS-1$
4819
		if (newOptions == null){
4835
			StackTraceElement[] elements = new Exception().getStackTrace();
4820
			try {
4836
			for (int i=0,n=elements.length; i<n; i++) {
4821
				instancePreferences.clear();
4837
				System.out.println("		+ "+elements[i]); //$NON-NLS-1$
4822
			} catch(BackingStoreException e) {
4823
				// ignore
4824
			}
4825
		} else {
4826
			Enumeration keys = newOptions.keys();
4827
			while (keys.hasMoreElements()){
4828
				String key = (String)keys.nextElement();
4829
				int optionLevel = getOptionLevel(key);
4830
				if (optionLevel == UNKNOWN_OPTION) continue; // unrecognized option
4831
				if (key.equals(JavaCore.CORE_ENCODING)) {
4832
					if (cachedValue != null) {
4833
						cachedValue.put(key, JavaCore.getEncoding());
4834
					}
4835
					continue; // skipped, contributed by resource prefs
4836
				}
4837
				String value = (String) newOptions.get(key);
4838
				String defaultValue = defaultPreferences.get(key, null);
4839
				// Store value in preferences
4840
				if (defaultValue != null && defaultValue.equals(value)) {
4841
					value = null;
4842
				}
4843
				storePreference(key, value, instancePreferences, newOptions);
4844
			}
4845
			try {
4846
				// persist options
4847
				instancePreferences.flush();
4848
			} catch(BackingStoreException e) {
4849
				// ignore
4838
			}
4850
			}
4839
		}
4851
		}
4840
4852
		// update cache
4841
			Hashtable cachedValue = newOptions == null ? null : new Hashtable(newOptions);
4853
		Util.fixTaskTags(cachedValue);
4842
			IEclipsePreferences defaultPreferences = getDefaultPreferences();
4854
		this.optionsCache = cachedValue;
4843
			IEclipsePreferences instancePreferences = getInstancePreferences();
4844
4845
			if (newOptions == null){
4846
				try {
4847
					instancePreferences.clear();
4848
				} catch(BackingStoreException e) {
4849
					// ignore
4850
				}
4851
			} else {
4852
				Enumeration keys = newOptions.keys();
4853
				while (keys.hasMoreElements()){
4854
					String key = (String)keys.nextElement();
4855
					int optionLevel = getOptionLevel(key);
4856
					if (optionLevel == UNKNOWN_OPTION) continue; // unrecognized option
4857
					if (key.equals(JavaCore.CORE_ENCODING)) {
4858
						if (cachedValue != null) {
4859
							cachedValue.put(key, JavaCore.getEncoding());
4860
						}
4861
						continue; // skipped, contributed by resource prefs
4862
					}
4863
					String value = (String) newOptions.get(key);
4864
					String defaultValue = defaultPreferences.get(key, null);
4865
					// Store value in preferences
4866
					if (defaultValue != null && defaultValue.equals(value)) {
4867
						value = null;
4868
					}
4869
					storePreference(key, value, instancePreferences, newOptions);
4870
				}
4871
				try {
4872
					// persist options
4873
					instancePreferences.flush();
4874
				} catch(BackingStoreException e) {
4875
					// ignore
4876
				}
4877
			}
4878
			// update cache
4879
			Util.fixTaskTags(cachedValue);
4880
			this.optionsCache = cachedValue;
4881
	}
4855
	}
4882
4856
4883
	public void startup() throws CoreException {
4857
	public void startup() throws CoreException {
(-)a/org.eclipse.jdt.core/model/org/eclipse/jdt/internal/core/JavaProject.java (-9 / +24 lines)
Lines 1-5 Link Here
1
/*******************************************************************************
1
/*******************************************************************************
2
 * Copyright (c) 2000, 2011 IBM Corporation and others.
2
 * Copyright (c) 2000, 2012 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 433-439 Link Here
433
							new JavaModelStatus(IJavaModelStatusConstants.CLASSPATH_CYCLE, project, cycleString));
433
							new JavaModelStatus(IJavaModelStatusConstants.CLASSPATH_CYCLE, project, cycleString));
434
					}
434
					}
435
				} else {
435
				} else {
436
					project.flushClasspathProblemMarkers(true, false);
436
					project.flushClasspathProblemMarkers(true, false, false);
437
				}
437
				}
438
			}
438
			}
439
		}
439
		}
Lines 803-809 Link Here
803
		IMarker marker = null;
803
		IMarker marker = null;
804
		int severity;
804
		int severity;
805
		String[] arguments = CharOperation.NO_STRINGS;
805
		String[] arguments = CharOperation.NO_STRINGS;
806
		boolean isCycleProblem = false, isClasspathFileFormatProblem = false;
806
		boolean isCycleProblem = false, isClasspathFileFormatProblem = false, isOutputOverlapping = false;
807
		switch (status.getCode()) {
807
		switch (status.getCode()) {
808
808
809
			case  IJavaModelStatusConstants.CLASSPATH_CYCLE :
809
			case  IJavaModelStatusConstants.CLASSPATH_CYCLE :
Lines 830-836 Link Here
830
					return; // setting == IGNORE
830
					return; // setting == IGNORE
831
				}
831
				}
832
				break;
832
				break;
833
833
			case IJavaModelStatusConstants.OUTPUT_LOCATION_OVERLAPPING_ANOTHER_SOURCE :
834
				isOutputOverlapping = true;
835
				setting = getOption(JavaCore.CORE_OUTPUT_LOCATION_OVERLAPPING_ANOTHER_SOURCE, true);
836
				if (JavaCore.ERROR.equals(setting)) {
837
					severity = IMarker.SEVERITY_ERROR;
838
				} else if (JavaCore.WARNING.equals(setting)) {
839
					severity = IMarker.SEVERITY_WARNING;
840
				} else {
841
					return; // setting == IGNORE
842
				}
843
				break;
834
			default:
844
			default:
835
				IPath path = status.getPath();
845
				IPath path = status.getPath();
836
				if (path != null) arguments = new String[] { path.toString() };
846
				if (path != null) arguments = new String[] { path.toString() };
Lines 852-857 Link Here
852
					IMarker.LOCATION,
862
					IMarker.LOCATION,
853
					IJavaModelMarker.CYCLE_DETECTED,
863
					IJavaModelMarker.CYCLE_DETECTED,
854
					IJavaModelMarker.CLASSPATH_FILE_FORMAT,
864
					IJavaModelMarker.CLASSPATH_FILE_FORMAT,
865
					IJavaModelMarker.OUTPUT_OVERLAPPING_SOURCE,
855
					IJavaModelMarker.ID,
866
					IJavaModelMarker.ID,
856
					IJavaModelMarker.ARGUMENTS ,
867
					IJavaModelMarker.ARGUMENTS ,
857
					IJavaModelMarker.CATEGORY_ID,
868
					IJavaModelMarker.CATEGORY_ID,
Lines 863-868 Link Here
863
					Messages.classpath_buildPath,
874
					Messages.classpath_buildPath,
864
					isCycleProblem ? "true" : "false",//$NON-NLS-1$ //$NON-NLS-2$
875
					isCycleProblem ? "true" : "false",//$NON-NLS-1$ //$NON-NLS-2$
865
					isClasspathFileFormatProblem ? "true" : "false",//$NON-NLS-1$ //$NON-NLS-2$
876
					isClasspathFileFormatProblem ? "true" : "false",//$NON-NLS-1$ //$NON-NLS-2$
877
					isOutputOverlapping ? "true" : "false", //$NON-NLS-1$ //$NON-NLS-2$
866
					new Integer(status.getCode()),
878
					new Integer(status.getCode()),
867
					Util.getProblemArgumentsForMarker(arguments) ,
879
					Util.getProblemArgumentsForMarker(arguments) ,
868
					new Integer(CategorizedProblem.CAT_BUILDPATH),
880
					new Integer(CategorizedProblem.CAT_BUILDPATH),
Lines 1356-1373 Link Here
1356
	/**
1368
	/**
1357
	 * Remove all markers denoting classpath problems
1369
	 * Remove all markers denoting classpath problems
1358
	 */ //TODO (philippe) should improve to use a bitmask instead of booleans (CYCLE, FORMAT, VALID)
1370
	 */ //TODO (philippe) should improve to use a bitmask instead of booleans (CYCLE, FORMAT, VALID)
1359
	protected void flushClasspathProblemMarkers(boolean flushCycleMarkers, boolean flushClasspathFormatMarkers) {
1371
	protected void flushClasspathProblemMarkers(boolean flushCycleMarkers, boolean flushClasspathFormatMarkers, boolean flushOverlappingOutputMarkers) {
1360
		try {
1372
		try {
1361
			if (this.project.isAccessible()) {
1373
			if (this.project.isAccessible()) {
1362
				IMarker[] markers = this.project.findMarkers(IJavaModelMarker.BUILDPATH_PROBLEM_MARKER, false, IResource.DEPTH_ZERO);
1374
				IMarker[] markers = this.project.findMarkers(IJavaModelMarker.BUILDPATH_PROBLEM_MARKER, false, IResource.DEPTH_ZERO);
1363
				for (int i = 0, length = markers.length; i < length; i++) {
1375
				for (int i = 0, length = markers.length; i < length; i++) {
1364
					IMarker marker = markers[i];
1376
					IMarker marker = markers[i];
1365
					if (flushCycleMarkers && flushClasspathFormatMarkers) {
1377
					if (flushCycleMarkers && flushClasspathFormatMarkers && flushOverlappingOutputMarkers) {
1366
						marker.delete();
1378
						marker.delete();
1367
					} else {
1379
					} else {
1368
						String cycleAttr = (String)marker.getAttribute(IJavaModelMarker.CYCLE_DETECTED);
1380
						String cycleAttr = (String)marker.getAttribute(IJavaModelMarker.CYCLE_DETECTED);
1369
						String classpathFileFormatAttr =  (String)marker.getAttribute(IJavaModelMarker.CLASSPATH_FILE_FORMAT);
1381
						String classpathFileFormatAttr =  (String)marker.getAttribute(IJavaModelMarker.CLASSPATH_FILE_FORMAT);
1382
						String overlappingOutputAttr = (String) marker.getAttribute(IJavaModelMarker.OUTPUT_OVERLAPPING_SOURCE);
1370
						if ((flushCycleMarkers == (cycleAttr != null && cycleAttr.equals("true"))) //$NON-NLS-1$
1383
						if ((flushCycleMarkers == (cycleAttr != null && cycleAttr.equals("true"))) //$NON-NLS-1$
1384
							&& (flushOverlappingOutputMarkers == (overlappingOutputAttr != null && overlappingOutputAttr.equals("true"))) //$NON-NLS-1$
1371
							&& (flushClasspathFormatMarkers == (classpathFileFormatAttr != null && classpathFileFormatAttr.equals("true")))){ //$NON-NLS-1$
1385
							&& (flushClasspathFormatMarkers == (classpathFileFormatAttr != null && classpathFileFormatAttr.equals("true")))){ //$NON-NLS-1$
1372
							marker.delete();
1386
							marker.delete();
1373
						}
1387
						}
Lines 1513-1518 Link Here
1513
						propertyName.equals(JavaCore.CORE_ENABLE_CLASSPATH_MULTIPLE_OUTPUT_LOCATIONS) ||
1527
						propertyName.equals(JavaCore.CORE_ENABLE_CLASSPATH_MULTIPLE_OUTPUT_LOCATIONS) ||
1514
						propertyName.equals(JavaCore.CORE_INCOMPLETE_CLASSPATH) ||
1528
						propertyName.equals(JavaCore.CORE_INCOMPLETE_CLASSPATH) ||
1515
						propertyName.equals(JavaCore.CORE_CIRCULAR_CLASSPATH) ||
1529
						propertyName.equals(JavaCore.CORE_CIRCULAR_CLASSPATH) ||
1530
						propertyName.equals(JavaCore.CORE_OUTPUT_LOCATION_OVERLAPPING_ANOTHER_SOURCE) ||
1516
						propertyName.equals(JavaCore.CORE_INCOMPATIBLE_JDK_LEVEL))
1531
						propertyName.equals(JavaCore.CORE_INCOMPATIBLE_JDK_LEVEL))
1517
					{
1532
					{
1518
						manager.deltaState.addClasspathValidation(JavaProject.this);
1533
						manager.deltaState.addClasspathValidation(JavaProject.this);
Lines 3104-3111 Link Here
3104
	 * Note that it is orthogonal to IResource persistent properties, and client code has to decide
3119
	 * Note that it is orthogonal to IResource persistent properties, and client code has to decide
3105
	 * which form of storage to use appropriately. Shared properties produce real resource files which
3120
	 * which form of storage to use appropriately. Shared properties produce real resource files which
3106
	 * can be shared through a VCM onto a server. Persistent properties are not shareable.
3121
	 * can be shared through a VCM onto a server. Persistent properties are not shareable.
3107
	 *
3122
	 * <p>
3108
	 * shared properties end up in resource files, and thus cannot be modified during
3123
	 * Shared properties end up in resource files, and thus cannot be modified during
3109
	 * delta notifications (a CoreException would then be thrown).
3124
	 * delta notifications (a CoreException would then be thrown).
3110
	 *
3125
	 *
3111
	 * @param key String
3126
	 * @param key String
Lines 3129-3135 Link Here
3129
		if (rscFile.exists()) {
3144
		if (rscFile.exists()) {
3130
			if (rscFile.isReadOnly()) {
3145
			if (rscFile.isReadOnly()) {
3131
				// provide opportunity to checkout read-only .classpath file (23984)
3146
				// provide opportunity to checkout read-only .classpath file (23984)
3132
				ResourcesPlugin.getWorkspace().validateEdit(new IFile[]{rscFile}, null);
3147
				ResourcesPlugin.getWorkspace().validateEdit(new IFile[]{rscFile}, IWorkspace.VALIDATE_PROMPT);
3133
			}
3148
			}
3134
			rscFile.setContents(inputStream, IResource.FORCE, null);
3149
			rscFile.setContents(inputStream, IResource.FORCE, null);
3135
		} else {
3150
		} else {
(-)a/org.eclipse.jdt.core/model/org/eclipse/jdt/internal/core/JavadocContents.java (-6 / +4 lines)
Lines 378-390 Link Here
378
		}
378
		}
379
		IType declaringType = this.type;
379
		IType declaringType = this.type;
380
		if (declaringType.isMember()) {
380
		if (declaringType.isMember()) {
381
			int depth = 0;
382
			// might need to remove a part of the signature corresponding to the synthetic argument (only for constructor)
381
			// might need to remove a part of the signature corresponding to the synthetic argument (only for constructor)
383
			if (method.isConstructor() && !Flags.isStatic(declaringType.getFlags())) {
382
			if (method.isConstructor() && !Flags.isStatic(declaringType.getFlags())) {
384
				depth++;
385
			}
386
			if (depth != 0) {
387
				// depth is 1
388
				int indexOfOpeningParen = anchor.indexOf('(');
383
				int indexOfOpeningParen = anchor.indexOf('(');
389
				if (indexOfOpeningParen == -1) {
384
				if (indexOfOpeningParen == -1) {
390
					// should not happen as this is a method signature
385
					// should not happen as this is a method signature
Lines 395-402 Link Here
395
				int indexOfComma = anchor.indexOf(',', index);
390
				int indexOfComma = anchor.indexOf(',', index);
396
				if (indexOfComma != -1) {
391
				if (indexOfComma != -1) {
397
					index = indexOfComma + 2;
392
					index = indexOfComma + 2;
398
					anchor = anchor.substring(0, indexOfOpeningParen) + anchor.substring(index);
393
				} else {
394
					// no argument, but a synthetic argument
395
					index = anchor.indexOf(')', index);
399
				}
396
				}
397
				anchor = anchor.substring(0, indexOfOpeningParen) + anchor.substring(index);
400
			}
398
			}
401
		}
399
		}
402
		return anchor + JavadocConstants.ANCHOR_PREFIX_END;
400
		return anchor + JavadocConstants.ANCHOR_PREFIX_END;
(-)a/org.eclipse.jdt.core/model/org/eclipse/jdt/internal/core/NameLookup.java (+7 lines)
Lines 987-992 Link Here
987
					break;
987
					break;
988
				case IPackageFragmentRoot.K_SOURCE :
988
				case IPackageFragmentRoot.K_SOURCE :
989
					seekTypesInSourcePackage(matchName, pkg, firstDot, partialMatch, topLevelTypeName, acceptFlags, requestor);
989
					seekTypesInSourcePackage(matchName, pkg, firstDot, partialMatch, topLevelTypeName, acceptFlags, requestor);
990
					if (matchName.indexOf('$') != -1) {
991
						matchName= matchName.replace('$', '.');
992
						firstDot = matchName.indexOf('.');
993
						if (!partialMatch)
994
							topLevelTypeName = firstDot == -1 ? matchName : matchName.substring(0, firstDot);
995
						seekTypesInSourcePackage(matchName, pkg, firstDot, partialMatch, topLevelTypeName, acceptFlags, requestor);
996
					}
990
					break;
997
					break;
991
				default :
998
				default :
992
					return;
999
					return;
(-)a/org.eclipse.jdt.core/model/org/eclipse/jdt/internal/core/NamedMember.java (-2 / +10 lines)
Lines 226-239 Link Here
226
		}
226
		}
227
		StringBuffer buffer = new StringBuffer(declaringType.getTypeQualifiedName(enclosingTypeSeparator, showParameters));
227
		StringBuffer buffer = new StringBuffer(declaringType.getTypeQualifiedName(enclosingTypeSeparator, showParameters));
228
		buffer.append(enclosingTypeSeparator);
228
		buffer.append(enclosingTypeSeparator);
229
		String simpleName = this.name.length() == 0 ? Integer.toString(this.occurrenceCount) : this.name;
229
		String simpleName = this.name.length() == 0 ? getOccurrenceCountSignature() : this.name;
230
		buffer.append(simpleName);
230
		buffer.append(simpleName);
231
		if (showParameters) {
231
		if (showParameters) {
232
			appendTypeParameters(buffer);
232
			appendTypeParameters(buffer);
233
		}
233
		}
234
		return buffer.toString();
234
		return buffer.toString();
235
	}
235
	}
236
236
	/*
237
	 * Returns the String representation of the occurrence count for this element.
238
	 * The occurrence count is a unique number representation to identify the particular element.
239
	 *
240
	 * @return the occurrence count for this element in the form of String
241
	 */
242
	protected String getOccurrenceCountSignature() {
243
		return Integer.toString(this.occurrenceCount);
244
	}
237
	protected ITypeParameter[] getTypeParameters() throws JavaModelException {
245
	protected ITypeParameter[] getTypeParameters() throws JavaModelException {
238
		return null;
246
		return null;
239
	}
247
	}
(-)a/org.eclipse.jdt.core/model/org/eclipse/jdt/internal/core/PackageFragmentRoot.java (-3 / +15 lines)
Lines 1-5 Link Here
1
/*******************************************************************************
1
/*******************************************************************************
2
 * Copyright (c) 2000, 2010 IBM Corporation and others.
2
 * Copyright (c) 2000, 2012 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 154-164 Link Here
154
	return computeChildren(info, underlyingResource);
154
	return computeChildren(info, underlyingResource);
155
}
155
}
156
156
157
SourceMapper createSourceMapper(IPath sourcePath, IPath rootPath) {
157
SourceMapper createSourceMapper(IPath sourcePath, IPath rootPath) throws JavaModelException {
158
	IClasspathEntry entry = ((JavaProject) getParent()).getClasspathEntryFor(getPath());
159
	String encoding = (entry== null) ? null : ((ClasspathEntry) entry).getSourceAttachmentEncoding();
158
	SourceMapper mapper = new SourceMapper(
160
	SourceMapper mapper = new SourceMapper(
159
		sourcePath,
161
		sourcePath,
160
		rootPath == null ? null : rootPath.toOSString(),
162
		rootPath == null ? null : rootPath.toOSString(),
161
		getJavaProject().getOptions(true)); // cannot use workspace options if external jar is 1.5 jar and workspace options are 1.4 options
163
		getJavaProject().getOptions(true),// cannot use workspace options if external jar is 1.5 jar and workspace options are 1.4 options
164
		encoding);
165
162
	return mapper;
166
	return mapper;
163
}
167
}
164
/*
168
/*
Lines 707-712 Link Here
707
	return resource().hashCode();
711
	return resource().hashCode();
708
}
712
}
709
713
714
public boolean ignoreOptionalProblems() {
715
	try {
716
		return ((PackageFragmentRootInfo) getElementInfo()).ignoreOptionalProblems(this);
717
	} catch (JavaModelException e) {
718
		return false;
719
	}
720
}
721
710
/**
722
/**
711
 * @see IPackageFragmentRoot
723
 * @see IPackageFragmentRoot
712
 */
724
 */
(-)a/org.eclipse.jdt.core/model/org/eclipse/jdt/internal/core/PackageFragmentRootInfo.java (-1 / +12 lines)
Lines 1-5 Link Here
1
/*******************************************************************************
1
/*******************************************************************************
2
 * Copyright (c) 2000, 2008 IBM Corporation and others.
2
 * Copyright (c) 2000, 2012 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 41-51 Link Here
41
	 * A array with all the non-java resources contained by this PackageFragment
41
	 * A array with all the non-java resources contained by this PackageFragment
42
	 */
42
	 */
43
	protected Object[] nonJavaResources;
43
	protected Object[] nonJavaResources;
44
45
	private boolean ignoreOptionalProblems;
46
	private boolean initialized;
44
/**
47
/**
45
 * Create and initialize a new instance of the receiver
48
 * Create and initialize a new instance of the receiver
46
 */
49
 */
47
public PackageFragmentRootInfo() {
50
public PackageFragmentRootInfo() {
48
	this.nonJavaResources = null;
51
	this.nonJavaResources = null;
52
	this.initialized = false;
49
}
53
}
50
/**
54
/**
51
 * Starting at this folder, create non-java resources for this package fragment root
55
 * Starting at this folder, create non-java resources for this package fragment root
Lines 155-160 Link Here
155
protected SourceMapper getSourceMapper() {
159
protected SourceMapper getSourceMapper() {
156
	return this.sourceMapper;
160
	return this.sourceMapper;
157
}
161
}
162
boolean ignoreOptionalProblems(PackageFragmentRoot packageFragmentRoot) throws JavaModelException {
163
	if (this.initialized == false) {
164
		this.ignoreOptionalProblems = ((ClasspathEntry) packageFragmentRoot.getRawClasspathEntry()).ignoreOptionalProblems();
165
		this.initialized = true;
166
	}
167
	return this.ignoreOptionalProblems;
168
}
158
private static boolean isClasspathEntry(IPath path, IClasspathEntry[] resolvedClasspath) {
169
private static boolean isClasspathEntry(IPath path, IClasspathEntry[] resolvedClasspath) {
159
	for (int i = 0, length = resolvedClasspath.length; i < length; i++) {
170
	for (int i = 0, length = resolvedClasspath.length; i < length; i++) {
160
		IClasspathEntry entry = resolvedClasspath[i];
171
		IClasspathEntry entry = resolvedClasspath[i];
(-)a/org.eclipse.jdt.core/model/org/eclipse/jdt/internal/core/ResolvedSourceType.java (-2 / +3 lines)
Lines 1-5 Link Here
1
/*******************************************************************************
1
/*******************************************************************************
2
 * Copyright (c) 2004, 2008 IBM Corporation and others.
2
 * Copyright (c) 2004, 2012 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 59-66 Link Here
59
	}
59
	}
60
60
61
	public JavaElement unresolved() {
61
	public JavaElement unresolved() {
62
		SourceRefElement handle = new SourceType(this.parent, this.name);
62
		SourceType handle = new SourceType(this.parent, this.name);
63
		handle.occurrenceCount = this.occurrenceCount;
63
		handle.occurrenceCount = this.occurrenceCount;
64
		handle.localOccurrenceCount = this.localOccurrenceCount;
64
		return handle;
65
		return handle;
65
	}
66
	}
66
}
67
}
(-)a/org.eclipse.jdt.core/model/org/eclipse/jdt/internal/core/SelectionRequestor.java (-1 / +1 lines)
Lines 341-347 Link Here
341
	}
341
	}
342
}
342
}
343
public void acceptLocalMethod(MethodBinding methodBinding) {
343
public void acceptLocalMethod(MethodBinding methodBinding) {
344
	IJavaElement res = findLocalElement(methodBinding.sourceStart());
344
	IJavaElement res = findLocalElement(methodBinding.original().sourceStart());
345
	if(res != null) {
345
	if(res != null) {
346
		if(res.getElementType() == IJavaElement.METHOD) {
346
		if(res.getElementType() == IJavaElement.METHOD) {
347
			IMethod method = (IMethod) res;
347
			IMethod method = (IMethod) res;
(-)a/org.eclipse.jdt.core/model/org/eclipse/jdt/internal/core/SetClasspathOperation.java (+1 lines)
Lines 114-119 Link Here
114
		IJavaModelStatus status = super.verify();
114
		IJavaModelStatus status = super.verify();
115
		if (!status.isOK())
115
		if (!status.isOK())
116
			return status;
116
			return status;
117
		this.project.flushClasspathProblemMarkers(false, false, true);
117
		return ClasspathEntry.validateClasspath(	this.project, this.newRawClasspath, this.newOutputLocation);
118
		return ClasspathEntry.validateClasspath(	this.project, this.newRawClasspath, this.newOutputLocation);
118
	}
119
	}
119
120
(-)a/org.eclipse.jdt.core/model/org/eclipse/jdt/internal/core/SourceMapper.java (-7 / +21 lines)
Lines 246-255 Link Here
246
	int anonymousCounter;
246
	int anonymousCounter;
247
	int anonymousClassName;
247
	int anonymousClassName;
248
248
249
	String encoding;
250
	String defaultEncoding;
249
	/**
251
	/**
250
	 *Options to be used
252
	 *Options to be used
251
	 */
253
	 */
252
	String encoding;
253
	Map options;
254
	Map options;
254
255
255
	/**
256
	/**
Lines 261-275 Link Here
261
		this.areRootPathsComputed = false;
262
		this.areRootPathsComputed = false;
262
	}
263
	}
263
264
265
	public SourceMapper(IPath sourcePath, String rootPath, Map options) {
266
		this(sourcePath, rootPath, options, null);
267
	}
264
	/**
268
	/**
265
	 * Creates a <code>SourceMapper</code> that locates source in the zip file
269
	 * Creates a <code>SourceMapper</code> that locates source in the zip file
266
	 * at the given location in the specified package fragment root.
270
	 * at the given location in the specified package fragment root.
267
	 */
271
	 */
268
	public SourceMapper(IPath sourcePath, String rootPath, Map options) {
272
	public SourceMapper(IPath sourcePath, String rootPath, Map options, String encoding) {
269
		this.areRootPathsComputed = false;
273
		this.areRootPathsComputed = false;
270
		this.options = options;
274
		this.options = options;
275
		this.encoding = encoding;
271
		try {
276
		try {
272
			this.encoding = ResourcesPlugin.getWorkspace().getRoot().getDefaultCharset();
277
			this.defaultEncoding = ResourcesPlugin.getWorkspace().getRoot().getDefaultCharset();
273
		} catch (CoreException e) {
278
		} catch (CoreException e) {
274
			// use no encoding
279
			// use no encoding
275
		}
280
		}
Lines 1020-1028 Link Here
1020
			IResource res = ((IContainer)target).findMember(fullName);
1025
			IResource res = ((IContainer)target).findMember(fullName);
1021
			if (res instanceof IFile) {
1026
			if (res instanceof IFile) {
1022
				try {
1027
				try {
1023
					source = org.eclipse.jdt.internal.core.util.Util.getResourceContentsAsCharArray((IFile)res);
1028
					// Order of preference: charSet supplied, this.encoding or this.defaultEncoding in that order
1029
					try {
1030
						// Use the implicit encoding only when the source attachment's encoding hasn't been explicitly set.
1031
						charSet = ((IFile) res).getCharset(this.encoding == null);
1032
					} catch (CoreException e) {
1033
						// Ignore
1034
					}
1035
					source = org.eclipse.jdt.internal.core.util.Util.getResourceContentsAsCharArray((IFile) res,
1036
									charSet == null ? (this.encoding == null ? this.defaultEncoding : this.encoding) : charSet);
1024
				} catch (JavaModelException e) {
1037
				} catch (JavaModelException e) {
1025
					// ignore
1038
					// Ignore
1026
				}
1039
				}
1027
			}
1040
			}
1028
		} else {
1041
		} else {
Lines 1030-1036 Link Here
1030
				// https://bugs.eclipse.org/bugs/show_bug.cgi?id=303511
1043
				// https://bugs.eclipse.org/bugs/show_bug.cgi?id=303511
1031
				// For a resource inside the workspace, use the encoding set on the resource
1044
				// For a resource inside the workspace, use the encoding set on the resource
1032
				if (target instanceof IFile)
1045
				if (target instanceof IFile)
1033
					charSet = ((IFile)target).getCharset();
1046
					charSet = ((IFile)target).getCharset(this.encoding == null);
1034
			} catch (CoreException e) {
1047
			} catch (CoreException e) {
1035
				// Ignore
1048
				// Ignore
1036
			}
1049
			}
Lines 1414-1420 Link Here
1414
		try {
1427
		try {
1415
			byte[] bytes = Util.getZipEntryByteContent(entry, zip);
1428
			byte[] bytes = Util.getZipEntryByteContent(entry, zip);
1416
			if (bytes != null) {
1429
			if (bytes != null) {
1417
				return Util.bytesToChar(bytes, charSet == null ? this.encoding : charSet);
1430
				// Order of preference: charSet supplied, this.encoding or this.defaultEncoding in that order
1431
				return Util.bytesToChar(bytes, charSet == null ? (this.encoding == null ? this.defaultEncoding : this.encoding) : charSet);
1418
			}
1432
			}
1419
		} catch (IOException e) {
1433
		} catch (IOException e) {
1420
			// ignore
1434
			// ignore
(-)a/org.eclipse.jdt.core/model/org/eclipse/jdt/internal/core/SourceType.java (-2 / +16 lines)
Lines 1-5 Link Here
1
/*******************************************************************************
1
/*******************************************************************************
2
 * Copyright (c) 2000, 2008 IBM Corporation and others.
2
 * Copyright (c) 2000, 2012 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 35-40 Link Here
35
 */
35
 */
36
36
37
public class SourceType extends NamedMember implements IType {
37
public class SourceType extends NamedMember implements IType {
38
39
/*
40
 * A count to uniquely identify this element within the context of the enclosing type.
41
 * Currently this is computed and used only for anonymous types.
42
 */
43
public int localOccurrenceCount = 1;
38
44
39
protected SourceType(JavaElement parent, String name) {
45
protected SourceType(JavaElement parent, String name) {
40
	super(parent, name);
46
	super(parent, name);
Lines 274-279 Link Here
274
 */
280
 */
275
public String getFullyQualifiedParameterizedName() throws JavaModelException {
281
public String getFullyQualifiedParameterizedName() throws JavaModelException {
276
	return getFullyQualifiedName('.', true/*show parameters*/);
282
	return getFullyQualifiedName('.', true/*show parameters*/);
283
}
284
/*
285
 * For source types, the occurrence count is the one computed in the context of the immediately enclosing type.
286
 *
287
 */
288
protected String getOccurrenceCountSignature() {
289
	return Integer.toString(this.localOccurrenceCount);
277
}
290
}
278
/*
291
/*
279
 * @see JavaElement
292
 * @see JavaElement
Lines 815-822 Link Here
815
	return op.getResult();
828
	return op.getResult();
816
}
829
}
817
public JavaElement resolved(Binding binding) {
830
public JavaElement resolved(Binding binding) {
818
	SourceRefElement resolvedHandle = new ResolvedSourceType(this.parent, this.name, new String(binding.computeUniqueKey()));
831
	ResolvedSourceType resolvedHandle = new ResolvedSourceType(this.parent, this.name, new String(binding.computeUniqueKey()));
819
	resolvedHandle.occurrenceCount = this.occurrenceCount;
832
	resolvedHandle.occurrenceCount = this.occurrenceCount;
833
	resolvedHandle.localOccurrenceCount = this.localOccurrenceCount;
820
	return resolvedHandle;
834
	return resolvedHandle;
821
}
835
}
822
/**
836
/**
(-)a/org.eclipse.jdt.core/model/org/eclipse/jdt/internal/core/builder/ClasspathLocation.java (-3 / +3 lines)
Lines 1-5 Link Here
1
/*******************************************************************************
1
/*******************************************************************************
2
 * Copyright (c) 2000, 2006 IBM Corporation and others.
2
 * Copyright (c) 2000, 2012 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 18-25 Link Here
18
18
19
public abstract class ClasspathLocation {
19
public abstract class ClasspathLocation {
20
20
21
static ClasspathLocation forSourceFolder(IContainer sourceFolder, IContainer outputFolder, char[][] inclusionPatterns, char[][] exclusionPatterns) {
21
static ClasspathLocation forSourceFolder(IContainer sourceFolder, IContainer outputFolder, char[][] inclusionPatterns, char[][] exclusionPatterns, boolean ignoreOptionalProblems) {
22
	return new ClasspathMultiDirectory(sourceFolder, outputFolder, inclusionPatterns, exclusionPatterns);
22
	return new ClasspathMultiDirectory(sourceFolder, outputFolder, inclusionPatterns, exclusionPatterns, ignoreOptionalProblems);
23
}
23
}
24
24
25
public static ClasspathLocation forBinaryFolder(IContainer binaryFolder, boolean isOutputFolder, AccessRuleSet accessRuleSet) {
25
public static ClasspathLocation forBinaryFolder(IContainer binaryFolder, boolean isOutputFolder, AccessRuleSet accessRuleSet) {
(-)a/org.eclipse.jdt.core/model/org/eclipse/jdt/internal/core/builder/ClasspathMultiDirectory.java (-4 / +7 lines)
Lines 1-5 Link Here
1
/*******************************************************************************
1
/*******************************************************************************
2
 * Copyright (c) 2000, 2010 IBM Corporation and others.
2
 * Copyright (c) 2000, 2012 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 15-34 Link Here
15
import org.eclipse.jdt.core.compiler.CharOperation;
15
import org.eclipse.jdt.core.compiler.CharOperation;
16
import org.eclipse.jdt.internal.core.util.Util;
16
import org.eclipse.jdt.internal.core.util.Util;
17
17
18
class ClasspathMultiDirectory extends ClasspathDirectory {
18
public class ClasspathMultiDirectory extends ClasspathDirectory {
19
19
20
IContainer sourceFolder;
20
IContainer sourceFolder;
21
char[][] inclusionPatterns; // used by builders when walking source folders
21
char[][] inclusionPatterns; // used by builders when walking source folders
22
char[][] exclusionPatterns; // used by builders when walking source folders
22
char[][] exclusionPatterns; // used by builders when walking source folders
23
boolean hasIndependentOutputFolder; // if output folder is not equal to any of the source folders
23
boolean hasIndependentOutputFolder; // if output folder is not equal to any of the source folders
24
public boolean ignoreOptionalProblems;
24
25
25
ClasspathMultiDirectory(IContainer sourceFolder, IContainer binaryFolder, char[][] inclusionPatterns, char[][] exclusionPatterns) {
26
ClasspathMultiDirectory(IContainer sourceFolder, IContainer binaryFolder, char[][] inclusionPatterns, char[][] exclusionPatterns, boolean ignoreOptionalProblems) {
26
	super(binaryFolder, true, null);
27
	super(binaryFolder, true, null);
27
28
28
	this.sourceFolder = sourceFolder;
29
	this.sourceFolder = sourceFolder;
29
	this.inclusionPatterns = inclusionPatterns;
30
	this.inclusionPatterns = inclusionPatterns;
30
	this.exclusionPatterns = exclusionPatterns;
31
	this.exclusionPatterns = exclusionPatterns;
31
	this.hasIndependentOutputFolder = false;
32
	this.hasIndependentOutputFolder = false;
33
	this.ignoreOptionalProblems = ignoreOptionalProblems;
32
34
33
	// handle the case when a state rebuilds a source folder
35
	// handle the case when a state rebuilds a source folder
34
	if (this.inclusionPatterns != null && this.inclusionPatterns.length == 0)
36
	if (this.inclusionPatterns != null && this.inclusionPatterns.length == 0)
Lines 42-48 Link Here
42
	if (!(o instanceof ClasspathMultiDirectory)) return false;
44
	if (!(o instanceof ClasspathMultiDirectory)) return false;
43
45
44
	ClasspathMultiDirectory md = (ClasspathMultiDirectory) o;
46
	ClasspathMultiDirectory md = (ClasspathMultiDirectory) o;
45
	return this.sourceFolder.equals(md.sourceFolder) && this.binaryFolder.equals(md.binaryFolder)
47
	return this.ignoreOptionalProblems == md.ignoreOptionalProblems 
48
		&& this.sourceFolder.equals(md.sourceFolder) && this.binaryFolder.equals(md.binaryFolder)
46
		&& CharOperation.equals(this.inclusionPatterns, md.inclusionPatterns)
49
		&& CharOperation.equals(this.inclusionPatterns, md.inclusionPatterns)
47
		&& CharOperation.equals(this.exclusionPatterns, md.exclusionPatterns);
50
		&& CharOperation.equals(this.exclusionPatterns, md.exclusionPatterns);
48
}
51
}
(-)a/org.eclipse.jdt.core/model/org/eclipse/jdt/internal/core/builder/NameEnvironment.java (-2 / +2 lines)
Lines 1-5 Link Here
1
/*******************************************************************************
1
/*******************************************************************************
2
 * Copyright (c) 2000, 2008 IBM Corporation and others.
2
 * Copyright (c) 2000, 2012 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 114-120 Link Here
114
						createOutputFolder(outputFolder);
114
						createOutputFolder(outputFolder);
115
				}
115
				}
116
				sLocations.add(
116
				sLocations.add(
117
					ClasspathLocation.forSourceFolder((IContainer) target, outputFolder, entry.fullInclusionPatternChars(), entry.fullExclusionPatternChars()));
117
					ClasspathLocation.forSourceFolder((IContainer) target, outputFolder, entry.fullInclusionPatternChars(), entry.fullExclusionPatternChars(), entry.ignoreOptionalProblems()));
118
				continue nextEntry;
118
				continue nextEntry;
119
119
120
			case IClasspathEntry.CPE_PROJECT :
120
			case IClasspathEntry.CPE_PROJECT :
(-)a/org.eclipse.jdt.core/model/org/eclipse/jdt/internal/core/builder/SourceFile.java (-1 / +4 lines)
Lines 1-5 Link Here
1
/*******************************************************************************
1
/*******************************************************************************
2
 * Copyright (c) 2000, 2009 IBM Corporation and others.
2
 * Copyright (c) 2000, 2012 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 103-108 Link Here
103
public int hashCode() {
103
public int hashCode() {
104
	return this.initialTypeName.hashCode();
104
	return this.initialTypeName.hashCode();
105
}
105
}
106
public boolean ignoreOptionalProblems() {
107
	return this.sourceLocation.ignoreOptionalProblems;
108
}
106
String typeLocator() {
109
String typeLocator() {
107
	return this.resource.getProjectRelativePath().toString();
110
	return this.resource.getProjectRelativePath().toString();
108
}
111
}
(-)a/org.eclipse.jdt.core/model/org/eclipse/jdt/internal/core/builder/State.java (-4 / +5 lines)
Lines 1-5 Link Here
1
/*******************************************************************************
1
/*******************************************************************************
2
 * Copyright (c) 2000, 2010 IBM Corporation and others.
2
 * Copyright (c) 2000, 2012 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 27-33 Link Here
27
// NOTE: this state cannot contain types that are not defined in this project
27
// NOTE: this state cannot contain types that are not defined in this project
28
28
29
String javaProjectName;
29
String javaProjectName;
30
ClasspathMultiDirectory[] sourceLocations;
30
public ClasspathMultiDirectory[] sourceLocations;
31
ClasspathLocation[] binaryLocations;
31
ClasspathLocation[] binaryLocations;
32
// keyed by the project relative path of the type (i.e. "src1/p1/p2/A.java"), value is a ReferenceCollection or an AdditionalTypeCollection
32
// keyed by the project relative path of the type (i.e. "src1/p1/p2/A.java"), value is a ReferenceCollection or an AdditionalTypeCollection
33
SimpleLookupTable references;
33
SimpleLookupTable references;
Lines 44-50 Link Here
44
private StringSet structurallyChangedTypes;
44
private StringSet structurallyChangedTypes;
45
public static int MaxStructurallyChangedTypes = 100; // keep track of ? structurally changed types, otherwise consider all to be changed
45
public static int MaxStructurallyChangedTypes = 100; // keep track of ? structurally changed types, otherwise consider all to be changed
46
46
47
public static final byte VERSION = 0x0019; // fix for 325755
47
public static final byte VERSION = 0x001B;
48
48
49
static final byte SOURCE_FOLDER = 1;
49
static final byte SOURCE_FOLDER = 1;
50
static final byte BINARY_FOLDER = 2;
50
static final byte BINARY_FOLDER = 2;
Lines 246-252 Link Here
246
		if ((folderName = in.readUTF()).length() > 0) sourceFolder = project.getFolder(folderName);
246
		if ((folderName = in.readUTF()).length() > 0) sourceFolder = project.getFolder(folderName);
247
		if ((folderName = in.readUTF()).length() > 0) outputFolder = project.getFolder(folderName);
247
		if ((folderName = in.readUTF()).length() > 0) outputFolder = project.getFolder(folderName);
248
		ClasspathMultiDirectory md =
248
		ClasspathMultiDirectory md =
249
			(ClasspathMultiDirectory) ClasspathLocation.forSourceFolder(sourceFolder, outputFolder, readNames(in), readNames(in));
249
			(ClasspathMultiDirectory) ClasspathLocation.forSourceFolder(sourceFolder, outputFolder, readNames(in), readNames(in), in.readBoolean());
250
		if (in.readBoolean())
250
		if (in.readBoolean())
251
			md.hasIndependentOutputFolder = true;
251
			md.hasIndependentOutputFolder = true;
252
		newState.sourceLocations[i] = md;
252
		newState.sourceLocations[i] = md;
Lines 425-430 Link Here
425
		out.writeUTF(md.binaryFolder.getProjectRelativePath().toString());
425
		out.writeUTF(md.binaryFolder.getProjectRelativePath().toString());
426
		writeNames(md.inclusionPatterns, out);
426
		writeNames(md.inclusionPatterns, out);
427
		writeNames(md.exclusionPatterns, out);
427
		writeNames(md.exclusionPatterns, out);
428
		out.writeBoolean(md.ignoreOptionalProblems);
428
		out.writeBoolean(md.hasIndependentOutputFolder);
429
		out.writeBoolean(md.hasIndependentOutputFolder);
429
	}
430
	}
430
431
(-)a/org.eclipse.jdt.core/model/org/eclipse/jdt/internal/core/hierarchy/HierarchyResolver.java (+2 lines)
Lines 846-851 Link Here
846
					char[][] memberTypeNames = CharOperation.splitOn('$', typeName, firstDollar+1, typeName.length);
846
					char[][] memberTypeNames = CharOperation.splitOn('$', typeName, firstDollar+1, typeName.length);
847
					for (int i = 0; i < memberTypeNames.length; i++) {
847
					for (int i = 0; i < memberTypeNames.length; i++) {
848
						this.focusType = this.focusType.getMemberType(memberTypeNames[i]);
848
						this.focusType = this.focusType.getMemberType(memberTypeNames[i]);
849
						if (this.focusType == null)
850
							return null;
849
					}
851
					}
850
				}
852
				}
851
			}
853
			}
(-)a/org.eclipse.jdt.core/model/org/eclipse/jdt/internal/core/jdom/CompilationUnit.java (-1 / +4 lines)
Lines 1-5 Link Here
1
/*******************************************************************************
1
/*******************************************************************************
2
 * Copyright (c) 2000, 2009 IBM Corporation and others.
2
 * Copyright (c) 2000, 2012 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 51-56 Link Here
51
public char[][] getPackageName() {
51
public char[][] getPackageName() {
52
	return null;
52
	return null;
53
}
53
}
54
public boolean ignoreOptionalProblems() {
55
	return false;
56
}
54
public String toString() {
57
public String toString() {
55
	return "CompilationUnit[" + new String(this.fFileName) + "]";  //$NON-NLS-2$ //$NON-NLS-1$
58
	return "CompilationUnit[" + new String(this.fFileName) + "]";  //$NON-NLS-2$ //$NON-NLS-1$
56
}
59
}
(-)a/org.eclipse.jdt.core/model/org/eclipse/jdt/internal/core/util/BootstrapMethodsAttribute.java (+63 lines)
Added Link Here
1
/*******************************************************************************
2
 * Copyright (c) 2011 IBM Corporation and others.
3
 * All rights reserved. This program and the accompanying materials
4
 * are made available under the terms of the Eclipse Public License v1.0
5
 * which accompanies this distribution, and is available at
6
 * http://www.eclipse.org/legal/epl-v10.html
7
 *
8
 * Contributors:
9
 *     IBM Corporation - initial API and implementation
10
 *******************************************************************************/
11
package org.eclipse.jdt.internal.core.util;
12
13
import org.eclipse.jdt.core.util.ClassFormatException;
14
import org.eclipse.jdt.core.util.IBootstrapMethodsAttribute;
15
import org.eclipse.jdt.core.util.IBootstrapMethodsEntry;
16
import org.eclipse.jdt.core.util.IConstantPool;
17
18
/**
19
 * Default implementation of IBootstrapMethodsAttribute.
20
 */
21
public class BootstrapMethodsAttribute extends ClassFileAttribute implements IBootstrapMethodsAttribute {
22
	private static final IBootstrapMethodsEntry[] NO_ENTRIES = new IBootstrapMethodsEntry[0];
23
24
	private IBootstrapMethodsEntry[] entries;
25
	private int numberOfBootstrapMethods;
26
27
	/**
28
	 * Constructor for BootstrapMethodsAttribute.
29
	 * @param classFileBytes
30
	 * @param constantPool
31
	 * @param offset
32
	 * @throws ClassFormatException
33
	 */
34
	public BootstrapMethodsAttribute(
35
			byte[] classFileBytes,
36
			IConstantPool constantPool,
37
			int offset) throws ClassFormatException {
38
		super(classFileBytes, constantPool, offset);
39
		this.numberOfBootstrapMethods = u2At(classFileBytes, 6, offset);
40
		final int length = this.numberOfBootstrapMethods;
41
		if (length != 0) {
42
			int readOffset = 8;
43
			this.entries = new IBootstrapMethodsEntry[length];
44
			for (int i = 0; i < length; i++) {
45
				this.entries[i] = new BootstrapMethodsEntry(classFileBytes, constantPool, offset + readOffset);
46
				readOffset += 8;
47
			}
48
		} else {
49
			this.entries = NO_ENTRIES;
50
		}
51
	}
52
53
	/**
54
	 * @see IBootstrapMethodsAttribute#getBootstrapMethods()
55
	 */
56
	public IBootstrapMethodsEntry[] getBootstrapMethods() {
57
		return this.entries;
58
	}
59
	
60
	public int getBootstrapMethodsLength() {
61
		return this.numberOfBootstrapMethods;
62
	}
63
}
(-)a/org.eclipse.jdt.core/model/org/eclipse/jdt/internal/core/util/BootstrapMethodsEntry.java (+52 lines)
Added Link Here
1
/*******************************************************************************
2
 * Copyright (c) 2011 IBM Corporation and others.
3
 * All rights reserved. This program and the accompanying materials
4
 * are made available under the terms of the Eclipse Public License v1.0
5
 * which accompanies this distribution, and is available at
6
 * http://www.eclipse.org/legal/epl-v10.html
7
 *
8
 * Contributors:
9
 *     IBM Corporation - initial API and implementation
10
 *******************************************************************************/
11
package org.eclipse.jdt.internal.core.util;
12
13
import org.eclipse.jdt.core.util.ClassFormatException;
14
import org.eclipse.jdt.core.util.IBootstrapMethodsEntry;
15
import org.eclipse.jdt.core.util.IConstantPool;
16
17
/**
18
 * Default implementation of {@link IBootstrapMethodsEntry}
19
 */
20
public class BootstrapMethodsEntry
21
	extends ClassFileStruct
22
	implements IBootstrapMethodsEntry {
23
24
	private int bootstrapMethodReference;
25
	private int[] bootstrapArguments;
26
27
	public BootstrapMethodsEntry(byte classFileBytes[], IConstantPool constantPool, int offset) throws ClassFormatException {
28
		this.bootstrapMethodReference = u2At(classFileBytes, 0, offset);
29
		int length = u2At(classFileBytes, 2, offset);
30
		int[] arguments = new int[length];
31
		int position = 4;
32
		for (int i = 0; i < length; i++) {
33
			arguments[i] = u2At(classFileBytes, position, offset);
34
			position += 2;
35
		}
36
		this.bootstrapArguments = arguments;
37
	}
38
39
	/**
40
	 * @see IBootstrapMethodsEntry#getBootstrapArguments()
41
	 */
42
	public int[] getBootstrapArguments() {
43
		return this.bootstrapArguments;
44
	}
45
46
	/**
47
	 * @see IBootstrapMethodsEntry#getBootstrapMethodReference()
48
	 */
49
	public int getBootstrapMethodReference() {
50
		return this.bootstrapMethodReference;
51
	}
52
}
(-)a/org.eclipse.jdt.core/model/org/eclipse/jdt/internal/core/util/ClassFileReader.java (-1 / +15 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 140-145 Link Here
140
						constantPoolOffsets[i] = readOffset;
140
						constantPoolOffsets[i] = readOffset;
141
						readOffset += IConstantPoolConstant.CONSTANT_NameAndType_SIZE;
141
						readOffset += IConstantPoolConstant.CONSTANT_NameAndType_SIZE;
142
						break;
142
						break;
143
					case IConstantPoolConstant.CONSTANT_MethodHandle :
144
						constantPoolOffsets[i] = readOffset;
145
						readOffset += IConstantPoolConstant.CONSTANT_MethodHandle_SIZE;
146
						break;
147
					case IConstantPoolConstant.CONSTANT_MethodType :
148
						constantPoolOffsets[i] = readOffset;
149
						readOffset += IConstantPoolConstant.CONSTANT_MethodType_SIZE;
150
						break;
151
					case IConstantPoolConstant.CONSTANT_InvokeDynamic :
152
						constantPoolOffsets[i] = readOffset;
153
						readOffset += IConstantPoolConstant.CONSTANT_InvokeDynamic_SIZE;
154
						break;
143
					default:
155
					default:
144
						throw new ClassFormatException(ClassFormatException.INVALID_TAG_CONSTANT);
156
						throw new ClassFormatException(ClassFormatException.INVALID_TAG_CONSTANT);
145
				}
157
				}
Lines 261-266 Link Here
261
							this.attributes[attributesIndex++] = new RuntimeVisibleAnnotationsAttribute(classFileBytes, this.constantPool, readOffset);
273
							this.attributes[attributesIndex++] = new RuntimeVisibleAnnotationsAttribute(classFileBytes, this.constantPool, readOffset);
262
						} else if (equals(attributeName, IAttributeNamesConstants.RUNTIME_INVISIBLE_ANNOTATIONS)) {
274
						} else if (equals(attributeName, IAttributeNamesConstants.RUNTIME_INVISIBLE_ANNOTATIONS)) {
263
							this.attributes[attributesIndex++] = new RuntimeInvisibleAnnotationsAttribute(classFileBytes, this.constantPool, readOffset);
275
							this.attributes[attributesIndex++] = new RuntimeInvisibleAnnotationsAttribute(classFileBytes, this.constantPool, readOffset);
276
						} else if (equals(attributeName, IAttributeNamesConstants.BOOTSTRAP_METHODS)) {
277
							this.attributes[attributesIndex++] = new BootstrapMethodsAttribute(classFileBytes, this.constantPool, readOffset);
264
						} else {
278
						} else {
265
							this.attributes[attributesIndex++] = new ClassFileAttribute(classFileBytes, this.constantPool, readOffset);
279
							this.attributes[attributesIndex++] = new ClassFileAttribute(classFileBytes, this.constantPool, readOffset);
266
						}
280
						}
(-)a/org.eclipse.jdt.core/model/org/eclipse/jdt/internal/core/util/CodeAttribute.java (-4 / +3 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 1049-1062 Link Here
1049
				case IOpcodeMnemonics.INVOKEDYNAMIC :
1049
				case IOpcodeMnemonics.INVOKEDYNAMIC :
1050
					index = u2At(this.classFileBytes, 1, pc);
1050
					index = u2At(this.classFileBytes, 1, pc);
1051
					constantPoolEntry = this.constantPool.decodeEntry(index);
1051
					constantPoolEntry = this.constantPool.decodeEntry(index);
1052
					if (constantPoolEntry.getKind() != IConstantPoolConstant.CONSTANT_NameAndType) {
1052
					if (constantPoolEntry.getKind() != IConstantPoolConstant.CONSTANT_InvokeDynamic) {
1053
						throw new ClassFormatException(ClassFormatException.INVALID_CONSTANT_POOL_ENTRY);
1053
						throw new ClassFormatException(ClassFormatException.INVALID_CONSTANT_POOL_ENTRY);
1054
					}
1054
					}
1055
					visitor._invokedynamic(
1055
					visitor._invokedynamic(
1056
							pc - this.codeOffset,
1056
							pc - this.codeOffset,
1057
							index,
1057
							index,
1058
							this.constantPool.decodeEntry(constantPoolEntry.getNameAndTypeInfoNameIndex()),
1058
							constantPoolEntry);
1059
							this.constantPool.decodeEntry(constantPoolEntry.getNameAndTypeInfoDescriptorIndex()));
1060
					pc += 5;
1059
					pc += 5;
1061
					break;
1060
					break;
1062
				case IOpcodeMnemonics.NEW :
1061
				case IOpcodeMnemonics.NEW :
(-)a/org.eclipse.jdt.core/model/org/eclipse/jdt/internal/core/util/ConstantPool.java (-4 / +69 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 33-51 Link Here
33
	 * @see IConstantPool#decodeEntry(int)
33
	 * @see IConstantPool#decodeEntry(int)
34
	 */
34
	 */
35
	public IConstantPoolEntry decodeEntry(int index) {
35
	public IConstantPoolEntry decodeEntry(int index) {
36
		ConstantPoolEntry constantPoolEntry = new ConstantPoolEntry();
36
		ConstantPoolEntry constantPoolEntry = null;
37
		constantPoolEntry.reset();
38
		int kind = getEntryKind(index);
37
		int kind = getEntryKind(index);
39
		constantPoolEntry.setKind(kind);
40
		switch(kind) {
38
		switch(kind) {
41
			case IConstantPoolConstant.CONSTANT_Class :
39
			case IConstantPoolConstant.CONSTANT_Class :
40
				constantPoolEntry = new ConstantPoolEntry();
41
				constantPoolEntry.reset();
42
				constantPoolEntry.setKind(kind);
42
				constantPoolEntry.setClassInfoNameIndex(u2At(this.classFileBytes,  1, this.constantPoolOffset[index]));
43
				constantPoolEntry.setClassInfoNameIndex(u2At(this.classFileBytes,  1, this.constantPoolOffset[index]));
43
				constantPoolEntry.setClassInfoName(getUtf8ValueAt(constantPoolEntry.getClassInfoNameIndex()));
44
				constantPoolEntry.setClassInfoName(getUtf8ValueAt(constantPoolEntry.getClassInfoNameIndex()));
44
				break;
45
				break;
45
			case IConstantPoolConstant.CONSTANT_Double :
46
			case IConstantPoolConstant.CONSTANT_Double :
47
				constantPoolEntry = new ConstantPoolEntry();
48
				constantPoolEntry.reset();
49
				constantPoolEntry.setKind(kind);
46
				constantPoolEntry.setDoubleValue(doubleAt(this.classFileBytes, 1, this.constantPoolOffset[index]));
50
				constantPoolEntry.setDoubleValue(doubleAt(this.classFileBytes, 1, this.constantPoolOffset[index]));
47
				break;
51
				break;
48
			case IConstantPoolConstant.CONSTANT_Fieldref :
52
			case IConstantPoolConstant.CONSTANT_Fieldref :
53
				constantPoolEntry = new ConstantPoolEntry();
54
				constantPoolEntry.reset();
55
				constantPoolEntry.setKind(kind);
56
				constantPoolEntry.reset();
57
				constantPoolEntry.setKind(kind);
49
				constantPoolEntry.setClassIndex(u2At(this.classFileBytes,  1, this.constantPoolOffset[index]));
58
				constantPoolEntry.setClassIndex(u2At(this.classFileBytes,  1, this.constantPoolOffset[index]));
50
				int declaringClassIndex = u2At(this.classFileBytes,  1, this.constantPoolOffset[constantPoolEntry.getClassIndex()]);
59
				int declaringClassIndex = u2At(this.classFileBytes,  1, this.constantPoolOffset[constantPoolEntry.getClassIndex()]);
51
				constantPoolEntry.setClassName(getUtf8ValueAt(declaringClassIndex));
60
				constantPoolEntry.setClassName(getUtf8ValueAt(declaringClassIndex));
Lines 57-62 Link Here
57
				break;
66
				break;
58
			case IConstantPoolConstant.CONSTANT_Methodref :
67
			case IConstantPoolConstant.CONSTANT_Methodref :
59
			case IConstantPoolConstant.CONSTANT_InterfaceMethodref :
68
			case IConstantPoolConstant.CONSTANT_InterfaceMethodref :
69
				constantPoolEntry = new ConstantPoolEntry();
70
				constantPoolEntry.reset();
71
				constantPoolEntry.setKind(kind);
72
				constantPoolEntry.reset();
73
				constantPoolEntry.setKind(kind);
60
				constantPoolEntry.setClassIndex(u2At(this.classFileBytes,  1, this.constantPoolOffset[index]));
74
				constantPoolEntry.setClassIndex(u2At(this.classFileBytes,  1, this.constantPoolOffset[index]));
61
				declaringClassIndex = u2At(this.classFileBytes,  1, this.constantPoolOffset[constantPoolEntry.getClassIndex()]);
75
				declaringClassIndex = u2At(this.classFileBytes,  1, this.constantPoolOffset[constantPoolEntry.getClassIndex()]);
62
				constantPoolEntry.setClassName(getUtf8ValueAt(declaringClassIndex));
76
				constantPoolEntry.setClassName(getUtf8ValueAt(declaringClassIndex));
Lines 67-91 Link Here
67
				constantPoolEntry.setMethodDescriptor(getUtf8ValueAt(methodDescriptorIndex));
81
				constantPoolEntry.setMethodDescriptor(getUtf8ValueAt(methodDescriptorIndex));
68
				break;
82
				break;
69
			case IConstantPoolConstant.CONSTANT_Float :
83
			case IConstantPoolConstant.CONSTANT_Float :
84
				constantPoolEntry = new ConstantPoolEntry();
85
				constantPoolEntry.reset();
86
				constantPoolEntry.setKind(kind);
87
				constantPoolEntry.reset();
88
				constantPoolEntry.setKind(kind);
70
				constantPoolEntry.setFloatValue(floatAt(this.classFileBytes, 1, this.constantPoolOffset[index]));
89
				constantPoolEntry.setFloatValue(floatAt(this.classFileBytes, 1, this.constantPoolOffset[index]));
71
				break;
90
				break;
72
			case IConstantPoolConstant.CONSTANT_Integer :
91
			case IConstantPoolConstant.CONSTANT_Integer :
92
				constantPoolEntry = new ConstantPoolEntry();
93
				constantPoolEntry.reset();
94
				constantPoolEntry.setKind(kind);
73
				constantPoolEntry.setIntegerValue(i4At(this.classFileBytes, 1, this.constantPoolOffset[index]));
95
				constantPoolEntry.setIntegerValue(i4At(this.classFileBytes, 1, this.constantPoolOffset[index]));
74
				break;
96
				break;
75
			case IConstantPoolConstant.CONSTANT_Long :
97
			case IConstantPoolConstant.CONSTANT_Long :
98
				constantPoolEntry = new ConstantPoolEntry();
99
				constantPoolEntry.reset();
100
				constantPoolEntry.setKind(kind);
76
				constantPoolEntry.setLongValue(i8At(this.classFileBytes, 1, this.constantPoolOffset[index]));
101
				constantPoolEntry.setLongValue(i8At(this.classFileBytes, 1, this.constantPoolOffset[index]));
77
				break;
102
				break;
78
			case IConstantPoolConstant.CONSTANT_NameAndType :
103
			case IConstantPoolConstant.CONSTANT_NameAndType :
104
				constantPoolEntry = new ConstantPoolEntry();
105
				constantPoolEntry.reset();
106
				constantPoolEntry.setKind(kind);
79
				constantPoolEntry.setNameAndTypeNameIndex(u2At(this.classFileBytes,  1, this.constantPoolOffset[index]));
107
				constantPoolEntry.setNameAndTypeNameIndex(u2At(this.classFileBytes,  1, this.constantPoolOffset[index]));
80
				constantPoolEntry.setNameAndTypeDescriptorIndex(u2At(this.classFileBytes,  3, this.constantPoolOffset[index]));
108
				constantPoolEntry.setNameAndTypeDescriptorIndex(u2At(this.classFileBytes,  3, this.constantPoolOffset[index]));
81
				break;
109
				break;
82
			case IConstantPoolConstant.CONSTANT_String :
110
			case IConstantPoolConstant.CONSTANT_String :
111
				constantPoolEntry = new ConstantPoolEntry();
112
				constantPoolEntry.reset();
113
				constantPoolEntry.setKind(kind);
83
				constantPoolEntry.setStringIndex(u2At(this.classFileBytes,  1, this.constantPoolOffset[index]));
114
				constantPoolEntry.setStringIndex(u2At(this.classFileBytes,  1, this.constantPoolOffset[index]));
84
				constantPoolEntry.setStringValue(getUtf8ValueAt(constantPoolEntry.getStringIndex()));
115
				constantPoolEntry.setStringValue(getUtf8ValueAt(constantPoolEntry.getStringIndex()));
85
				break;
116
				break;
86
			case IConstantPoolConstant.CONSTANT_Utf8 :
117
			case IConstantPoolConstant.CONSTANT_Utf8 :
118
				constantPoolEntry = new ConstantPoolEntry();
119
				constantPoolEntry.reset();
120
				constantPoolEntry.setKind(kind);
87
				constantPoolEntry.setUtf8Length(u2At(this.classFileBytes,  1, this.constantPoolOffset[index]));
121
				constantPoolEntry.setUtf8Length(u2At(this.classFileBytes,  1, this.constantPoolOffset[index]));
88
				constantPoolEntry.setUtf8Value(getUtf8ValueAt(index));
122
				constantPoolEntry.setUtf8Value(getUtf8ValueAt(index));
123
				break;
124
			case IConstantPoolConstant.CONSTANT_MethodHandle :
125
				ConstantPoolEntry2 constantPoolEntry2 = new ConstantPoolEntry2();
126
				constantPoolEntry2.reset();
127
				constantPoolEntry2.setKind(kind);
128
				constantPoolEntry2.setReferenceKind(u1At(this.classFileBytes,  1, this.constantPoolOffset[index]));
129
				constantPoolEntry2.setReferenceIndex(u2At(this.classFileBytes,  2, this.constantPoolOffset[index]));
130
				constantPoolEntry = constantPoolEntry2;
131
				break;
132
			case IConstantPoolConstant.CONSTANT_MethodType :
133
				constantPoolEntry2 = new ConstantPoolEntry2();
134
				constantPoolEntry2.reset();
135
				constantPoolEntry2.setKind(kind);
136
				methodDescriptorIndex = u2At(this.classFileBytes,  1, this.constantPoolOffset[index]);
137
				constantPoolEntry2.setDescriptorIndex(methodDescriptorIndex);
138
				constantPoolEntry2.setMethodDescriptor(getUtf8ValueAt(methodDescriptorIndex));
139
				constantPoolEntry = constantPoolEntry2;
140
				break;
141
			case IConstantPoolConstant.CONSTANT_InvokeDynamic :
142
				constantPoolEntry2 = new ConstantPoolEntry2();
143
				constantPoolEntry2.reset();
144
				constantPoolEntry2.setKind(kind);
145
				constantPoolEntry2.setBootstrapMethodAttributeIndex(u2At(this.classFileBytes,  1, this.constantPoolOffset[index]));
146
				int nameAndTypeIndex = u2At(this.classFileBytes,  3, this.constantPoolOffset[index]);
147
				constantPoolEntry2.setNameAndTypeIndex(nameAndTypeIndex);
148
				methodNameIndex = u2At(this.classFileBytes,  1, this.constantPoolOffset[nameAndTypeIndex]);
149
				methodDescriptorIndex = u2At(this.classFileBytes,  3, this.constantPoolOffset[nameAndTypeIndex]);
150
				constantPoolEntry2.setMethodName(getUtf8ValueAt(methodNameIndex));
151
				constantPoolEntry2.setMethodDescriptor(getUtf8ValueAt(methodDescriptorIndex));
152
				constantPoolEntry = constantPoolEntry2;
153
				break;
89
		}
154
		}
90
		return constantPoolEntry;
155
		return constantPoolEntry;
91
	}
156
	}
(-)a/org.eclipse.jdt.core/model/org/eclipse/jdt/internal/core/util/ConstantPoolEntry.java (-1 / +2 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 341-346 Link Here
341
341
342
	/**
342
	/**
343
	 * Sets the methodDescriptor.
343
	 * Sets the methodDescriptor.
344
	 *
344
	 * @param methodDescriptor The methodDescriptor to set
345
	 * @param methodDescriptor The methodDescriptor to set
345
	 */
346
	 */
346
	public void setMethodDescriptor(char[] methodDescriptor) {
347
	public void setMethodDescriptor(char[] methodDescriptor) {
(-)a/org.eclipse.jdt.core/model/org/eclipse/jdt/internal/core/util/ConstantPoolEntry2.java (+66 lines)
Added Link Here
1
/*******************************************************************************
2
 * Copyright (c) 2000, 2011 IBM Corporation and others.
3
 * All rights reserved. This program and the accompanying materials
4
 * are made available under the terms of the Eclipse Public License v1.0
5
 * which accompanies this distribution, and is available at
6
 * http://www.eclipse.org/legal/epl-v10.html
7
 *
8
 * Contributors:
9
 *     IBM Corporation - initial API and implementation
10
 *******************************************************************************/
11
package org.eclipse.jdt.internal.core.util;
12
13
import org.eclipse.jdt.core.util.IConstantPoolEntry2;
14
15
/**
16
 * Default implementation of IConstantPoolEntry
17
 *
18
 * @since 2.0
19
 */
20
public class ConstantPoolEntry2 extends ConstantPoolEntry implements IConstantPoolEntry2 {
21
	
22
	private int descriptorIndex;
23
	private int referenceKind;
24
	private int referenceIndex;
25
	private int bootstrapMethodAttributeIndex;
26
	
27
	public int getDescriptorIndex() {
28
		return this.descriptorIndex;
29
	}
30
31
	public int getReferenceKind() {
32
		return this.referenceKind;
33
	}
34
35
	public int getReferenceIndex() {
36
		return this.referenceIndex;
37
	}
38
39
	public int getBootstrapMethodAttributeIndex() {
40
		return this.bootstrapMethodAttributeIndex;
41
	}
42
43
	public void setDescriptorIndex(int descriptorIndex) {
44
		this.descriptorIndex = descriptorIndex;
45
	}
46
47
	public void setReferenceKind(int referenceKind) {
48
		this.referenceKind = referenceKind;
49
	}
50
51
	public void setReferenceIndex(int referenceIndex) {
52
		this.referenceIndex = referenceIndex;
53
	}
54
55
	public void setBootstrapMethodAttributeIndex(int bootstrapMethodAttributeIndex) {
56
		this.bootstrapMethodAttributeIndex = bootstrapMethodAttributeIndex;
57
	}
58
	
59
	public void reset() {
60
		super.reset();
61
		this.descriptorIndex = 0;
62
		this.referenceKind = 0;
63
		this.referenceIndex = 0;
64
		this.bootstrapMethodAttributeIndex = 0;
65
	}
66
}
(-)a/org.eclipse.jdt.core/model/org/eclipse/jdt/internal/core/util/DefaultBytecodeVisitor.java (-2 / +27 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 17-22 Link Here
17
import org.eclipse.jdt.core.util.ICodeAttribute;
17
import org.eclipse.jdt.core.util.ICodeAttribute;
18
import org.eclipse.jdt.core.util.IConstantPoolConstant;
18
import org.eclipse.jdt.core.util.IConstantPoolConstant;
19
import org.eclipse.jdt.core.util.IConstantPoolEntry;
19
import org.eclipse.jdt.core.util.IConstantPoolEntry;
20
import org.eclipse.jdt.core.util.IConstantPoolEntry2;
20
import org.eclipse.jdt.core.util.ILocalVariableAttribute;
21
import org.eclipse.jdt.core.util.ILocalVariableAttribute;
21
import org.eclipse.jdt.core.util.ILocalVariableTableEntry;
22
import org.eclipse.jdt.core.util.ILocalVariableTableEntry;
22
import org.eclipse.jdt.core.util.OpcodeStringValues;
23
import org.eclipse.jdt.core.util.OpcodeStringValues;
Lines 1491-1497 Link Here
1491
		writeNewLine();
1492
		writeNewLine();
1492
	}
1493
	}
1493
	/**
1494
	/**
1494
	 * @see IBytecodeVisitor#_invokedynamic(int, int, IConstantPoolEntry, IConstantPoolEntry)
1495
	 * @see IBytecodeVisitor#_invokedynamic(int, int, IConstantPoolEntry)
1495
	 */
1496
	 */
1496
	public void _invokedynamic(
1497
	public void _invokedynamic(
1497
		int pc,
1498
		int pc,
Lines 1513-1518 Link Here
1513
		writeNewLine();
1514
		writeNewLine();
1514
	}
1515
	}
1515
	/**
1516
	/**
1517
	 * @see IBytecodeVisitor#_invokedynamic(int, int, IConstantPoolEntry)
1518
	 */
1519
	public void _invokedynamic(
1520
		int pc,
1521
		int index,
1522
		IConstantPoolEntry invokeDynamicEntry) {
1523
1524
		dumpPcNumber(pc);
1525
		IConstantPoolEntry2 entry = (IConstantPoolEntry2) invokeDynamicEntry;
1526
		this.buffer.append(Messages.bind(Messages.classformat_invokedynamic,
1527
			new String[] {
1528
				OpcodeStringValues.BYTECODE_NAMES[IOpcodeMnemonics.INVOKEDYNAMIC],
1529
				Integer.toString(index),
1530
				Integer.toString(entry.getBootstrapMethodAttributeIndex()),
1531
				Util.toString(
1532
					null,
1533
					entry.getMethodName(),
1534
					entry.getMethodDescriptor(),
1535
					true,
1536
					isCompact())
1537
			}));
1538
		writeNewLine();
1539
	}
1540
	/**
1516
	 * @see IBytecodeVisitor#_invokeinterface(int, int, byte, IConstantPoolEntry)
1541
	 * @see IBytecodeVisitor#_invokeinterface(int, int, byte, IConstantPoolEntry)
1517
	 */
1542
	 */
1518
	public void _invokeinterface(
1543
	public void _invokeinterface(
(-)a/org.eclipse.jdt.core/model/org/eclipse/jdt/internal/core/util/Disassembler.java (-16 / +135 lines)
Lines 741-747 Link Here
741
		final int classNameLength = className.length;
741
		final int classNameLength = className.length;
742
		final int accessFlags = classFileReader.getAccessFlags();
742
		final int accessFlags = classFileReader.getAccessFlags();
743
		final boolean isEnum = (accessFlags & IModifierConstants.ACC_ENUM) != 0;
743
		final boolean isEnum = (accessFlags & IModifierConstants.ACC_ENUM) != 0;
744
744
	
745
		StringBuffer buffer = new StringBuffer();
745
		StringBuffer buffer = new StringBuffer();
746
		ISourceAttribute sourceAttribute = classFileReader.getSourceFileAttribute();
746
		ISourceAttribute sourceAttribute = classFileReader.getSourceFileAttribute();
747
		IClassFileAttribute classFileAttribute = Util.getAttribute(classFileReader, IAttributeNamesConstants.SIGNATURE);
747
		IClassFileAttribute classFileAttribute = Util.getAttribute(classFileReader, IAttributeNamesConstants.SIGNATURE);
Lines 788-794 Link Here
788
			}
788
			}
789
		}
789
		}
790
		final int lastDotIndexInClassName = CharOperation.lastIndexOf('.', className);
790
		final int lastDotIndexInClassName = CharOperation.lastIndexOf('.', className);
791
791
	
792
		if (checkMode(mode, WORKING_COPY) && lastDotIndexInClassName != -1) {
792
		if (checkMode(mode, WORKING_COPY) && lastDotIndexInClassName != -1) {
793
			// we print a package declaration
793
			// we print a package declaration
794
			buffer.append("package ");//$NON-NLS-1$
794
			buffer.append("package ");//$NON-NLS-1$
Lines 796-806 Link Here
796
			buffer.append(';');
796
			buffer.append(';');
797
			writeNewLine(buffer, lineSeparator, 0);
797
			writeNewLine(buffer, lineSeparator, 0);
798
		}
798
		}
799
799
	
800
		IInnerClassesAttribute innerClassesAttribute = classFileReader.getInnerClassesAttribute();
800
		IInnerClassesAttribute innerClassesAttribute = classFileReader.getInnerClassesAttribute();
801
		IClassFileAttribute runtimeVisibleAnnotationsAttribute = Util.getAttribute(classFileReader, IAttributeNamesConstants.RUNTIME_VISIBLE_ANNOTATIONS);
801
		IClassFileAttribute runtimeVisibleAnnotationsAttribute = Util.getAttribute(classFileReader, IAttributeNamesConstants.RUNTIME_VISIBLE_ANNOTATIONS);
802
		IClassFileAttribute runtimeInvisibleAnnotationsAttribute = Util.getAttribute(classFileReader, IAttributeNamesConstants.RUNTIME_INVISIBLE_ANNOTATIONS);
802
		IClassFileAttribute runtimeInvisibleAnnotationsAttribute = Util.getAttribute(classFileReader, IAttributeNamesConstants.RUNTIME_INVISIBLE_ANNOTATIONS);
803
803
	
804
		IClassFileAttribute bootstrapMethods = Util.getAttribute(classFileReader, IAttributeNamesConstants.BOOTSTRAP_METHODS);
805
	
804
		if (checkMode(mode, DETAILED)) {
806
		if (checkMode(mode, DETAILED)) {
805
			// disassemble compact version of annotations
807
			// disassemble compact version of annotations
806
			if (runtimeInvisibleAnnotationsAttribute != null) {
808
			if (runtimeInvisibleAnnotationsAttribute != null) {
Lines 838-844 Link Here
838
				}
840
				}
839
			}
841
			}
840
		}
842
		}
841
843
	
842
		final boolean isAnnotation = (accessFlags & IModifierConstants.ACC_ANNOTATION) != 0;
844
		final boolean isAnnotation = (accessFlags & IModifierConstants.ACC_ANNOTATION) != 0;
843
		boolean isInterface = false;
845
		boolean isInterface = false;
844
		if (isEnum) {
846
		if (isEnum) {
Lines 852-858 Link Here
852
			buffer.append("interface "); //$NON-NLS-1$
854
			buffer.append("interface "); //$NON-NLS-1$
853
			isInterface = true;
855
			isInterface = true;
854
		}
856
		}
855
857
	
856
		if (checkMode(mode, WORKING_COPY)) {
858
		if (checkMode(mode, WORKING_COPY)) {
857
			// we print the simple class name
859
			// we print the simple class name
858
			final int start = lastDotIndexInClassName + 1;
860
			final int start = lastDotIndexInClassName + 1;
Lines 864-870 Link Here
864
		} else {
866
		} else {
865
			buffer.append(className);
867
			buffer.append(className);
866
		}
868
		}
867
869
	
868
		char[] superclassName = classFileReader.getSuperclassName();
870
		char[] superclassName = classFileReader.getSuperclassName();
869
		if (superclassName != null) {
871
		if (superclassName != null) {
870
			CharOperation.replace(superclassName, '/', '.');
872
			CharOperation.replace(superclassName, '/', '.');
Lines 917-930 Link Here
917
			if (signatureAttribute != null) {
919
			if (signatureAttribute != null) {
918
				remainingAttributesLength--;
920
				remainingAttributesLength--;
919
			}
921
			}
920
			if (innerClassesAttribute != null || enclosingMethodAttribute != null || remainingAttributesLength != 0) {
922
			if (bootstrapMethods != null) {
921
				writeNewLine(buffer, lineSeparator, 0);
923
				remainingAttributesLength--;
924
			}
925
			if (innerClassesAttribute != null
926
					|| enclosingMethodAttribute != null
927
					|| bootstrapMethods != null
928
					|| remainingAttributesLength != 0) {
929
				// this test is to ensure we don't insert more than one line separator
930
				if (buffer.lastIndexOf(lineSeparator) != buffer.length() - lineSeparator.length()) {
931
					writeNewLine(buffer, lineSeparator, 0);
932
				}
922
			}
933
			}
923
			if (innerClassesAttribute != null) {
934
			if (innerClassesAttribute != null) {
924
				disassemble(innerClassesAttribute, buffer, lineSeparator, 1);
935
				disassemble(innerClassesAttribute, buffer, lineSeparator, 1);
925
			}
936
			}
926
			if (enclosingMethodAttribute != null) {
937
			if (enclosingMethodAttribute != null) {
927
				disassemble(enclosingMethodAttribute, buffer, lineSeparator, 0);
938
				disassemble(enclosingMethodAttribute, buffer, lineSeparator, 0);
939
			}
940
			if (bootstrapMethods != null) {
941
				disassemble((IBootstrapMethodsAttribute) bootstrapMethods, buffer, lineSeparator, 0);
928
			}
942
			}
929
			if (checkMode(mode, SYSTEM)) {
943
			if (checkMode(mode, SYSTEM)) {
930
				if (runtimeVisibleAnnotationsAttribute != null) {
944
				if (runtimeVisibleAnnotationsAttribute != null) {
Lines 937-949 Link Here
937
					for (int i = 0; i < length; i++) {
951
					for (int i = 0; i < length; i++) {
938
						IClassFileAttribute attribute = attributes[i];
952
						IClassFileAttribute attribute = attributes[i];
939
						if (attribute != innerClassesAttribute
953
						if (attribute != innerClassesAttribute
940
							&& attribute != sourceAttribute
954
								&& attribute != sourceAttribute
941
							&& attribute != signatureAttribute
955
								&& attribute != signatureAttribute
942
							&& attribute != enclosingMethodAttribute
956
								&& attribute != enclosingMethodAttribute
943
							&& attribute != runtimeInvisibleAnnotationsAttribute
957
								&& attribute != runtimeInvisibleAnnotationsAttribute
944
							&& attribute != runtimeVisibleAnnotationsAttribute
958
								&& attribute != runtimeVisibleAnnotationsAttribute
945
							&& !CharOperation.equals(attribute.getAttributeName(), IAttributeNamesConstants.DEPRECATED)
959
								&& !CharOperation.equals(attribute.getAttributeName(), IAttributeNamesConstants.DEPRECATED)
946
							&& !CharOperation.equals(attribute.getAttributeName(), IAttributeNamesConstants.SYNTHETIC)) {
960
								&& !CharOperation.equals(attribute.getAttributeName(), IAttributeNamesConstants.SYNTHETIC)
961
								&& attribute != bootstrapMethods) {
947
							disassemble(attribute, buffer, lineSeparator, 0, mode);
962
							disassemble(attribute, buffer, lineSeparator, 0, mode);
948
						}
963
						}
949
					}
964
					}
Lines 1408-1415 Link Here
1408
								Integer.toString(i),
1423
								Integer.toString(i),
1409
								decodeStringValue(new String(constantPoolEntry.getUtf8Value()))}));
1424
								decodeStringValue(new String(constantPoolEntry.getUtf8Value()))}));
1410
					break;
1425
					break;
1426
				case IConstantPoolConstant.CONSTANT_MethodHandle :
1427
					IConstantPoolEntry2 entry2 = (IConstantPoolEntry2) constantPoolEntry;
1428
					buffer.append(
1429
							Messages.bind(Messages.disassembler_constantpool_methodhandle,
1430
								new String[] {
1431
									Integer.toString(i),
1432
									getReferenceKind(entry2.getReferenceKind()),
1433
									Integer.toString(entry2.getReferenceIndex()),
1434
								}));
1435
					break;
1436
				case IConstantPoolConstant.CONSTANT_MethodType :
1437
					entry2 = (IConstantPoolEntry2) constantPoolEntry;
1438
					buffer.append(
1439
							Messages.bind(Messages.disassembler_constantpool_methodtype,
1440
								new String[] {
1441
									Integer.toString(i),
1442
									Integer.toString(entry2.getDescriptorIndex()),
1443
									String.valueOf(entry2.getMethodDescriptor()),
1444
								}));
1445
					break;
1446
				case IConstantPoolConstant.CONSTANT_InvokeDynamic :
1447
					entry2 = (IConstantPoolEntry2) constantPoolEntry;
1448
					buffer.append(
1449
						Messages.bind(Messages.disassembler_constantpool_invokedynamic,
1450
							new String[] {
1451
								Integer.toString(i),
1452
								Integer.toString(entry2.getBootstrapMethodAttributeIndex()),
1453
								Integer.toString(entry2.getNameAndTypeIndex()),
1454
								new String(constantPoolEntry.getMethodName()),
1455
								new String(constantPoolEntry.getMethodDescriptor())
1456
							}));
1411
			}
1457
			}
1412
		}
1458
		}
1459
	}
1460
	
1461
	private String getReferenceKind(int referenceKind) {
1462
		String message = null;
1463
		switch(referenceKind) {
1464
			case IConstantPoolConstant.METHOD_TYPE_REF_GetField :
1465
				message = Messages.disassembler_method_type_ref_getfield;
1466
				break;
1467
			case IConstantPoolConstant.METHOD_TYPE_REF_GetStatic :
1468
				message = Messages.disassembler_method_type_ref_getstatic;
1469
				break;
1470
			case IConstantPoolConstant.METHOD_TYPE_REF_PutField :
1471
				message = Messages.disassembler_method_type_ref_putfield;
1472
				break;
1473
			case IConstantPoolConstant.METHOD_TYPE_REF_PutStatic :
1474
				message = Messages.disassembler_method_type_ref_putstatic;
1475
				break;
1476
			case IConstantPoolConstant.METHOD_TYPE_REF_InvokeInterface :
1477
				message = Messages.disassembler_method_type_ref_invokeinterface;
1478
				break;
1479
			case IConstantPoolConstant.METHOD_TYPE_REF_InvokeSpecial :
1480
				message = Messages.disassembler_method_type_ref_invokespecial;
1481
				break;
1482
			case IConstantPoolConstant.METHOD_TYPE_REF_InvokeStatic :
1483
				message = Messages.disassembler_method_type_ref_invokestatic;
1484
				break;
1485
			case IConstantPoolConstant.METHOD_TYPE_REF_InvokeVirtual :
1486
				message = Messages.disassembler_method_type_ref_invokevirtual;
1487
				break;
1488
			default :
1489
				message = Messages.disassembler_method_type_ref_newinvokespecial;
1490
		}
1491
		return Messages.bind(message, new String[] { Integer.toString(referenceKind) });
1413
	}
1492
	}
1414
1493
1415
	private void disassemble(IEnclosingMethodAttribute enclosingMethodAttribute, StringBuffer buffer, String lineSeparator, int tabNumber) {
1494
	private void disassemble(IEnclosingMethodAttribute enclosingMethodAttribute, StringBuffer buffer, String lineSeparator, int tabNumber) {
Lines 1669-1674 Link Here
1669
		}
1748
		}
1670
	}
1749
	}
1671
1750
1751
	private void disassemble(IBootstrapMethodsAttribute bootstrapMethodsAttribute, StringBuffer buffer, String lineSeparator, int tabNumber) {
1752
		writeNewLine(buffer, lineSeparator, tabNumber);
1753
		buffer.append(Messages.disassembler_bootstrapmethodattributesheader);
1754
		writeNewLine(buffer, lineSeparator, tabNumber + 1);
1755
		IBootstrapMethodsEntry[] entries = bootstrapMethodsAttribute.getBootstrapMethods();
1756
		int length = entries.length;
1757
		for (int i = 0; i < length; i++) {
1758
			if (i != 0) {
1759
				buffer.append(Messages.disassembler_comma);
1760
				writeNewLine(buffer, lineSeparator, tabNumber + 1);
1761
			}
1762
			IBootstrapMethodsEntry entry = entries[i];
1763
			buffer.append(
1764
				Messages.bind(
1765
					Messages.disassembler_bootstrapmethodentry,
1766
					new String[] {
1767
						Integer.toString(i),
1768
						Integer.toString(entry.getBootstrapMethodReference()),
1769
						getArguments(entry.getBootstrapArguments())
1770
					}));
1771
		}
1772
	}
1773
1774
	private String getArguments(int[] arguments) {
1775
		StringBuffer buffer = new StringBuffer();
1776
		buffer.append('{');
1777
		for (int i = 0, max = arguments.length; i < max; i++) {
1778
			if (i != 0) {
1779
				buffer.append(Messages.disassembler_comma);
1780
			}
1781
			buffer.append(
1782
				Messages.bind(
1783
					Messages.disassembler_bootstrapmethodentry_argument,
1784
					new String[] {
1785
						Integer.toString(arguments[i]),
1786
					}));
1787
		}
1788
		buffer.append('}');
1789
		return String.valueOf(buffer);
1790
	}
1672
	private void disassemble(int index, IParameterAnnotation parameterAnnotation, StringBuffer buffer, String lineSeparator, int tabNumber, int mode) {
1791
	private void disassemble(int index, IParameterAnnotation parameterAnnotation, StringBuffer buffer, String lineSeparator, int tabNumber, int mode) {
1673
		IAnnotation[] annotations = parameterAnnotation.getAnnotations();
1792
		IAnnotation[] annotations = parameterAnnotation.getAnnotations();
1674
		writeNewLine(buffer, lineSeparator, tabNumber + 1);
1793
		writeNewLine(buffer, lineSeparator, tabNumber + 1);
(-)a/org.eclipse.jdt.core/model/org/eclipse/jdt/internal/core/util/Messages.java (+16 lines)
Lines 259-264 Link Here
259
	public static String disassembler_inner_accessflags;
259
	public static String disassembler_inner_accessflags;
260
	public static String disassembler_genericattributeheader;
260
	public static String disassembler_genericattributeheader;
261
	public static String disassembler_signatureattributeheader;
261
	public static String disassembler_signatureattributeheader;
262
	public static String disassembler_bootstrapmethodattributesheader;
263
	public static String disassembler_bootstrapmethodentry;
264
	public static String disassembler_bootstrapmethodentry_argument;
262
	public static String disassembler_indentation;
265
	public static String disassembler_indentation;
263
	public static String disassembler_constantpoolindex;
266
	public static String disassembler_constantpoolindex;
264
	public static String disassembler_space;
267
	public static String disassembler_space;
Lines 278-283 Link Here
278
	public static String disassembler_constantpool_methodref;
281
	public static String disassembler_constantpool_methodref;
279
	public static String disassembler_constantpool_name_and_type;
282
	public static String disassembler_constantpool_name_and_type;
280
	public static String disassembler_constantpool_utf8;
283
	public static String disassembler_constantpool_utf8;
284
	public static String disassembler_constantpool_methodhandle;
285
	public static String disassembler_constantpool_methodtype;
286
	public static String disassembler_constantpool_invokedynamic;
281
	public static String disassembler_annotationdefaultheader;
287
	public static String disassembler_annotationdefaultheader;
282
	public static String disassembler_annotationdefaultvalue;
288
	public static String disassembler_annotationdefaultvalue;
283
	public static String disassembler_annotationenumvalue;
289
	public static String disassembler_annotationenumvalue;
Lines 348-353 Link Here
348
	public static String disassembler_frame_same_frame;
354
	public static String disassembler_frame_same_frame;
349
	public static String disassembler_frame_same_locals_1_stack_item;
355
	public static String disassembler_frame_same_locals_1_stack_item;
350
	public static String code_assist_internal_error;
356
	public static String code_assist_internal_error;
357
	
358
	public static String disassembler_method_type_ref_getfield;
359
	public static String disassembler_method_type_ref_putfield;
360
	public static String disassembler_method_type_ref_getstatic;
361
	public static String disassembler_method_type_ref_putstatic;
362
	public static String disassembler_method_type_ref_invokestatic;
363
	public static String disassembler_method_type_ref_invokevirtual;
364
	public static String disassembler_method_type_ref_invokespecial;
365
	public static String disassembler_method_type_ref_invokeinterface;
366
	public static String disassembler_method_type_ref_newinvokespecial;
351
367
352
	static {
368
	static {
353
		NLS.initializeMessages(BUNDLE_NAME, Messages.class);
369
		NLS.initializeMessages(BUNDLE_NAME, Messages.class);
(-)a/org.eclipse.jdt.core/model/org/eclipse/jdt/internal/core/util/PublicScanner.java (-7 / +7 lines)
Lines 1817-1829 Link Here
1817
		this.currentPosition += (this.eofPosition - this.currentPosition);
1817
		this.currentPosition += (this.eofPosition - this.currentPosition);
1818
		throw new InvalidInputException(INVALID_UNICODE_ESCAPE);
1818
		throw new InvalidInputException(INVALID_UNICODE_ESCAPE);
1819
	}
1819
	}
1820
	if ((c1 = ScannerHelper.getNumericValue(this.source[this.currentPosition++])) > 15
1820
	if ((c1 = ScannerHelper.getHexadecimalValue(this.source[this.currentPosition++])) > 15
1821
    		|| c1 < 0
1821
    		|| c1 < 0
1822
    		|| (c2 = ScannerHelper.getNumericValue(this.source[this.currentPosition++])) > 15
1822
    		|| (c2 = ScannerHelper.getHexadecimalValue(this.source[this.currentPosition++])) > 15
1823
    		|| c2 < 0
1823
    		|| c2 < 0
1824
    		|| (c3 = ScannerHelper.getNumericValue(this.source[this.currentPosition++])) > 15
1824
    		|| (c3 = ScannerHelper.getHexadecimalValue(this.source[this.currentPosition++])) > 15
1825
    		|| c3 < 0
1825
    		|| c3 < 0
1826
    		|| (c4 = ScannerHelper.getNumericValue(this.source[this.currentPosition++])) > 15
1826
    		|| (c4 = ScannerHelper.getHexadecimalValue(this.source[this.currentPosition++])) > 15
1827
    		|| c4 < 0){
1827
    		|| c4 < 0){
1828
		throw new InvalidInputException(INVALID_UNICODE_ESCAPE);
1828
		throw new InvalidInputException(INVALID_UNICODE_ESCAPE);
1829
	}
1829
	}
Lines 2723-2740 Link Here
2723
			// OctalDigit OctalDigit
2723
			// OctalDigit OctalDigit
2724
			// ZeroToThree OctalDigit OctalDigit
2724
			// ZeroToThree OctalDigit OctalDigit
2725
2725
2726
			int number = ScannerHelper.getNumericValue(this.currentCharacter);
2726
			int number = ScannerHelper.getHexadecimalValue(this.currentCharacter);
2727
			if (number >= 0 && number <= 7) {
2727
			if (number >= 0 && number <= 7) {
2728
				boolean zeroToThreeNot = number > 3;
2728
				boolean zeroToThreeNot = number > 3;
2729
				if (ScannerHelper.isDigit(this.currentCharacter = this.source[this.currentPosition++])) {
2729
				if (ScannerHelper.isDigit(this.currentCharacter = this.source[this.currentPosition++])) {
2730
					int digit = ScannerHelper.getNumericValue(this.currentCharacter);
2730
					int digit = ScannerHelper.getHexadecimalValue(this.currentCharacter);
2731
					if (digit >= 0 && digit <= 7) {
2731
					if (digit >= 0 && digit <= 7) {
2732
						number = (number * 8) + digit;
2732
						number = (number * 8) + digit;
2733
						if (ScannerHelper.isDigit(this.currentCharacter = this.source[this.currentPosition++])) {
2733
						if (ScannerHelper.isDigit(this.currentCharacter = this.source[this.currentPosition++])) {
2734
							if (zeroToThreeNot) {// has read \NotZeroToThree OctalDigit Digit --> ignore last character
2734
							if (zeroToThreeNot) {// has read \NotZeroToThree OctalDigit Digit --> ignore last character
2735
								this.currentPosition--;
2735
								this.currentPosition--;
2736
							} else {
2736
							} else {
2737
								digit = ScannerHelper.getNumericValue(this.currentCharacter);
2737
								digit = ScannerHelper.getHexadecimalValue(this.currentCharacter);
2738
								if (digit >= 0 && digit <= 7){ // has read \ZeroToThree OctalDigit OctalDigit
2738
								if (digit >= 0 && digit <= 7){ // has read \ZeroToThree OctalDigit OctalDigit
2739
									number = (number * 8) + digit;
2739
									number = (number * 8) + digit;
2740
								} else {// has read \ZeroToThree OctalDigit NonOctalDigit --> ignore last character
2740
								} else {// has read \ZeroToThree OctalDigit NonOctalDigit --> ignore last character
(-)a/org.eclipse.jdt.core/model/org/eclipse/jdt/internal/core/util/messages.properties (-1 / +16 lines)
Lines 285-290 Link Here
285
disassembler_stackmaptableattributeheader = Stack map table: number of frames {0}
285
disassembler_stackmaptableattributeheader = Stack map table: number of frames {0}
286
disassembler_stackmapattributeheader =  Stack map : number of frames {0}
286
disassembler_stackmapattributeheader =  Stack map : number of frames {0}
287
disassembler_signatureattributeheader = // Signature: {0}
287
disassembler_signatureattributeheader = // Signature: {0}
288
disassembler_bootstrapmethodattributesheader = Bootstrap methods:
289
disassembler_bootstrapmethodentry = {0} : # {1} arguments: {2}
290
disassembler_bootstrapmethodentry_argument = #{0}
288
disassembler_indentation = \  
291
disassembler_indentation = \  
289
disassembler_constantpoolindex =\ #
292
disassembler_constantpoolindex =\ #
290
disassembler_space = \ 
293
disassembler_space = \ 
Lines 304-309 Link Here
304
disassembler_constantpool_methodref = constant #{0} method_ref: #{1}.#{2} {3}.{4} {5}
307
disassembler_constantpool_methodref = constant #{0} method_ref: #{1}.#{2} {3}.{4} {5}
305
disassembler_constantpool_name_and_type = constant #{0} name_and_type: #{1}.#{2} {3} {4}
308
disassembler_constantpool_name_and_type = constant #{0} name_and_type: #{1}.#{2} {3} {4}
306
disassembler_constantpool_utf8 = constant #{0} utf8: "{1}"
309
disassembler_constantpool_utf8 = constant #{0} utf8: "{1}"
310
disassembler_constantpool_methodhandle = constant #{0} method handle: {1} #{2} 
311
disassembler_constantpool_methodtype = constant #{0} method type: #{1} {2}
312
disassembler_constantpool_invokedynamic = constant #{0} invoke dynamic: #{1} #{2} {3} {4}
307
disassembler_annotationdefaultheader = Annotation Default:\ 
313
disassembler_annotationdefaultheader = Annotation Default:\ 
308
disassembler_annotationdefaultvalue= {0} (constant type)
314
disassembler_annotationdefaultvalue= {0} (constant type)
309
disassembler_annotationenumvalue = {2}.{3}(enum type #{0}.#{1})
315
disassembler_annotationenumvalue = {2}.{3}(enum type #{0}.#{1})
Lines 323-328 Link Here
323
disassembler_frame_chop=[pc: {0}, chop {1} local(s)]
329
disassembler_frame_chop=[pc: {0}, chop {1} local(s)]
324
disassembler_frame_same_frame_extended=[pc: {0}, same_extended]
330
disassembler_frame_same_frame_extended=[pc: {0}, same_extended]
325
disassembler_frame_append=[pc: {0}, append: {1}]
331
disassembler_frame_append=[pc: {0}, append: {1}]
332
disassembler_method_type_ref_getfield = getfield ({0})
333
disassembler_method_type_ref_putfield = putfield ({0})
334
disassembler_method_type_ref_getstatic = getstatic ({0})
335
disassembler_method_type_ref_putstatic = putstatic ({0})
336
disassembler_method_type_ref_invokestatic = invokestatic ({0})
337
disassembler_method_type_ref_invokevirtual = invokevirtual ({0})
338
disassembler_method_type_ref_invokeinterface = invokeinterface ({0})
339
disassembler_method_type_ref_invokespecial = invokespecial ({0})
340
disassembler_method_type_ref_newinvokespecial = newinvokespecial ({0})
326
# {0} = offset delta
341
# {0} = offset delta
327
# {1} = number of locals
342
# {1} = number of locals
328
# {2} = locals
343
# {2} = locals
Lines 358-364 Link Here
358
classformat_iinc = {0} {1} {2}{3}
373
classformat_iinc = {0} {1} {2}{3}
359
classformat_invokespecial ={0} {2} [{1}]
374
classformat_invokespecial ={0} {2} [{1}]
360
classformat_invokeinterface ={0} {3} [{1}] [nargs: {2}]
375
classformat_invokeinterface ={0} {3} [{1}] [nargs: {2}]
361
classformat_invokedynamic={0} {2} [{1}]
376
classformat_invokedynamic={0} {2} {3} [{1}]
362
classformat_invokestatic ={0} {2} [{1}]
377
classformat_invokestatic ={0} {2} [{1}]
363
classformat_invokevirtual ={0} {2} [{1}]
378
classformat_invokevirtual ={0} {2} [{1}]
364
classformat_getfield ={0} {2}.{3} : {4} [{1}]
379
classformat_getfield ={0} {2}.{3} : {4} [{1}]
(-)a/org.eclipse.jdt.core/plugin.xml (-1 / +17 lines)
Lines 1-7 Link Here
1
<?xml version="1.0" encoding="UTF-8"?>
1
<?xml version="1.0" encoding="UTF-8"?>
2
<?eclipse version="3.0"?>
2
<?eclipse version="3.0"?>
3
<!--
3
<!--
4
    Copyright (c) 2004, 2010 IBM Corporation and others.
4
    Copyright (c) 2004, 2011 IBM Corporation and others.
5
    All rights reserved. This program and the accompanying materials
5
    All rights reserved. This program and the accompanying materials
6
    are made available under the terms of the Eclipse Public License v1.0
6
    are made available under the terms of the Eclipse Public License v1.0
7
    which accompanies this distribution, and is available at
7
    which accompanies this distribution, and is available at
Lines 158-163 Link Here
158
		class="org.eclipse.jdt.core.CheckDebugAttributes"
158
		class="org.eclipse.jdt.core.CheckDebugAttributes"
159
		library="jdtCompilerAdapter.jar">
159
		library="jdtCompilerAdapter.jar">
160
	</antTask>
160
	</antTask>
161
	<antTask
162
		name="eclipse.buildJarIndex"
163
		class="org.eclipse.jdt.core.BuildJarIndex"
164
		library="jdtCompilerAdapter.jar">
165
	</antTask>
161
</extension>
166
</extension>
162
      
167
      
163
<!-- =================================================================================== -->
168
<!-- =================================================================================== -->
Lines 196-201 Link Here
196
</extension>
201
</extension>
197
202
198
<!-- =================================================================================== -->
203
<!-- =================================================================================== -->
204
<!-- Extension: Java Generate Indexer                                                    -->
205
<!-- =================================================================================== -->
206
<extension
207
      id="JavaIndexer"
208
      point="org.eclipse.core.runtime.applications">
209
   		<application>
210
      		<run class="org.eclipse.jdt.core.index.JavaIndexerApplication" />
211
   		</application>
212
</extension>
213
214
<!-- =================================================================================== -->
199
<!-- Extension: Java Content Types                                                       -->
215
<!-- Extension: Java Content Types                                                       -->
200
<!-- =================================================================================== -->
216
<!-- =================================================================================== -->
201
<extension point="org.eclipse.core.contenttype.contentTypes">
217
<extension point="org.eclipse.core.contenttype.contentTypes">
(-)a/org.eclipse.jdt.core/scripts/exportplugin.xml (-8 / +8 lines)
Lines 1-7 Link Here
1
<?xml version="1.0" encoding="UTF-8"?>
1
<?xml version="1.0" encoding="UTF-8"?>
2
2
3
<!--
3
<!--
4
    Copyright (c) 2007, 2011 IBM Corporation and others.
4
    Copyright (c) 2007, 2012 IBM Corporation and others.
5
    All rights reserved. This program and the accompanying materials
5
    All rights reserved. This program and the accompanying materials
6
    are made available under the terms of the Eclipse Public License v1.0
6
    are made available under the terms of the Eclipse Public License v1.0
7
    which accompanies this distribution, and is available at
7
    which accompanies this distribution, and is available at
Lines 12-37 Link Here
12
 -->
12
 -->
13
13
14
<!-- build script to create a plugin from ${plugin} -->
14
<!-- build script to create a plugin from ${plugin} -->
15
<project name="${plugin}" default="export plug-in [_3.8.0]" basedir="..">
15
<project name="${plugin}" default="export plug-in [_3.8.1]" basedir="..">
16
<target name="export plug-in [_3.8.0]">
16
<target name="export plug-in [_3.8.1]">
17
    <tstamp/>
17
    <tstamp/>
18
	<property name="qualifier" value="z${DSTAMP}-${TSTAMP}" />
18
	<property name="qualifier" value="z${DSTAMP}-${TSTAMP}" />
19
	<antcall target="zz_internal_export">
19
	<antcall target="zz_internal_export">
20
		<param name="jdt_core_version" value="3.8.0"/>
20
		<param name="jdt_core_version" value="3.8.1"/>
21
	</antcall>
21
	</antcall>
22
</target>
22
</target>
23
<target name="export plug-in [_3.8.0.qualifier] (binary only)">
23
<target name="export plug-in [_3.8.1.qualifier] (binary only)">
24
    <tstamp/>
24
    <tstamp/>
25
	<property name="qualifier" value="z${DSTAMP}-${TSTAMP}" />
25
	<property name="qualifier" value="z${DSTAMP}-${TSTAMP}" />
26
	<antcall target="zz_internal_export_binary_only">
26
	<antcall target="zz_internal_export_binary_only">
27
		<param name="jdt_core_version" value="3.8.0.${qualifier}"/>
27
		<param name="jdt_core_version" value="3.8.1.${qualifier}"/>
28
	</antcall>
28
	</antcall>
29
</target>
29
</target>
30
<target name="export plug-in [_3.8.0.qualifier] (with sources)">
30
<target name="export plug-in [_3.8.1.qualifier] (with sources)">
31
    <tstamp/>
31
    <tstamp/>
32
	<property name="qualifier" value="z${DSTAMP}-${TSTAMP}" />
32
	<property name="qualifier" value="z${DSTAMP}-${TSTAMP}" />
33
	<antcall target="zz_internal_export">
33
	<antcall target="zz_internal_export">
34
		<param name="jdt_core_version" value="3.8.0.${qualifier}"/>
34
		<param name="jdt_core_version" value="3.8.1.${qualifier}"/>
35
	</antcall>
35
	</antcall>
36
</target>
36
</target>
37
37
(-)a/org.eclipse.jdt.core/search/org/eclipse/jdt/core/index/JavaIndexer.java (+42 lines)
Added Link Here
1
/*******************************************************************************
2
 * Copyright (c) 2011 IBM Corporation and others.
3
 * All rights reserved. This program and the accompanying materials
4
 * are made available under the terms of the Eclipse Public License v1.0
5
 * which accompanies this distribution, and is available at
6
 * http://www.eclipse.org/legal/epl-v10.html
7
 *
8
 * Contributors:
9
 *     IBM Corporation - initial API and implementation
10
 *******************************************************************************/
11
package org.eclipse.jdt.core.index;
12
13
import java.io.IOException;
14
15
import org.eclipse.jdt.core.search.SearchEngine;
16
import org.eclipse.jdt.internal.core.search.indexing.DefaultJavaIndexer;
17
18
/**
19
 * {@link JavaIndexer} provides functionality to generate index files which can be used by the JDT {@link SearchEngine}.
20
 * The generated index files can be used as a classpath attribute for the particular classpath entry.
21
 * 
22
 * <p> The search engine indexes all the elements referred in the classpath entries of the project into
23
 * index files. These index files are used to search the elements faster. Indexing for bigger jars could
24
 * take some time. To avoid this time, one can generate the index file and specify it when the jar is added
25
 * to the classpath of the project. </p>
26
 *
27
 * @since 3.8
28
 */
29
public final class JavaIndexer {
30
31
	/**
32
	 * Generates the index file for the specified jar.
33
	 * @param pathToJar The full path to the jar that needs to be indexed
34
	 * @param pathToIndexFile The full path to the index file that needs to be generated
35
	 * @throws IOException if the jar is not found or could not write into the index file
36
	 * @since 3.8
37
	 */
38
	public static void generateIndexForJar(String pathToJar, String pathToIndexFile) throws IOException {
39
		new DefaultJavaIndexer().generateIndexForJar(pathToJar, pathToIndexFile);
40
	}
41
42
}
(-)a/org.eclipse.jdt.core/search/org/eclipse/jdt/core/index/JavaIndexerApplication.java (+158 lines)
Added Link Here
1
/*******************************************************************************
2
 *  Copyright (c) 2011 IBM Corporation and others.
3
 *  All rights reserved. This program and the accompanying materials
4
 *  are made available under the terms of the Eclipse Public License v1.0
5
 *  which accompanies this distribution, and is available at
6
 *  http://www.eclipse.org/legal/epl-v10.html
7
 * 
8
 *  Contributors:
9
 *     IBM Corporation - initial API and implementation
10
 *******************************************************************************/
11
package org.eclipse.jdt.core.index;
12
13
import java.io.File;
14
import java.io.IOException;
15
import java.text.MessageFormat;
16
import java.util.ArrayList;
17
18
import org.eclipse.equinox.app.IApplication;
19
import org.eclipse.equinox.app.IApplicationContext;
20
import org.eclipse.osgi.util.NLS;
21
22
/**
23
 * Implements an Eclipse Application for {@link org.eclipse.jdt.core.index.JavaIndexer}.
24
 * 
25
 * <p>
26
 * On MacOS, when invoked using the Eclipse executable, the "user.dir" property is set to the folder in which the
27
 * eclipse.ini file is located. This makes it harder to use relative paths to point to the files to be jar'd or to
28
 * the index file that is generated.
29
 * </p>
30
 * 
31
 * 
32
 * @since 3.8
33
 * @noinstantiate This class is not intended to be instantiated by clients.
34
 * @noextend This class is not intended to be subclassed by clients.
35
 */
36
public class JavaIndexerApplication implements IApplication {
37
38
	private final static class Messages extends NLS {
39
		private static final String MESSAGES_NAME = "org.eclipse.jdt.core.index.messages";//$NON-NLS-1$
40
41
		public static String CommandLineProcessing;
42
		public static String CommandLineUsage;
43
		public static String CommandLineOnlyOneOutputError;
44
		public static String CommandLineOutputTakesArgs;
45
		public static String CommandLineOnlyOneJarError;
46
		public static String CommandLineJarNotSpecified;
47
		public static String CommandLineIndexFileNotSpecified;
48
		public static String CaughtException;
49
		public static String CommandLineJarFileNotExist;
50
51
		static {
52
			NLS.initializeMessages(MESSAGES_NAME, Messages.class);
53
		}
54
55
		public static String bind(String message) {
56
			return bind(message, null);
57
		}
58
59
		public static String bind(String message, Object binding) {
60
			return bind(message, new Object[] { binding });
61
		}
62
63
		public static String bind(String message, Object binding1, Object binding2) {
64
			return bind(message, new Object[] { binding1, binding2 });
65
		}
66
67
		public static String bind(String message, Object[] bindings) {
68
			return MessageFormat.format(message, bindings);
69
		}
70
	}
71
72
	private String jarToIndex;
73
	private String indexFile;
74
	private boolean verbose = false;
75
	private static final String PDE_LAUNCH = "-pdelaunch"; //$NON-NLS-1$
76
	private static final String ARG_HELP = "-help"; //$NON-NLS-1$
77
	private static final String ARG_VERBOSE = "-verbose"; //$NON-NLS-1$
78
	private static final String ARG_OUTPUT = "-output"; //$NON-NLS-1$
79
80
	private void displayHelp() {
81
		System.out.println(Messages.bind(Messages.CommandLineUsage));
82
	}
83
84
	private void displayError(String message) {
85
		System.out.println(message);
86
		System.out.println();
87
		displayHelp();
88
	}
89
90
	private boolean processCommandLine(String[] argsArray) {
91
		ArrayList args = new ArrayList();
92
		for (int i = 0, max = argsArray.length; i < max; i++) {
93
			args.add(argsArray[i]);
94
		}
95
		int index = 0;
96
		final int argCount = argsArray.length;
97
98
		loop: while (index < argCount) {
99
			String currentArg = argsArray[index++];
100
			if (PDE_LAUNCH.equals(currentArg)) {
101
				continue loop;
102
			} else if (ARG_HELP.equals(currentArg)) {
103
				displayHelp();
104
				return false;
105
			} else if (ARG_VERBOSE.equals(currentArg)) {
106
				this.verbose = true;
107
				continue loop;
108
			} else if (ARG_OUTPUT.equals(currentArg)) {
109
				if (this.indexFile != null) {
110
					displayError(Messages.bind(Messages.CommandLineOnlyOneOutputError));
111
					return false;
112
				} else if (index == argCount) {
113
					displayError(Messages.bind(Messages.CommandLineOutputTakesArgs));
114
					return false;
115
				}
116
				this.indexFile = argsArray[index++];
117
			} else {
118
				if (this.jarToIndex != null) {
119
					displayError(Messages.bind(Messages.CommandLineOnlyOneJarError));
120
					return false;
121
				}
122
				this.jarToIndex = currentArg;
123
			}
124
		}
125
		return true;
126
	}
127
128
	public Object start(IApplicationContext context) throws Exception {
129
		boolean execute = processCommandLine((String[]) context.getArguments().get(IApplicationContext.APPLICATION_ARGS));
130
		if (execute) {
131
			if (this.jarToIndex != null && this.indexFile != null) {
132
				File f = new File(this.jarToIndex);
133
				if (f.exists()) {
134
					if (this.verbose) {
135
						System.out.println(Messages.bind(Messages.CommandLineProcessing, this.indexFile, this.jarToIndex));
136
					}
137
					try {
138
						JavaIndexer.generateIndexForJar(this.jarToIndex, this.indexFile);
139
					} catch (IOException e) {
140
						System.out.println(Messages.bind(Messages.CaughtException, "IOException", e.getLocalizedMessage())); //$NON-NLS-1$
141
					}
142
				} else {
143
						System.out.println(Messages.bind(Messages.CommandLineJarFileNotExist, this.jarToIndex));
144
				}
145
			} else if (this.jarToIndex == null) {
146
				System.out.println(Messages.bind(Messages.CommandLineJarNotSpecified));
147
			} else if (this.indexFile == null) {
148
				System.out.println(Messages.bind(Messages.CommandLineIndexFileNotSpecified));
149
			}
150
		}
151
		return IApplication.EXIT_OK;
152
	}
153
154
	public void stop() {
155
		// do nothing
156
	}
157
158
}
(-)a/org.eclipse.jdt.core/search/org/eclipse/jdt/core/index/messages.properties (+29 lines)
Added Link Here
1
###############################################################################
2
# Copyright (c) 2000, 2006 IBM Corporation and others.
3
# All rights reserved. This program and the accompanying materials
4
# are made available under the terms of the Eclipse Public License v1.0
5
# which accompanies this distribution, and is available at
6
# http://www.eclipse.org/legal/epl-v10.html
7
#
8
# Contributors:
9
#     IBM Corporation - initial API and implementation
10
###############################################################################
11
CommandLineUsage=Usage: eclipse -application org.eclipse.jdt.core.JavaIndexer [ OPTIONS ] -output <indexFile> <jarfile>\n\
12
\n\
13
\   -output <indexFile> Path to the index file to be generated.\n\
14
\
15
\   <jarfile>   Path to the jar for which index needs to be generated.\n\
16
\
17
\n\
18
\ OPTIONS:\n\
19
\n\
20
\   -help                Display this message.\n\
21
\   -verbose             Be verbose about the job.
22
CommandLineProcessing=Generating index {0} for the jar {1}.
23
CommandLineOnlyOneOutputError=Only one output needs to be specified.
24
CommandLineOutputTakesArgs=-output should be followed by the path to the index file.
25
CommandLineOnlyOneJarError=Only one jar file needs to be specified.
26
CommandLineJarNotSpecified=No jar file is specified.
27
CommandLineIndexFileNotSpecified=No index file is specified.
28
CaughtException=Exception {0} - {1}.
29
CommandLineJarFileNotExist={0} does not exist.
(-)a/org.eclipse.jdt.core/search/org/eclipse/jdt/core/index/package.html (+19 lines)
Added Link Here
1
<!doctype html public "-//w3c//dtd html 4.0 transitional//en">
2
<html>
3
<head>
4
   <meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1">
5
   <meta name="Author" content="IBM">
6
   <meta name="GENERATOR" content="Mozilla/4.73 [en] (Windows NT 5.0; U) [Netscape]">
7
   <title>Package-level Javadoc</title>
8
</head>
9
<body>
10
Provides support for generating indexes that can be used by the JDT search engine.
11
<h2>
12
Package Specification</h2>
13
This package provides support for generating indexes that can be used by the search engine. The search engine 
14
indexes all the elements referred in the classpath entries of the project into
15
index files. These index files are used to search the elements faster. Indexing for bigger jars could
16
take some time. To avoid this time, one can generate the index file and specify it when the jar is added
17
to the classpath of the project.
18
</body>
19
</html>
(-)a/org.eclipse.jdt.core/search/org/eclipse/jdt/core/search/SearchParticipant.java (-5 / +9 lines)
Lines 14-19 Link Here
14
import org.eclipse.core.runtime.*;
14
import org.eclipse.core.runtime.*;
15
import org.eclipse.jdt.internal.core.JavaModel;
15
import org.eclipse.jdt.internal.core.JavaModel;
16
import org.eclipse.jdt.internal.core.JavaModelManager;
16
import org.eclipse.jdt.internal.core.JavaModelManager;
17
import org.eclipse.jdt.internal.core.index.FileIndexLocation;
18
import org.eclipse.jdt.internal.core.index.IndexLocation;
17
import org.eclipse.jdt.internal.core.search.indexing.IndexManager;
19
import org.eclipse.jdt.internal.core.search.indexing.IndexManager;
18
20
19
/**
21
/**
Lines 192-200 Link Here
192
	 * </p>
194
	 * </p>
193
	 *
195
	 *
194
	 * @param document the document to index
196
	 * @param document the document to index
195
	 * @param indexLocation the location on the file system of the index
197
	 * @param indexPath the location on the file system of the index
196
	 */
198
	 */
197
	public final void scheduleDocumentIndexing(SearchDocument document, IPath indexLocation) {
199
	public final void scheduleDocumentIndexing(SearchDocument document, IPath indexPath) {
198
		IPath documentPath = new Path(document.getPath());
200
		IPath documentPath = new Path(document.getPath());
199
		Object file = JavaModel.getTarget(documentPath, true);
201
		Object file = JavaModel.getTarget(documentPath, true);
200
		IPath containerPath = documentPath;
202
		IPath containerPath = documentPath;
Lines 205-215 Link Here
205
		}
207
		}
206
		IndexManager manager = JavaModelManager.getIndexManager();
208
		IndexManager manager = JavaModelManager.getIndexManager();
207
		// TODO (frederic) should not have to create index manually, should expose API that recreates index instead
209
		// TODO (frederic) should not have to create index manually, should expose API that recreates index instead
210
		IndexLocation indexLocation;
211
		indexLocation = new FileIndexLocation(indexPath.toFile(), true);
208
		manager.ensureIndexExists(indexLocation, containerPath);
212
		manager.ensureIndexExists(indexLocation, containerPath);
209
		manager.scheduleDocumentIndexing(document, containerPath, indexLocation, this);
213
		manager.scheduleDocumentIndexing(document, containerPath, indexLocation, this);
210
		if (!indexLocation.equals(this.lastIndexLocation)) {
214
		if (!indexPath.equals(this.lastIndexLocation)) {
211
			manager.updateParticipant(indexLocation, containerPath);
215
			manager.updateParticipant(indexPath, containerPath);
212
			this.lastIndexLocation = indexLocation;
216
			this.lastIndexLocation = indexPath;
213
		}
217
		}
214
	}
218
	}
215
219
(-)a/org.eclipse.jdt.core/search/org/eclipse/jdt/internal/core/index/DiskIndex.java (-58 / +69 lines)
Lines 23-29 Link Here
23
23
24
public class DiskIndex {
24
public class DiskIndex {
25
25
26
File indexFile;
26
IndexLocation indexLocation;
27
27
28
private int headerInfoOffset;
28
private int headerInfoOffset;
29
private int numberOfChunks;
29
private int numberOfChunks;
Lines 82-93 Link Here
82
}
82
}
83
83
84
84
85
DiskIndex(String fileName) {
85
DiskIndex() {
86
	if (fileName == null)
87
		throw new java.lang.IllegalArgumentException();
88
	this.indexFile = new File(fileName);
89
90
	// clear cached items
91
	this.headerInfoOffset = -1;
86
	this.headerInfoOffset = -1;
92
	this.numberOfChunks = -1;
87
	this.numberOfChunks = -1;
93
	this.sizeOfLastChunk = -1;
88
	this.sizeOfLastChunk = -1;
Lines 99-104 Link Here
99
	this.cachedCategoryName = null;
94
	this.cachedCategoryName = null;
100
	this.categoryOffsets = null;
95
	this.categoryOffsets = null;
101
	this.categoryEnds = null;
96
	this.categoryEnds = null;
97
}
98
DiskIndex(IndexLocation location) throws IOException {
99
	this();
100
	if (location == null) {
101
		throw new IllegalArgumentException();
102
	}
103
	this.indexLocation = location;
102
}
104
}
103
SimpleSet addDocumentNames(String substring, MemoryIndex memoryIndex) throws IOException {
105
SimpleSet addDocumentNames(String substring, MemoryIndex memoryIndex) throws IOException {
104
	// must skip over documents which have been added/changed/deleted in the memory index
106
	// must skip over documents which have been added/changed/deleted in the memory index
Lines 230-236 Link Here
230
private void cacheDocumentNames() throws IOException {
232
private void cacheDocumentNames() throws IOException {
231
	// will need all document names so get them now
233
	// will need all document names so get them now
232
	this.cachedChunks = new String[this.numberOfChunks][];
234
	this.cachedChunks = new String[this.numberOfChunks][];
233
	FileInputStream stream = new FileInputStream(this.indexFile);
235
	InputStream stream = this.indexLocation.getInputStream();
234
	try {
236
	try {
235
		if (this.numberOfChunks > 5) BUFFER_READ_SIZE <<= 1;
237
		if (this.numberOfChunks > 5) BUFFER_READ_SIZE <<= 1;
236
		int offset = this.chunkOffsets[0];
238
		int offset = this.chunkOffsets[0];
Lines 370-378 Link Here
370
	}
372
	}
371
}
373
}
372
void initialize(boolean reuseExistingFile) throws IOException {
374
void initialize(boolean reuseExistingFile) throws IOException {
373
	if (this.indexFile.exists()) {
375
	if (this.indexLocation.exists()) {
374
		if (reuseExistingFile) {
376
		if (reuseExistingFile) {
375
			FileInputStream stream = new FileInputStream(this.indexFile);
377
			InputStream stream = this.indexLocation.getInputStream();
378
			if (stream == null) {
379
				throw new IOException("Failed to use the index file"); //$NON-NLS-1$
380
			}
376
			this.streamBuffer = new byte[BUFFER_READ_SIZE];
381
			this.streamBuffer = new byte[BUFFER_READ_SIZE];
377
			this.bufferIndex = 0;
382
			this.bufferIndex = 0;
378
			this.bufferEnd = stream.read(this.streamBuffer, 0, 128);
383
			this.bufferEnd = stream.read(this.streamBuffer, 0, 128);
Lines 393-406 Link Here
393
			}
398
			}
394
			return;
399
			return;
395
		}
400
		}
396
		if (!this.indexFile.delete()) {
401
		if (!this.indexLocation.delete()) {
397
			if (DEBUG)
402
			if (DEBUG)
398
				System.out.println("initialize - Failed to delete index " + this.indexFile); //$NON-NLS-1$
403
				System.out.println("initialize - Failed to delete index " + this.indexLocation); //$NON-NLS-1$
399
			throw new IOException("Failed to delete index " + this.indexFile); //$NON-NLS-1$
404
			throw new IOException("Failed to delete index " + this.indexLocation); //$NON-NLS-1$
400
		}
405
		}
401
	}
406
	}
402
	if (this.indexFile.createNewFile()) {
407
	if (this.indexLocation.createNewFile()) {
403
		FileOutputStream stream = new FileOutputStream(this.indexFile, false);
408
		FileOutputStream stream = new FileOutputStream(this.indexLocation.getIndexFile(), false);
404
		try {
409
		try {
405
			this.streamBuffer = new byte[BUFFER_READ_SIZE];
410
			this.streamBuffer = new byte[BUFFER_READ_SIZE];
406
			this.bufferIndex = 0;
411
			this.bufferIndex = 0;
Lines 416-433 Link Here
416
		}
421
		}
417
	} else {
422
	} else {
418
		if (DEBUG)
423
		if (DEBUG)
419
			System.out.println("initialize - Failed to create new index " + this.indexFile); //$NON-NLS-1$
424
			System.out.println("initialize - Failed to create new index " + this.indexLocation); //$NON-NLS-1$
420
		throw new IOException("Failed to create new index " + this.indexFile); //$NON-NLS-1$
425
		throw new IOException("Failed to create new index " + this.indexLocation); //$NON-NLS-1$
421
	}
426
	}
422
}
427
}
423
private void initializeFrom(DiskIndex diskIndex, File newIndexFile) throws IOException {
428
private void initializeFrom(DiskIndex diskIndex, File newIndexFile) throws IOException {
424
	if (newIndexFile.exists() && !newIndexFile.delete()) { // delete the temporary index file
429
	if (newIndexFile.exists() && !newIndexFile.delete()) { // delete the temporary index file
425
		if (DEBUG)
430
		if (DEBUG)
426
			System.out.println("initializeFrom - Failed to delete temp index " + this.indexFile); //$NON-NLS-1$
431
			System.out.println("initializeFrom - Failed to delete temp index " + this.indexLocation); //$NON-NLS-1$
427
	} else if (!newIndexFile.createNewFile()) {
432
	} else if (!newIndexFile.createNewFile()) {
428
		if (DEBUG)
433
		if (DEBUG)
429
			System.out.println("initializeFrom - Failed to create temp index " + this.indexFile); //$NON-NLS-1$
434
			System.out.println("initializeFrom - Failed to create temp index " + this.indexLocation); //$NON-NLS-1$
430
		throw new IOException("Failed to create temp index " + this.indexFile); //$NON-NLS-1$
435
		throw new IOException("Failed to create temp index " + this.indexLocation); //$NON-NLS-1$
431
	}
436
	}
432
437
433
	int size = diskIndex.categoryOffsets == null ? 8 : diskIndex.categoryOffsets.elementSize;
438
	int size = diskIndex.categoryOffsets == null ? 8 : diskIndex.categoryOffsets.elementSize;
Lines 500-505 Link Here
500
DiskIndex mergeWith(MemoryIndex memoryIndex) throws IOException {
505
DiskIndex mergeWith(MemoryIndex memoryIndex) throws IOException {
501
 	// assume write lock is held
506
 	// assume write lock is held
502
	// compute & write out new docNames
507
	// compute & write out new docNames
508
	if (this.indexLocation == null) {
509
		throw new IOException("Pre-built index file not writeable");  //$NON-NLS-1$
510
	}
503
	String[] docNames = readAllDocumentNames();
511
	String[] docNames = readAllDocumentNames();
504
	int previousLength = docNames.length;
512
	int previousLength = docNames.length;
505
	int[] positions = new int[previousLength]; // keeps track of the position of each document in the new sorted docNames
513
	int[] positions = new int[previousLength]; // keeps track of the position of each document in the new sorted docNames
Lines 509-523 Link Here
509
		if (previousLength == 0) return this; // nothing to do... memory index contained deleted documents that had never been saved
517
		if (previousLength == 0) return this; // nothing to do... memory index contained deleted documents that had never been saved
510
518
511
		// index is now empty since all the saved documents were removed
519
		// index is now empty since all the saved documents were removed
512
		DiskIndex newDiskIndex = new DiskIndex(this.indexFile.getPath());
520
		DiskIndex newDiskIndex = new DiskIndex(this.indexLocation);
513
		newDiskIndex.initialize(false);
521
		newDiskIndex.initialize(false);
514
		return newDiskIndex;
522
		return newDiskIndex;
515
	}
523
	}
516
524
	File oldIndexFile = this.indexLocation.getIndexFile();
517
	DiskIndex newDiskIndex = new DiskIndex(this.indexFile.getPath() + ".tmp"); //$NON-NLS-1$
525
	DiskIndex newDiskIndex = new DiskIndex(new FileIndexLocation(new File(oldIndexFile.getPath() + ".tmp"))); //$NON-NLS-1$
526
	File newIndexFile = newDiskIndex.indexLocation.getIndexFile();
518
	try {
527
	try {
519
		newDiskIndex.initializeFrom(this, newDiskIndex.indexFile);
528
		newDiskIndex.initializeFrom(this, newIndexFile);
520
		FileOutputStream stream = new FileOutputStream(newDiskIndex.indexFile, false);
529
		FileOutputStream stream = new FileOutputStream(newIndexFile, false);
521
		int offsetToHeader = -1;
530
		int offsetToHeader = -1;
522
		try {
531
		try {
523
			newDiskIndex.writeAllDocumentNames(docNames, stream);
532
			newDiskIndex.writeAllDocumentNames(docNames, stream);
Lines 549-579 Link Here
549
		newDiskIndex.writeOffsetToHeader(offsetToHeader);
558
		newDiskIndex.writeOffsetToHeader(offsetToHeader);
550
559
551
		// rename file by deleting previous index file & renaming temp one
560
		// rename file by deleting previous index file & renaming temp one
552
		if (this.indexFile.exists() && !this.indexFile.delete()) {
561
		if (oldIndexFile.exists() && !oldIndexFile.delete()) {
553
			if (DEBUG)
562
			if (DEBUG)
554
				System.out.println("mergeWith - Failed to delete " + this.indexFile); //$NON-NLS-1$
563
				System.out.println("mergeWith - Failed to delete " + this.indexLocation); //$NON-NLS-1$
555
			throw new IOException("Failed to delete index file " + this.indexFile); //$NON-NLS-1$
564
			throw new IOException("Failed to delete index file " + this.indexLocation); //$NON-NLS-1$
556
		}
565
		}
557
		if (!newDiskIndex.indexFile.renameTo(this.indexFile)) {
566
		if (!newIndexFile.renameTo(oldIndexFile)) {
558
			if (DEBUG)
567
			if (DEBUG)
559
				System.out.println("mergeWith - Failed to rename " + this.indexFile); //$NON-NLS-1$
568
				System.out.println("mergeWith - Failed to rename " + this.indexLocation); //$NON-NLS-1$
560
			throw new IOException("Failed to rename index file " + this.indexFile); //$NON-NLS-1$
569
			throw new IOException("Failed to rename index file " + this.indexLocation); //$NON-NLS-1$
561
		}
570
		}
562
	} catch (IOException e) {
571
	} catch (IOException e) {
563
		if (newDiskIndex.indexFile.exists() && !newDiskIndex.indexFile.delete())
572
		if (newIndexFile.exists() && !newIndexFile.delete())
564
			if (DEBUG)
573
			if (DEBUG)
565
				System.out.println("mergeWith - Failed to delete temp index " + newDiskIndex.indexFile); //$NON-NLS-1$
574
				System.out.println("mergeWith - Failed to delete temp index " + newDiskIndex.indexLocation); //$NON-NLS-1$
566
		throw e;
575
		throw e;
567
	}
576
	}
568
577
569
	newDiskIndex.indexFile = this.indexFile;
578
	newDiskIndex.indexLocation = this.indexLocation;
570
	return newDiskIndex;
579
	return newDiskIndex;
571
}
580
}
572
private synchronized String[] readAllDocumentNames() throws IOException {
581
private synchronized String[] readAllDocumentNames() throws IOException {
573
	if (this.numberOfChunks <= 0)
582
	if (this.numberOfChunks <= 0)
574
		return CharOperation.NO_STRINGS;
583
		return CharOperation.NO_STRINGS;
575
584
576
	FileInputStream stream = new FileInputStream(this.indexFile);
585
	InputStream stream = this.indexLocation.getInputStream();
577
	try {
586
	try {
578
		int offset = this.chunkOffsets[0];
587
		int offset = this.chunkOffsets[0];
579
		stream.skip(offset);
588
		stream.skip(offset);
Lines 612-618 Link Here
612
		}
621
		}
613
	}
622
	}
614
623
615
	FileInputStream stream = new FileInputStream(this.indexFile);
624
	InputStream stream = this.indexLocation.getInputStream();
616
	HashtableOfObject categoryTable = null;
625
	HashtableOfObject categoryTable = null;
617
	char[][] matchingWords = null;
626
	char[][] matchingWords = null;
618
	int count = 0;
627
	int count = 0;
Lines 626-632 Link Here
626
		try {
635
		try {
627
			if (size < 0) { // DEBUG
636
			if (size < 0) { // DEBUG
628
				System.err.println("-------------------- DEBUG --------------------"); //$NON-NLS-1$
637
				System.err.println("-------------------- DEBUG --------------------"); //$NON-NLS-1$
629
				System.err.println("file = "+this.indexFile); //$NON-NLS-1$
638
				System.err.println("file = "+this.indexLocation); //$NON-NLS-1$
630
				System.err.println("offset = "+offset); //$NON-NLS-1$
639
				System.err.println("offset = "+offset); //$NON-NLS-1$
631
				System.err.println("size = "+size); //$NON-NLS-1$
640
				System.err.println("size = "+size); //$NON-NLS-1$
632
				System.err.println("--------------------   END   --------------------"); //$NON-NLS-1$
641
				System.err.println("--------------------   END   --------------------"); //$NON-NLS-1$
Lines 636-642 Link Here
636
			// DEBUG
645
			// DEBUG
637
			oom.printStackTrace();
646
			oom.printStackTrace();
638
			System.err.println("-------------------- DEBUG --------------------"); //$NON-NLS-1$
647
			System.err.println("-------------------- DEBUG --------------------"); //$NON-NLS-1$
639
			System.err.println("file = "+this.indexFile); //$NON-NLS-1$
648
			System.err.println("file = "+this.indexLocation); //$NON-NLS-1$
640
			System.err.println("offset = "+offset); //$NON-NLS-1$
649
			System.err.println("offset = "+offset); //$NON-NLS-1$
641
			System.err.println("size = "+size); //$NON-NLS-1$
650
			System.err.println("size = "+size); //$NON-NLS-1$
642
			System.err.println("--------------------   END   --------------------"); //$NON-NLS-1$
651
			System.err.println("--------------------   END   --------------------"); //$NON-NLS-1$
Lines 678-684 Link Here
678
	}
687
	}
679
688
680
	if (matchingWords != null && count > 0) {
689
	if (matchingWords != null && count > 0) {
681
		stream = new FileInputStream(this.indexFile);
690
		stream = this.indexLocation.getInputStream();
682
		try {
691
		try {
683
			stream.skip(firstOffset);
692
			stream.skip(firstOffset);
684
			this.bufferIndex = 0;
693
			this.bufferIndex = 0;
Lines 696-702 Link Here
696
	this.streamBuffer = null;
705
	this.streamBuffer = null;
697
	return categoryTable;
706
	return categoryTable;
698
}
707
}
699
private void readChunk(String[] docNames, FileInputStream stream, int index, int size) throws IOException {
708
private void readChunk(String[] docNames, InputStream stream, int index, int size) throws IOException {
700
	String current = new String(readStreamChars(stream));
709
	String current = new String(readStreamChars(stream));
701
	docNames[index++] = current;
710
	docNames[index++] = current;
702
	for (int i = 1; i < size; i++) {
711
	for (int i = 1; i < size; i++) {
Lines 734-740 Link Here
734
			throw new IllegalArgumentException();
743
			throw new IllegalArgumentException();
735
		this.streamBuffer = new byte[numberOfBytes];
744
		this.streamBuffer = new byte[numberOfBytes];
736
		this.bufferIndex = 0;
745
		this.bufferIndex = 0;
737
		FileInputStream file = new FileInputStream(this.indexFile);
746
		InputStream file = this.indexLocation.getInputStream();
738
		try {
747
		try {
739
			file.skip(start);
748
			file.skip(start);
740
			if (file.read(this.streamBuffer, 0, numberOfBytes) != numberOfBytes)
749
			if (file.read(this.streamBuffer, 0, numberOfBytes) != numberOfBytes)
Lines 763-769 Link Here
763
	if (arrayOffset instanceof int[])
772
	if (arrayOffset instanceof int[])
764
		return (int[]) arrayOffset;
773
		return (int[]) arrayOffset;
765
774
766
	FileInputStream stream = new FileInputStream(this.indexFile);
775
	InputStream stream = this.indexLocation.getInputStream();
767
	try {
776
	try {
768
		int offset = ((Integer) arrayOffset).intValue();
777
		int offset = ((Integer) arrayOffset).intValue();
769
		stream.skip(offset);
778
		stream.skip(offset);
Lines 776-794 Link Here
776
		this.streamBuffer = null;
785
		this.streamBuffer = null;
777
	}
786
	}
778
}
787
}
779
private void readHeaderInfo(FileInputStream stream) throws IOException {
788
private void readHeaderInfo(InputStream stream) throws IOException {
780
789
781
	// must be same order as writeHeaderInfo()
790
	// must be same order as writeHeaderInfo()
782
	this.numberOfChunks = readStreamInt(stream);
791
	this.numberOfChunks = readStreamInt(stream);
783
	this.sizeOfLastChunk = this.streamBuffer[this.bufferIndex++] & 0xFF;
792
	this.sizeOfLastChunk = this.streamBuffer[this.bufferIndex++] & 0xFF;
784
	this.documentReferenceSize = this.streamBuffer[this.bufferIndex++] & 0xFF;
793
	this.documentReferenceSize = this.streamBuffer[this.bufferIndex++] & 0xFF;
785
	this.separator = (char) (this.streamBuffer[this.bufferIndex++] & 0xFF);
794
	this.separator = (char) (this.streamBuffer[this.bufferIndex++] & 0xFF);
786
	long fileLength = this.indexFile.length();
795
	long length = this.indexLocation.length();
787
	if (this.numberOfChunks > fileLength ) {
796
	if (length != -1 && this.numberOfChunks > length) {
788
		// not an accurate check, but good enough https://bugs.eclipse.org/bugs/show_bug.cgi?id=350612
797
		// not an accurate check, but good enough https://bugs.eclipse.org/bugs/show_bug.cgi?id=350612
789
		if (DEBUG)
798
		if (DEBUG)
790
			System.out.println("Index file is corrupted " + this.indexFile); //$NON-NLS-1$
799
			System.out.println("Index file is corrupted " + this.indexLocation); //$NON-NLS-1$
791
		throw new IOException("Index file is corrupted " + this.indexFile); //$NON-NLS-1$
800
		throw new IOException("Index file is corrupted " + this.indexLocation); //$NON-NLS-1$
792
	}
801
	}
793
	this.chunkOffsets = new int[this.numberOfChunks];
802
	this.chunkOffsets = new int[this.numberOfChunks];
794
	for (int i = 0; i < this.numberOfChunks; i++)
803
	for (int i = 0; i < this.numberOfChunks; i++)
Lines 799-809 Link Here
799
	int size = readStreamInt(stream);
808
	int size = readStreamInt(stream);
800
	this.categoryOffsets = new HashtableOfIntValues(size);
809
	this.categoryOffsets = new HashtableOfIntValues(size);
801
	this.categoryEnds = new HashtableOfIntValues(size);
810
	this.categoryEnds = new HashtableOfIntValues(size);
802
	if (size > fileLength) {
811
	if (length != -1 && size > length) {
803
		//  not an accurate check, but good enough  https://bugs.eclipse.org/bugs/show_bug.cgi?id=350612
812
		//  not an accurate check, but good enough  https://bugs.eclipse.org/bugs/show_bug.cgi?id=350612
804
		if (DEBUG)
813
		if (DEBUG)
805
			System.out.println("Index file is corrupted " + this.indexFile); //$NON-NLS-1$
814
			System.out.println("Index file is corrupted " + this.indexLocation); //$NON-NLS-1$
806
		throw new IOException("Index file is corrupted " + this.indexFile); //$NON-NLS-1$
815
		throw new IOException("Index file is corrupted " + this.indexLocation); //$NON-NLS-1$
807
	}
816
	}
808
	char[] previousCategory = null;
817
	char[] previousCategory = null;
809
	int offset = -1;
818
	int offset = -1;
Lines 840-850 Link Here
840
		}
849
		}
841
	}
850
	}
842
}
851
}
843
private void readStreamBuffer(FileInputStream stream) throws IOException {
852
private void readStreamBuffer(InputStream stream) throws IOException {
844
	// if we're about to read a known amount at the end of the existing buffer, but it does not completely fit
853
	// if we're about to read a known amount at the end of the existing buffer, but it does not completely fit
845
	// so we need to shift the remaining bytes to be read, and fill the buffer from the stream
854
	// so we need to shift the remaining bytes to be read, and fill the buffer from the stream
846
	if (this.bufferEnd < this.streamBuffer.length)
855
	if (this.bufferEnd < this.streamBuffer.length) {
847
		return; // we're at the end of the stream - nothing left to read
856
		if (stream.available() == 0)
857
			return; // we're at the end of the stream - nothing left to read
858
	}
848
859
849
	int bytesInBuffer = this.bufferEnd - this.bufferIndex;
860
	int bytesInBuffer = this.bufferEnd - this.bufferIndex;
850
	if (bytesInBuffer > 0)
861
	if (bytesInBuffer > 0)
Lines 872-878 Link Here
872
 * @exception  UTFDataFormatException  if the bytes do not represent a
883
 * @exception  UTFDataFormatException  if the bytes do not represent a
873
 *               valid UTF-8 encoding of a Unicode string.
884
 *               valid UTF-8 encoding of a Unicode string.
874
 */
885
 */
875
private char[] readStreamChars(FileInputStream stream) throws IOException {
886
private char[] readStreamChars(InputStream stream) throws IOException {
876
	// read chars array length
887
	// read chars array length
877
	if (stream != null && this.bufferIndex + 2 >= this.bufferEnd)
888
	if (stream != null && this.bufferIndex + 2 >= this.bufferEnd)
878
		readStreamBuffer(stream);
889
		readStreamBuffer(stream);
Lines 886-892 Link Here
886
		// how many characters can be decoded without refilling the buffer?
897
		// how many characters can be decoded without refilling the buffer?
887
		int charsInBuffer = i + ((this.bufferEnd - this.bufferIndex) / 3);
898
		int charsInBuffer = i + ((this.bufferEnd - this.bufferIndex) / 3);
888
		// all the characters must already be in the buffer if we're at the end of the stream
899
		// all the characters must already be in the buffer if we're at the end of the stream
889
		if (charsInBuffer > length || this.bufferEnd != this.streamBuffer.length || stream == null)
900
		if (charsInBuffer > length || stream == null  || (this.bufferEnd != this.streamBuffer.length && stream.available() == 0))
890
			charsInBuffer = length;
901
			charsInBuffer = length;
891
		while (i < charsInBuffer) {
902
		while (i < charsInBuffer) {
892
			byte b = this.streamBuffer[this.bufferIndex++];
903
			byte b = this.streamBuffer[this.bufferIndex++];
Lines 931-937 Link Here
931
	}
942
	}
932
	return word;
943
	return word;
933
}
944
}
934
private int[] readStreamDocumentArray(FileInputStream stream, int arraySize) throws IOException {
945
private int[] readStreamDocumentArray(InputStream stream, int arraySize) throws IOException {
935
	int[] indexes = new int[arraySize];
946
	int[] indexes = new int[arraySize];
936
	if (arraySize == 0) return indexes;
947
	if (arraySize == 0) return indexes;
937
948
Lines 972-978 Link Here
972
	}
983
	}
973
	return indexes;
984
	return indexes;
974
}
985
}
975
private int readStreamInt(FileInputStream stream) throws IOException {
986
private int readStreamInt(InputStream stream) throws IOException {
976
	if (this.bufferIndex + 4 >= this.bufferEnd) {
987
	if (this.bufferIndex + 4 >= this.bufferEnd) {
977
		readStreamBuffer(stream);
988
		readStreamBuffer(stream);
978
	}
989
	}
Lines 1182-1188 Link Here
1182
}
1193
}
1183
private void writeOffsetToHeader(int offsetToHeader) throws IOException {
1194
private void writeOffsetToHeader(int offsetToHeader) throws IOException {
1184
	if (offsetToHeader > 0) {
1195
	if (offsetToHeader > 0) {
1185
		RandomAccessFile file = new RandomAccessFile(this.indexFile, "rw"); //$NON-NLS-1$
1196
		RandomAccessFile file = new RandomAccessFile(this.indexLocation.getIndexFile(), "rw"); //$NON-NLS-1$
1186
		try {
1197
		try {
1187
			file.seek(this.headerInfoOffset); // offset to position in header
1198
			file.seek(this.headerInfoOffset); // offset to position in header
1188
			file.writeInt(offsetToHeader);
1199
			file.writeInt(offsetToHeader);
(-)a/org.eclipse.jdt.core/search/org/eclipse/jdt/internal/core/index/FileIndexLocation.java (+98 lines)
Added Link Here
1
/*******************************************************************************
2
 * Copyright (c) 2011 IBM Corporation and others.
3
 * All rights reserved. This program and the accompanying materials
4
 * are made available under the terms of the Eclipse Public License v1.0
5
 * which accompanies this distribution, and is available at
6
 * http://www.eclipse.org/legal/epl-v10.html
7
 *
8
 * Contributors:
9
 *     IBM Corporation - initial API and implementation
10
 *******************************************************************************/
11
package org.eclipse.jdt.internal.core.index;
12
13
import java.io.File;
14
import java.io.FileInputStream;
15
import java.io.IOException;
16
import java.io.InputStream;
17
import java.net.URL;
18
19
import org.eclipse.core.runtime.IPath;
20
import org.eclipse.core.runtime.Path;
21
22
public class FileIndexLocation extends IndexLocation {
23
	File indexFile;
24
25
	public FileIndexLocation(File file) {
26
		super(file);
27
		this.indexFile = file;
28
	}
29
30
	public FileIndexLocation(URL url, File file) {
31
		super(url);
32
		this.indexFile = file;
33
	}
34
35
	public FileIndexLocation(File file, boolean participantIndex) {
36
		this(file);
37
		this.participantIndex = true;
38
	}
39
40
	public boolean createNewFile() throws IOException {
41
		return this.indexFile.createNewFile();
42
	}
43
44
	public boolean delete() {
45
		return this.indexFile.delete();
46
	}
47
48
	public boolean equals(Object other) {
49
		if (!(other instanceof FileIndexLocation)) return false;
50
		return this.indexFile.equals(((FileIndexLocation) other).indexFile);
51
	}
52
53
	public boolean exists() {
54
		return this.indexFile.exists();
55
	}
56
57
	public String fileName() {
58
		return this.indexFile.getName();
59
	}
60
	
61
	public File getIndexFile() {
62
		return this.indexFile;
63
	}
64
65
	InputStream getInputStream() throws IOException {
66
		return new FileInputStream(this.indexFile);
67
	}
68
69
	public String getCanonicalFilePath() {
70
		try {
71
			return this.indexFile.getCanonicalPath();
72
		} catch (IOException e) {
73
			// ignore
74
		}
75
		return null;
76
	}
77
78
	public int hashCode() {
79
		return this.indexFile.hashCode();
80
	}
81
82
	public long lastModified() {
83
		return this.indexFile.lastModified();
84
	}
85
86
	public long length() {
87
		return this.indexFile.length();
88
	}
89
90
	public boolean startsWith(IPath path) {
91
		try {
92
			return path.isPrefixOf(new Path(this.indexFile.getCanonicalPath()));
93
		} catch (IOException e) {
94
			return false;
95
		}
96
	}
97
98
}
(-)a/org.eclipse.jdt.core/search/org/eclipse/jdt/internal/core/index/Index.java (-5 / +11 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 88-99 Link Here
88
}
88
}
89
89
90
90
91
public Index(String fileName, String containerPath, boolean reuseExistingFile) throws IOException {
91
public Index(IndexLocation location, String containerPath, boolean reuseExistingFile) throws IOException {
92
	this.containerPath = containerPath;
92
	this.containerPath = containerPath;
93
	this.monitor = new ReadWriteMonitor();
93
	this.monitor = new ReadWriteMonitor();
94
94
95
	this.memoryIndex = new MemoryIndex();
95
	this.memoryIndex = new MemoryIndex();
96
	this.diskIndex = new DiskIndex(fileName);
96
	this.diskIndex = new DiskIndex(location);
97
	this.diskIndex.initialize(reuseExistingFile);
97
	this.diskIndex.initialize(reuseExistingFile);
98
	if (reuseExistingFile) this.separator = this.diskIndex.separator;
98
	if (reuseExistingFile) this.separator = this.diskIndex.separator;
99
}
99
}
Lines 110-116 Link Here
110
	return documentPath.substring(index + 1);
110
	return documentPath.substring(index + 1);
111
}
111
}
112
public File getIndexFile() {
112
public File getIndexFile() {
113
	return this.diskIndex == null ? null : this.diskIndex.indexFile;
113
	return this.diskIndex == null ? null : this.diskIndex.indexLocation.getIndexFile();
114
}
115
public IndexLocation getIndexLocation() {
116
	return this.diskIndex == null ? null : this.diskIndex.indexLocation;
117
}
118
public long getIndexLastModified() {
119
	return this.diskIndex == null? -1 : this.diskIndex.indexLocation.lastModified();
114
}
120
}
115
public boolean hasChanged() {
121
public boolean hasChanged() {
116
	return this.memoryIndex.hasChanged();
122
	return this.memoryIndex.hasChanged();
Lines 180-186 Link Here
180
 */
186
 */
181
public void reset() throws IOException {
187
public void reset() throws IOException {
182
	this.memoryIndex = new MemoryIndex();
188
	this.memoryIndex = new MemoryIndex();
183
	this.diskIndex = new DiskIndex(this.diskIndex.indexFile.getCanonicalPath());
189
	this.diskIndex = new DiskIndex(this.diskIndex.indexLocation);
184
	this.diskIndex.initialize(false/*do not reuse the index file*/);
190
	this.diskIndex.initialize(false/*do not reuse the index file*/);
185
}
191
}
186
public void save() throws IOException {
192
public void save() throws IOException {
(-)a/org.eclipse.jdt.core/search/org/eclipse/jdt/internal/core/index/IndexLocation.java (+124 lines)
Added Link Here
1
/*******************************************************************************
2
 * Copyright (c) 2011 IBM Corporation and others.
3
 * All rights reserved. This program and the accompanying materials
4
 * are made available under the terms of the Eclipse Public License v1.0
5
 * which accompanies this distribution, and is available at
6
 * http://www.eclipse.org/legal/epl-v10.html
7
 *
8
 * Contributors:
9
 *     IBM Corporation - initial API and implementation
10
 *******************************************************************************/
11
package org.eclipse.jdt.internal.core.index;
12
13
import java.io.File;
14
import java.io.IOException;
15
import java.io.InputStream;
16
17
import java.net.MalformedURLException;
18
import java.net.URL;
19
20
import org.eclipse.core.runtime.FileLocator;
21
import org.eclipse.core.runtime.IPath;
22
23
/**
24
 * The location of the index files are represented as {@link IndexLocation}
25
 * 
26
 * This is an abstract class to allow different implementation for a jar entry and a file
27
 * on the disk. Some of these functions could mean different for a jar entry or a file
28
 * 
29
 */
30
public abstract class IndexLocation {
31
	
32
	public static IndexLocation createIndexLocation(URL url) {
33
		URL localUrl;
34
		try {
35
			localUrl = FileLocator.resolve(url);
36
		} catch (IOException e) {
37
			return null;
38
		}
39
		if (localUrl.getProtocol().equals("file")) { //$NON-NLS-1$
40
			return new FileIndexLocation(url, new File(localUrl.getPath()));
41
		}
42
		return new JarIndexLocation(url, localUrl);
43
	}
44
	
45
	private final URL url; // url of the given index location
46
47
	/**
48
	 * Set to true if this index location is of an index file specified
49
	 * by a participant through 
50
	 * {@link org.eclipse.jdt.core.search.SearchParticipant#scheduleDocumentIndexing}
51
	 */
52
	protected boolean participantIndex;
53
	
54
	protected IndexLocation(File file) {
55
		URL tempUrl = null;
56
		try {
57
			tempUrl = file.toURI().toURL();
58
		} catch (MalformedURLException e) {
59
			// should not happen
60
		}
61
		this.url = tempUrl;
62
	}
63
	
64
	public IndexLocation(URL url) {
65
		this.url = url;
66
	}
67
68
	/**
69
	 * Closes any open streams.
70
	 */
71
	public void close() {
72
		// default nothing to do
73
	}
74
75
	/**
76
	 * Creates a new file for the given index location
77
	 * @return true if the file is created
78
	 * @throws IOException
79
	 */
80
	public abstract boolean createNewFile() throws IOException;
81
82
	public abstract boolean delete();
83
84
	public abstract boolean exists();
85
	
86
	public abstract String fileName();
87
88
	/**
89
	 * @return the canonical file path if the location is a file or null otherwise
90
	 */
91
	public abstract String getCanonicalFilePath();
92
93
	public abstract File getIndexFile();
94
95
	abstract InputStream getInputStream() throws IOException;
96
97
	public URL getUrl() {
98
		return this.url;
99
	}
100
101
	public int hashCode() {
102
		return this.url.hashCode();
103
	}
104
105
	public boolean isParticipantIndex() {
106
		return this.participantIndex;
107
	}
108
109
	/**
110
	 * @return the last modified time if the location is a file or -1 otherwise
111
	 */
112
	public abstract long lastModified();
113
114
	/**
115
	 * @return the length of the file if the location is a file or -1 otherwise
116
	 */
117
	public abstract long length();
118
119
	public abstract boolean startsWith(IPath path);
120
121
	public String toString() {
122
		return this.url.toString();
123
	}
124
}
(-)a/org.eclipse.jdt.core/search/org/eclipse/jdt/internal/core/index/JarIndexLocation.java (+108 lines)
Added Link Here
1
/*******************************************************************************
2
 * Copyright (c) 2011 IBM Corporation and others.
3
 * All rights reserved. This program and the accompanying materials
4
 * are made available under the terms of the Eclipse Public License v1.0
5
 * which accompanies this distribution, and is available at
6
 * http://www.eclipse.org/legal/epl-v10.html
7
 *
8
 * Contributors:
9
 *     IBM Corporation - initial API and implementation
10
 *******************************************************************************/
11
package org.eclipse.jdt.internal.core.index;
12
13
import java.io.File;
14
import java.io.IOException;
15
import java.io.InputStream;
16
import java.net.JarURLConnection;
17
import java.net.URL;
18
import java.util.jar.JarEntry;
19
import java.util.jar.JarFile;
20
21
import org.eclipse.core.runtime.IPath;
22
import org.eclipse.core.runtime.Path;
23
24
public class JarIndexLocation extends IndexLocation {
25
	private JarFile jarFile = null;
26
	private JarEntry jarEntry = null;
27
	private URL localUrl;
28
29
	public JarIndexLocation(URL url, URL localUrl2) {
30
		super(url);
31
		this.localUrl = localUrl2;
32
	}
33
34
	public boolean createNewFile() throws IOException {
35
		return false;
36
	}
37
38
	public void close() {
39
		if (this.jarFile != null) {
40
			try {
41
				this.jarFile.close();
42
			} catch (IOException e) {
43
				// ignore
44
			}
45
			this.jarFile = null;
46
		}
47
	}
48
49
	public boolean delete() {
50
		return false;
51
	}
52
53
	public boolean equals(Object other) {
54
		if (!(other instanceof JarIndexLocation)) return false;
55
		return this.localUrl.equals(((JarIndexLocation) other).localUrl);
56
	}
57
58
	public boolean exists() {
59
		try {
60
			if (this.jarFile == null) {
61
				JarURLConnection connection = (JarURLConnection) this.localUrl.openConnection();
62
				JarFile file = connection.getJarFile();
63
				if (file == null)
64
					return false;
65
				file.close();
66
			}
67
		} catch (IOException e) {
68
			return false;
69
		}
70
		return true;
71
	}
72
73
	public String fileName() {
74
		return null;
75
	}
76
77
	public File getIndexFile() {
78
		return null;
79
	}
80
81
	InputStream getInputStream() throws IOException {
82
		if (this.jarFile == null) {
83
			JarURLConnection connection = (JarURLConnection) this.localUrl.openConnection();
84
			this.jarFile = connection.getJarFile();
85
			this.jarEntry = connection.getJarEntry();
86
		}
87
		if (this.jarFile == null || this.jarEntry == null)
88
			return null;
89
		return this.jarFile.getInputStream(this.jarEntry);
90
	}
91
92
	public String getCanonicalFilePath() {
93
		return null;
94
	}
95
96
	public long lastModified() {
97
		return -1;
98
	}
99
100
	public long length() {
101
		return -1;
102
	}
103
104
	public boolean startsWith(IPath path) {
105
		return (path.isPrefixOf(new Path(this.localUrl.getPath())));
106
	}
107
108
}
(-)a/org.eclipse.jdt.core/search/org/eclipse/jdt/internal/core/search/IndexSelector.java (-3 / +4 lines)
Lines 27-32 Link Here
27
import org.eclipse.jdt.internal.core.JavaProject;
27
import org.eclipse.jdt.internal.core.JavaProject;
28
import org.eclipse.jdt.internal.core.builder.ReferenceCollection;
28
import org.eclipse.jdt.internal.core.builder.ReferenceCollection;
29
import org.eclipse.jdt.internal.core.builder.State;
29
import org.eclipse.jdt.internal.core.builder.State;
30
import org.eclipse.jdt.internal.core.index.IndexLocation;
30
import org.eclipse.jdt.internal.core.search.indexing.IndexManager;
31
import org.eclipse.jdt.internal.core.search.indexing.IndexManager;
31
import org.eclipse.jdt.internal.core.search.matching.MatchLocator;
32
import org.eclipse.jdt.internal.core.search.matching.MatchLocator;
32
import org.eclipse.jdt.internal.core.search.matching.MethodPattern;
33
import org.eclipse.jdt.internal.core.search.matching.MethodPattern;
Lines 38-44 Link Here
38
public class IndexSelector {
39
public class IndexSelector {
39
	IJavaSearchScope searchScope;
40
	IJavaSearchScope searchScope;
40
	SearchPattern pattern;
41
	SearchPattern pattern;
41
	IPath[] indexLocations; // cache of the keys for looking index up
42
	IndexLocation[] indexLocations; // cache of the keys for looking index up
42
43
43
public IndexSelector(
44
public IndexSelector(
44
		IJavaSearchScope searchScope,
45
		IJavaSearchScope searchScope,
Lines 267-276 Link Here
267
	}
268
	}
268
269
269
	locations.remove(null); // Ensure no nulls
270
	locations.remove(null); // Ensure no nulls
270
	this.indexLocations = (IPath[]) locations.toArray(new IPath[locations.size()]);
271
	this.indexLocations = (IndexLocation[]) locations.toArray(new IndexLocation[locations.size()]);
271
}
272
}
272
273
273
public IPath[] getIndexLocations() {
274
public IndexLocation[] getIndexLocations() {
274
	if (this.indexLocations == null) {
275
	if (this.indexLocations == null) {
275
		initializeIndexLocations();
276
		initializeIndexLocations();
276
	}
277
	}
(-)a/org.eclipse.jdt.core/search/org/eclipse/jdt/internal/core/search/JavaSearchParticipant.java (-1 / +15 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 12-17 Link Here
12
12
13
import org.eclipse.core.runtime.*;
13
import org.eclipse.core.runtime.*;
14
import org.eclipse.jdt.core.search.*;
14
import org.eclipse.jdt.core.search.*;
15
import org.eclipse.jdt.internal.core.index.IndexLocation;
15
import org.eclipse.jdt.internal.core.search.indexing.BinaryIndexer;
16
import org.eclipse.jdt.internal.core.search.indexing.BinaryIndexer;
16
import org.eclipse.jdt.internal.core.search.indexing.SourceIndexer;
17
import org.eclipse.jdt.internal.core.search.indexing.SourceIndexer;
17
import org.eclipse.jdt.internal.core.search.matching.MatchLocator;
18
import org.eclipse.jdt.internal.core.search.matching.MatchLocator;
Lines 98-104 Link Here
98
	 * @see org.eclipse.jdt.core.search.SearchParticipant#selectIndexes(org.eclipse.jdt.core.search.SearchQuery, org.eclipse.jdt.core.search.SearchContext)
99
	 * @see org.eclipse.jdt.core.search.SearchParticipant#selectIndexes(org.eclipse.jdt.core.search.SearchQuery, org.eclipse.jdt.core.search.SearchContext)
99
	 */
100
	 */
100
	public IPath[] selectIndexes(SearchPattern pattern, IJavaSearchScope scope) {
101
	public IPath[] selectIndexes(SearchPattern pattern, IJavaSearchScope scope) {
102
		IndexSelector selector = (IndexSelector) this.indexSelector.get();
103
		if (selector == null) {
104
			selector = new IndexSelector(scope, pattern);
105
			this.indexSelector.set(selector);
106
		}
107
		IndexLocation[] urls = selector.getIndexLocations();
108
		IPath[] paths = new IPath[urls.length];
109
		for (int i = 0; i < urls.length; i++) {
110
			paths[i] = new Path(urls[i].getIndexFile().getPath());
111
		}
112
		return paths;
113
	}
101
114
115
	public IndexLocation[] selectIndexURLs(SearchPattern pattern, IJavaSearchScope scope) {
102
		IndexSelector selector = (IndexSelector) this.indexSelector.get();
116
		IndexSelector selector = (IndexSelector) this.indexSelector.get();
103
		if (selector == null) {
117
		if (selector == null) {
104
			selector = new IndexSelector(scope, pattern);
118
			selector = new IndexSelector(scope, pattern);
(-)a/org.eclipse.jdt.core/search/org/eclipse/jdt/internal/core/search/PatternSearchJob.java (-2 / +15 lines)
Lines 17-23 Link Here
17
import org.eclipse.core.runtime.OperationCanceledException;
17
import org.eclipse.core.runtime.OperationCanceledException;
18
import org.eclipse.jdt.core.search.*;
18
import org.eclipse.jdt.core.search.*;
19
import org.eclipse.jdt.internal.core.JavaModelManager;
19
import org.eclipse.jdt.internal.core.JavaModelManager;
20
import org.eclipse.jdt.internal.core.index.FileIndexLocation;
20
import org.eclipse.jdt.internal.core.index.Index;
21
import org.eclipse.jdt.internal.core.index.Index;
22
import org.eclipse.jdt.internal.core.index.IndexLocation;
21
import org.eclipse.jdt.internal.core.search.indexing.ReadWriteMonitor;
23
import org.eclipse.jdt.internal.core.search.indexing.ReadWriteMonitor;
22
import org.eclipse.jdt.internal.core.search.matching.MatchLocator;
24
import org.eclipse.jdt.internal.core.search.matching.MatchLocator;
23
import org.eclipse.jdt.internal.core.search.processing.IJob;
25
import org.eclipse.jdt.internal.core.search.processing.IJob;
Lines 76-83 Link Here
76
}
78
}
77
public Index[] getIndexes(IProgressMonitor progressMonitor) {
79
public Index[] getIndexes(IProgressMonitor progressMonitor) {
78
	// acquire the in-memory indexes on the fly
80
	// acquire the in-memory indexes on the fly
79
	IPath[] indexLocations = this.participant.selectIndexes(this.pattern, this.scope);
81
	IndexLocation[] indexLocations;
80
	int length = indexLocations.length;
82
	int length;
83
	if (this.participant instanceof JavaSearchParticipant) {
84
		indexLocations = ((JavaSearchParticipant)this.participant).selectIndexURLs(this.pattern, this.scope);
85
		length = indexLocations.length;
86
	} else {
87
		IPath[] paths = this.participant.selectIndexes(this.pattern, this.scope);
88
		length = paths.length;
89
		indexLocations = new IndexLocation[paths.length];
90
		for (int i = 0, len = paths.length; i < len; i++) {
91
			indexLocations[i] = new FileIndexLocation(paths[i].toFile(), true);
92
		}
93
	}
81
	Index[] indexes = JavaModelManager.getIndexManager().getIndexes(indexLocations, progressMonitor);
94
	Index[] indexes = JavaModelManager.getIndexManager().getIndexes(indexLocations, progressMonitor);
82
	this.areIndexesReady = indexes.length == length;
95
	this.areIndexesReady = indexes.length == length;
83
	return indexes;
96
	return indexes;
(-)a/org.eclipse.jdt.core/search/org/eclipse/jdt/internal/core/search/indexing/AddJarFileToIndex.java (-5 / +19 lines)
Lines 1-5 Link Here
1
/*******************************************************************************
1
/*******************************************************************************
2
 * Copyright (c) 2000, 2010 IBM Corporation and others.
2
 * Copyright (c) 2000, 2011 IBM Corporation and others.
3
 * All rights reserved. This program and the accompanying materials
3
 * All rights reserved. This program and the accompanying materials
4
 * are made available under the terms of the Eclipse Public License v1.0
4
 * are made available under the terms of the Eclipse Public License v1.0
5
 * which accompanies this distribution, and is available at
5
 * which accompanies this distribution, and is available at
Lines 34-39 Link Here
34
import org.eclipse.jdt.internal.compiler.util.Util;
34
import org.eclipse.jdt.internal.compiler.util.Util;
35
import org.eclipse.jdt.internal.core.JavaModelManager;
35
import org.eclipse.jdt.internal.core.JavaModelManager;
36
import org.eclipse.jdt.internal.core.index.Index;
36
import org.eclipse.jdt.internal.core.index.Index;
37
import org.eclipse.jdt.internal.core.index.IndexLocation;
37
import org.eclipse.jdt.internal.core.search.JavaSearchDocument;
38
import org.eclipse.jdt.internal.core.search.JavaSearchDocument;
38
import org.eclipse.jdt.internal.core.search.processing.JobManager;
39
import org.eclipse.jdt.internal.core.search.processing.JobManager;
39
40
Lines 42-55 Link Here
42
	private static final char JAR_SEPARATOR = IJavaSearchScope.JAR_FILE_ENTRY_SEPARATOR.charAt(0);
43
	private static final char JAR_SEPARATOR = IJavaSearchScope.JAR_FILE_ENTRY_SEPARATOR.charAt(0);
43
	IFile resource;
44
	IFile resource;
44
	Scanner scanner;
45
	Scanner scanner;
46
	private IndexLocation indexFileURL;
45
47
46
	public AddJarFileToIndex(IFile resource, IndexManager manager) {
48
	public AddJarFileToIndex(IFile resource, IndexLocation indexFile, IndexManager manager) {
47
		super(resource.getFullPath(), manager);
49
		super(resource.getFullPath(), manager);
48
		this.resource = resource;
50
		this.resource = resource;
51
		this.indexFileURL = indexFile;
49
	}
52
	}
50
	public AddJarFileToIndex(IPath jarPath, IndexManager manager) {
53
	public AddJarFileToIndex(IPath jarPath, IndexLocation indexFile, IndexManager manager) {
51
		// external JAR scenario - no resource
54
		// external JAR scenario - no resource
52
		super(jarPath, manager);
55
		super(jarPath, manager);
56
		this.indexFileURL = indexFile;
53
	}
57
	}
54
	public boolean equals(Object o) {
58
	public boolean equals(Object o) {
55
		if (o instanceof AddJarFileToIndex) {
59
		if (o instanceof AddJarFileToIndex) {
Lines 70-75 Link Here
70
	public boolean execute(IProgressMonitor progressMonitor) {
74
	public boolean execute(IProgressMonitor progressMonitor) {
71
75
72
		if (this.isCancelled || progressMonitor != null && progressMonitor.isCanceled()) return true;
76
		if (this.isCancelled || progressMonitor != null && progressMonitor.isCanceled()) return true;
77
78
		if (this.indexFileURL != null) {
79
			boolean added = this.manager.addIndex(this.containerPath, this.indexFileURL);
80
			if (added) return true;	
81
			this.indexFileURL = null;
82
		}
73
83
74
		try {
84
		try {
75
			// if index is already cached, then do not perform any check
85
			// if index is already cached, then do not perform any check
Lines 192-198 Link Here
192
					return false;
202
					return false;
193
				}
203
				}
194
				index.separator = JAR_SEPARATOR;
204
				index.separator = JAR_SEPARATOR;
195
205
				IPath indexPath = null;
206
				IndexLocation indexLocation;
207
				if ((indexLocation = index.getIndexLocation()) != null) {
208
					indexPath = new Path(indexLocation.getCanonicalFilePath());
209
				}
196
				for (Enumeration e = zip.entries(); e.hasMoreElements();) {
210
				for (Enumeration e = zip.entries(); e.hasMoreElements();) {
197
					if (this.isCancelled) {
211
					if (this.isCancelled) {
198
						if (JobManager.VERBOSE)
212
						if (JobManager.VERBOSE)
Lines 208-214 Link Here
208
						// index only classes coming from valid packages - https://bugs.eclipse.org/bugs/show_bug.cgi?id=293861
222
						// index only classes coming from valid packages - https://bugs.eclipse.org/bugs/show_bug.cgi?id=293861
209
						final byte[] classFileBytes = org.eclipse.jdt.internal.compiler.util.Util.getZipEntryByteContent(ze, zip);
223
						final byte[] classFileBytes = org.eclipse.jdt.internal.compiler.util.Util.getZipEntryByteContent(ze, zip);
210
						JavaSearchDocument entryDocument = new JavaSearchDocument(ze, zipFilePath, classFileBytes, participant);
224
						JavaSearchDocument entryDocument = new JavaSearchDocument(ze, zipFilePath, classFileBytes, participant);
211
						this.manager.indexDocument(entryDocument, participant, index, this.containerPath);
225
						this.manager.indexDocument(entryDocument, participant, index, indexPath);
212
					}
226
					}
213
				}
227
				}
214
				this.manager.saveIndex(index);
228
				this.manager.saveIndex(index);
(-)a/org.eclipse.jdt.core/search/org/eclipse/jdt/internal/core/search/indexing/BinaryIndexer.java (-9 / +4 lines)
Lines 1-5 Link Here
1
/*******************************************************************************
1
/*******************************************************************************
2
 * Copyright (c) 2000, 2011 IBM Corporation and others.
2
 * Copyright (c) 2000, 2012 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 46-51 Link Here
46
		super(document);
46
		super(document);
47
	}
47
	}
48
	private void addBinaryStandardAnnotations(long annotationTagBits) {
48
	private void addBinaryStandardAnnotations(long annotationTagBits) {
49
		if ((annotationTagBits & TagBits.AllStandardAnnotationsMask) == 0) {
50
			return;
51
		}
49
		if ((annotationTagBits & TagBits.AnnotationTargetMASK) != 0) {
52
		if ((annotationTagBits & TagBits.AnnotationTargetMASK) != 0) {
50
			char[][] compoundName = TypeConstants.JAVA_LANG_ANNOTATION_TARGET;
53
			char[][] compoundName = TypeConstants.JAVA_LANG_ANNOTATION_TARGET;
51
			addAnnotationTypeReference(compoundName[compoundName.length-1]);
54
			addAnnotationTypeReference(compoundName[compoundName.length-1]);
Lines 83-96 Link Here
83
		if ((annotationTagBits & TagBits.AnnotationPolymorphicSignature) != 0) {
86
		if ((annotationTagBits & TagBits.AnnotationPolymorphicSignature) != 0) {
84
			char[][] compoundName =
87
			char[][] compoundName =
85
					TypeConstants.JAVA_LANG_INVOKE_METHODHANDLE_$_POLYMORPHICSIGNATURE;
88
					TypeConstants.JAVA_LANG_INVOKE_METHODHANDLE_$_POLYMORPHICSIGNATURE;
86
			addAnnotationTypeReference(compoundName[compoundName.length-1]);
87
		}
88
		if ((annotationTagBits & TagBits.AnnotationPostConstruct) != 0) {
89
			char[][] compoundName = TypeConstants.JAVAX_ANNOTATION_POSTCONSTRUCT;
90
			addAnnotationTypeReference(compoundName[compoundName.length-1]);
91
		}
92
		if ((annotationTagBits & TagBits.AnnotationPreDestroy) != 0) {
93
			char[][] compoundName = TypeConstants.JAVAX_ANNOTATION_PREDESTROY;
94
			addAnnotationTypeReference(compoundName[compoundName.length-1]);
89
			addAnnotationTypeReference(compoundName[compoundName.length-1]);
95
		}
90
		}
96
	}
91
	}
(-)a/org.eclipse.jdt.core/search/org/eclipse/jdt/internal/core/search/indexing/DefaultJavaIndexer.java (+61 lines)
Added Link Here
1
/*******************************************************************************
2
 * Copyright (c) 2011 IBM Corporation and others.
3
 * All rights reserved. This program and the accompanying materials
4
 * are made available under the terms of the Eclipse Public License v1.0
5
 * which accompanies this distribution, and is available at
6
 * http://www.eclipse.org/legal/epl-v10.html
7
 *
8
 * Contributors:
9
 *     IBM Corporation - initial API and implementation
10
 *******************************************************************************/
11
package org.eclipse.jdt.internal.core.search.indexing;
12
13
import java.io.File;
14
import java.io.FileNotFoundException;
15
import java.io.IOException;
16
import java.util.Enumeration;
17
import java.util.zip.ZipEntry;
18
import java.util.zip.ZipFile;
19
20
import org.eclipse.core.runtime.Path;
21
import org.eclipse.jdt.core.search.IJavaSearchScope;
22
import org.eclipse.jdt.core.search.SearchEngine;
23
import org.eclipse.jdt.core.search.SearchParticipant;
24
import org.eclipse.jdt.internal.compiler.util.Util;
25
import org.eclipse.jdt.internal.core.index.FileIndexLocation;
26
import org.eclipse.jdt.internal.core.index.Index;
27
import org.eclipse.jdt.internal.core.index.IndexLocation;
28
import org.eclipse.jdt.internal.core.search.JavaSearchDocument;
29
30
public class DefaultJavaIndexer {
31
	private static final char JAR_SEPARATOR = IJavaSearchScope.JAR_FILE_ENTRY_SEPARATOR.charAt(0);
32
	
33
	public void generateIndexForJar(String pathToJar, String pathToIndexFile) throws IOException {
34
		File f = new File(pathToJar);
35
		if (!f.exists()) {
36
			throw new FileNotFoundException(pathToJar + " not found"); //$NON-NLS-1$
37
		}
38
		IndexLocation indexLocation = new FileIndexLocation(new File(pathToIndexFile));
39
		Index index = new Index(indexLocation, pathToJar, false /*reuse index file*/);
40
		SearchParticipant participant = SearchEngine.getDefaultSearchParticipant();
41
		index.separator = JAR_SEPARATOR;
42
		ZipFile zip = new ZipFile(pathToJar);
43
		try {
44
			for (Enumeration e = zip.entries(); e.hasMoreElements();) {
45
				// iterate each entry to index it
46
				ZipEntry ze = (ZipEntry) e.nextElement();
47
				String zipEntryName = ze.getName();
48
				if (Util.isClassFileName(zipEntryName)) {
49
					final byte[] classFileBytes = org.eclipse.jdt.internal.compiler.util.Util.getZipEntryByteContent(ze, zip);
50
					JavaSearchDocument entryDocument = new JavaSearchDocument(ze, new Path(pathToJar), classFileBytes, participant);
51
					entryDocument.setIndex(index);
52
					new BinaryIndexer(entryDocument).indexDocument();
53
				}
54
			}
55
			index.save();
56
		} finally {
57
			zip.close();
58
		}
59
		return;
60
	}
61
}
(-)a/org.eclipse.jdt.core/search/org/eclipse/jdt/internal/core/search/indexing/IndexAllProject.java (-3 / +3 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 77-83 Link Here
77
					if (entry.getEntryKind() == IClasspathEntry.CPE_LIBRARY && entry.getPath().equals(projectPath)) {
77
					if (entry.getEntryKind() == IClasspathEntry.CPE_LIBRARY && entry.getPath().equals(projectPath)) {
78
						// the project is also a library folder (see https://bugs.eclipse.org/bugs/show_bug.cgi?id=89815)
78
						// the project is also a library folder (see https://bugs.eclipse.org/bugs/show_bug.cgi?id=89815)
79
						// ensure a job exists to index it as a binary folder
79
						// ensure a job exists to index it as a binary folder
80
						this.manager.indexLibrary(projectPath, this.project);
80
						this.manager.indexLibrary(projectPath, this.project, ((ClasspathEntry)entry).getLibraryIndexLocation());
81
						return true;
81
						return true;
82
					}
82
					}
83
				}
83
				}
Lines 107-113 Link Here
107
				for (int i = 0; i < max; i++)
107
				for (int i = 0; i < max; i++)
108
					indexedFileNames.put(paths[i], DELETED);
108
					indexedFileNames.put(paths[i], DELETED);
109
			}
109
			}
110
			final long indexLastModified = max == 0 ? 0L : index.getIndexFile().lastModified();
110
			final long indexLastModified = max == 0 ? 0L : index.getIndexLastModified();
111
111
112
			IWorkspaceRoot root = this.project.getWorkspace().getRoot();
112
			IWorkspaceRoot root = this.project.getWorkspace().getRoot();
113
			for (int i = 0; i < sourceEntriesNumber; i++) {
113
			for (int i = 0; i < sourceEntriesNumber; i++) {
(-)a/org.eclipse.jdt.core/search/org/eclipse/jdt/internal/core/search/indexing/IndexBinaryFolder.java (-1 / +1 lines)
Lines 80-86 Link Here
80
				for (int i = 0; i < max; i++) {
80
				for (int i = 0; i < max; i++) {
81
					indexedFileNames.put(paths[i], DELETED);
81
					indexedFileNames.put(paths[i], DELETED);
82
				}
82
				}
83
				final long indexLastModified = index.getIndexFile().lastModified();
83
				final long indexLastModified = index.getIndexLastModified();
84
				this.folder.accept(
84
				this.folder.accept(
85
					new IResourceProxyVisitor() {
85
					new IResourceProxyVisitor() {
86
						public boolean visit(IResourceProxy proxy) throws CoreException {
86
						public boolean visit(IResourceProxy proxy) throws CoreException {
(-)a/org.eclipse.jdt.core/search/org/eclipse/jdt/internal/core/search/indexing/IndexManager.java (-87 / +177 lines)
Lines 1-5 Link Here
1
/*******************************************************************************
1
/*******************************************************************************
2
 * Copyright (c) 2000, 2010 IBM Corporation and others.
2
 * Copyright (c) 2000, 2012 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 11-16 Link Here
11
package org.eclipse.jdt.internal.core.search.indexing;
11
package org.eclipse.jdt.internal.core.search.indexing;
12
12
13
import java.io.*;
13
import java.io.*;
14
import java.net.URL;
14
import java.util.*;
15
import java.util.*;
15
import java.util.zip.CRC32;
16
import java.util.zip.CRC32;
16
17
Lines 52-57 Link Here
52
	/* can only replace a current state if its less than the new one */
53
	/* can only replace a current state if its less than the new one */
53
	// key = indexLocation path, value = index state integer
54
	// key = indexLocation path, value = index state integer
54
	private SimpleLookupTable indexStates = null;
55
	private SimpleLookupTable indexStates = null;
56
	private File indexNamesMapFile = new File(getSavedIndexesDirectory(), "indexNamesMap.txt"); //$NON-NLS-1$
55
	private File savedIndexNamesFile = new File(getSavedIndexesDirectory(), "savedIndexNames.txt"); //$NON-NLS-1$
57
	private File savedIndexNamesFile = new File(getSavedIndexesDirectory(), "savedIndexNames.txt"); //$NON-NLS-1$
56
	private File participantIndexNamesFile = new File(getSavedIndexesDirectory(), "participantsIndexNames.txt"); //$NON-NLS-1$
58
	private File participantIndexNamesFile = new File(getSavedIndexesDirectory(), "participantsIndexNames.txt"); //$NON-NLS-1$
57
	private boolean javaLikeNamesChanged = true;
59
	private boolean javaLikeNamesChanged = true;
Lines 59-64 Link Here
59
	public static final Integer UPDATING_STATE = new Integer(1);
61
	public static final Integer UPDATING_STATE = new Integer(1);
60
	public static final Integer UNKNOWN_STATE = new Integer(2);
62
	public static final Integer UNKNOWN_STATE = new Integer(2);
61
	public static final Integer REBUILDING_STATE = new Integer(3);
63
	public static final Integer REBUILDING_STATE = new Integer(3);
64
	public static final Integer REUSE_STATE = new Integer(4);
62
	
65
	
63
	// search participants who register indexes with the index manager
66
	// search participants who register indexes with the index manager
64
	private SimpleLookupTable participantsContainers = null;
67
	private SimpleLookupTable participantsContainers = null;
Lines 70-79 Link Here
70
	public synchronized void aboutToUpdateIndex(IPath containerPath, Integer newIndexState) {
73
	public synchronized void aboutToUpdateIndex(IPath containerPath, Integer newIndexState) {
71
	// newIndexState is either UPDATING_STATE or REBUILDING_STATE
74
	// newIndexState is either UPDATING_STATE or REBUILDING_STATE
72
	// must tag the index as inconsistent, in case we exit before the update job is started
75
	// must tag the index as inconsistent, in case we exit before the update job is started
73
	IPath indexLocation = computeIndexLocation(containerPath);
76
	IndexLocation indexLocation = computeIndexLocation(containerPath);
74
	Object state = getIndexStates().get(indexLocation);
77
	Object state = getIndexStates().get(indexLocation);
75
	Integer currentIndexState = state == null ? UNKNOWN_STATE : (Integer) state;
78
	Integer currentIndexState = state == null ? UNKNOWN_STATE : (Integer) state;
76
	if (currentIndexState.equals(REBUILDING_STATE)) return; // already rebuilding the index
79
	if (currentIndexState.compareTo(REBUILDING_STATE) >= 0) return; // already rebuilding the index
77
80
78
	int compare = newIndexState.compareTo(currentIndexState);
81
	int compare = newIndexState.compareTo(currentIndexState);
79
	if (compare > 0) {
82
	if (compare > 0) {
Lines 92-98 Link Here
92
	if (JavaCore.getPlugin() == null) return;
95
	if (JavaCore.getPlugin() == null) return;
93
	SearchParticipant participant = SearchEngine.getDefaultSearchParticipant();
96
	SearchParticipant participant = SearchEngine.getDefaultSearchParticipant();
94
	SearchDocument document = participant.getDocument(resource.getFullPath().toString());
97
	SearchDocument document = participant.getDocument(resource.getFullPath().toString());
95
	IPath indexLocation = computeIndexLocation(containerPath);
98
	IndexLocation indexLocation = computeIndexLocation(containerPath);
96
	scheduleDocumentIndexing(document, containerPath, indexLocation, participant);
99
	scheduleDocumentIndexing(document, containerPath, indexLocation, participant);
97
}
100
}
98
/**
101
/**
Lines 104-110 Link Here
104
	SearchParticipant participant = SearchEngine.getDefaultSearchParticipant();
107
	SearchParticipant participant = SearchEngine.getDefaultSearchParticipant();
105
	SearchDocument document = participant.getDocument(resource.getFullPath().toString());
108
	SearchDocument document = participant.getDocument(resource.getFullPath().toString());
106
	document.setParser(parser);
109
	document.setParser(parser);
107
	IPath indexLocation = computeIndexLocation(containerPath);
110
	IndexLocation indexLocation = computeIndexLocation(containerPath);
108
	scheduleDocumentIndexing(document, containerPath, indexLocation, participant);
111
	scheduleDocumentIndexing(document, containerPath, indexLocation, participant);
109
}
112
}
110
/*
113
/*
Lines 116-132 Link Here
116
	PatternSearchJob job = new PatternSearchJob(null, SearchEngine.getDefaultSearchParticipant(), scope, null);
119
	PatternSearchJob job = new PatternSearchJob(null, SearchEngine.getDefaultSearchParticipant(), scope, null);
117
	Index[] selectedIndexes = job.getIndexes(null);
120
	Index[] selectedIndexes = job.getIndexes(null);
118
	for (int i = 0, l = selectedIndexes.length; i < l; i++) {
121
	for (int i = 0, l = selectedIndexes.length; i < l; i++) {
119
		String path = selectedIndexes[i].getIndexFile().getAbsolutePath();
122
		IndexLocation IndexLocation = selectedIndexes[i].getIndexLocation();
120
		knownPaths.add(path);
123
		knownPaths.add(IndexLocation);
121
	}
124
	}
122
125
123
	if (this.indexStates != null) {
126
	if (this.indexStates != null) {
124
		Object[] keys = this.indexStates.keyTable;
127
		Object[] keys = this.indexStates.keyTable;
125
		IPath[] locations = new IPath[this.indexStates.elementSize];
128
		IndexLocation[] locations = new IndexLocation[this.indexStates.elementSize];
126
		int count = 0;
129
		int count = 0;
127
		for (int i = 0, l = keys.length; i < l; i++) {
130
		for (int i = 0, l = keys.length; i < l; i++) {
128
			IPath key = (IPath) keys[i];
131
			IndexLocation key = (IndexLocation) keys[i];
129
			if (key != null && !knownPaths.includes(key.toOSString()))
132
			if (key != null && !knownPaths.includes(key))
130
				locations[count++] = key;
133
				locations[count++] = key;
131
		}
134
		}
132
		if (count > 0)
135
		if (count > 0)
Lines 134-141 Link Here
134
	}
137
	}
135
	deleteIndexFiles(knownPaths);
138
	deleteIndexFiles(knownPaths);
136
}
139
}
137
public synchronized IPath computeIndexLocation(IPath containerPath) {
140
public synchronized IndexLocation computeIndexLocation(IPath containerPath) {
138
	IPath indexLocation = (IPath) this.indexLocations.get(containerPath);
141
	IndexLocation indexLocation = (IndexLocation) this.indexLocations.get(containerPath);
139
	if (indexLocation == null) {
142
	if (indexLocation == null) {
140
		String pathString = containerPath.toOSString();
143
		String pathString = containerPath.toOSString();
141
		CRC32 checksumCalculator = new CRC32();
144
		CRC32 checksumCalculator = new CRC32();
Lines 144-150 Link Here
144
		if (VERBOSE)
147
		if (VERBOSE)
145
			Util.verbose("-> index name for " + pathString + " is " + fileName); //$NON-NLS-1$ //$NON-NLS-2$
148
			Util.verbose("-> index name for " + pathString + " is " + fileName); //$NON-NLS-1$ //$NON-NLS-2$
146
		// to share the indexLocation between the indexLocations and indexStates tables, get the key from the indexStates table
149
		// to share the indexLocation between the indexLocations and indexStates tables, get the key from the indexStates table
147
		indexLocation = (IPath) getIndexStates().getKey(getJavaPluginWorkingLocation().append(fileName));
150
		indexLocation = (IndexLocation) getIndexStates().getKey(new FileIndexLocation(new File(getSavedIndexesDirectory(), fileName)));
148
		this.indexLocations.put(containerPath, indexLocation);
151
		this.indexLocations.put(containerPath, indexLocation);
149
	}
152
	}
150
	return indexLocation;
153
	return indexLocation;
Lines 161-167 Link Here
161
164
162
	for (int i = 0, l = indexesFiles.length; i < l; i++) {
165
	for (int i = 0, l = indexesFiles.length; i < l; i++) {
163
		String fileName = indexesFiles[i].getAbsolutePath();
166
		String fileName = indexesFiles[i].getAbsolutePath();
164
		if (pathsToKeep != null && pathsToKeep.includes(fileName)) continue;
167
		if (pathsToKeep != null && pathsToKeep.includes(new FileIndexLocation(indexesFiles[i]))) continue;
165
		String suffix = ".index"; //$NON-NLS-1$
168
		String suffix = ".index"; //$NON-NLS-1$
166
		if (fileName.regionMatches(true, fileName.length() - suffix.length(), suffix, 0, suffix.length())) {
169
		if (fileName.regionMatches(true, fileName.length() - suffix.length(), suffix, 0, suffix.length())) {
167
			if (VERBOSE || DEBUG)
170
			if (VERBOSE || DEBUG)
Lines 173-179 Link Here
173
/*
176
/*
174
 * Creates an empty index at the given location, for the given container path, if none exist.
177
 * Creates an empty index at the given location, for the given container path, if none exist.
175
 */
178
 */
176
public synchronized void ensureIndexExists(IPath indexLocation, IPath containerPath) {
179
public synchronized void ensureIndexExists(IndexLocation indexLocation, IPath containerPath) {
177
	SimpleLookupTable states = getIndexStates();
180
	SimpleLookupTable states = getIndexStates();
178
	Object state = states.get(indexLocation);
181
	Object state = states.get(indexLocation);
179
	if (state == null) {
182
	if (state == null) {
Lines 207-213 Link Here
207
 * @param indexLocation The path of the index file
210
 * @param indexLocation The path of the index file
208
 * @return The corresponding index or <code>null</code> if not found
211
 * @return The corresponding index or <code>null</code> if not found
209
 */
212
 */
210
public synchronized Index getIndex(IPath indexLocation) {
213
public synchronized Index getIndex(IndexLocation indexLocation) {
211
	return (Index) this.indexes.get(indexLocation); // is null if unknown, call if the containerPath must be computed
214
	return (Index) this.indexes.get(indexLocation); // is null if unknown, call if the containerPath must be computed
212
}
215
}
213
/**
216
/**
Lines 219-225 Link Here
219
 * Warning: Does not check whether index is consistent (not being used)
222
 * Warning: Does not check whether index is consistent (not being used)
220
 */
223
 */
221
public synchronized Index getIndex(IPath containerPath, boolean reuseExistingFile, boolean createIfMissing) {
224
public synchronized Index getIndex(IPath containerPath, boolean reuseExistingFile, boolean createIfMissing) {
222
	IPath indexLocation = computeIndexLocation(containerPath);
225
	IndexLocation indexLocation = computeIndexLocation(containerPath);
223
	return getIndex(containerPath, indexLocation, reuseExistingFile, createIfMissing);
226
	return getIndex(containerPath, indexLocation, reuseExistingFile, createIfMissing);
224
}
227
}
225
/**
228
/**
Lines 230-236 Link Here
230
 *
233
 *
231
 * Warning: Does not check whether index is consistent (not being used)
234
 * Warning: Does not check whether index is consistent (not being used)
232
 */
235
 */
233
public synchronized Index getIndex(IPath containerPath, IPath indexLocation, boolean reuseExistingFile, boolean createIfMissing) {
236
public synchronized Index getIndex(IPath containerPath, IndexLocation indexLocation, boolean reuseExistingFile, boolean createIfMissing) {
234
	// Path is already canonical per construction
237
	// Path is already canonical per construction
235
	Index index = getIndex(indexLocation);
238
	Index index = getIndex(indexLocation);
236
	if (index == null) {
239
	if (index == null) {
Lines 245-263 Link Here
245
248
246
		// index isn't cached, consider reusing an existing index file
249
		// index isn't cached, consider reusing an existing index file
247
		String containerPathString = containerPath.getDevice() == null ? containerPath.toString() : containerPath.toOSString();
250
		String containerPathString = containerPath.getDevice() == null ? containerPath.toString() : containerPath.toOSString();
248
		String indexLocationString = indexLocation.toOSString();
249
		if (reuseExistingFile) {
251
		if (reuseExistingFile) {
250
			File indexFile = new File(indexLocationString);
252
			if (indexLocation.exists()) { // check before creating index so as to avoid creating a new empty index if file is missing
251
			if (indexFile.exists()) { // check before creating index so as to avoid creating a new empty index if file is missing
252
				try {
253
				try {
253
					index = new Index(indexLocationString, containerPathString, true /*reuse index file*/);
254
					index = new Index(indexLocation, containerPathString, true /*reuse index file*/);
254
					this.indexes.put(indexLocation, index);
255
					this.indexes.put(indexLocation, index);
255
					return index;
256
					return index;
256
				} catch (IOException e) {
257
				} catch (IOException e) {
257
					// failed to read the existing file or its no longer compatible
258
					// failed to read the existing file or its no longer compatible
258
					if (currentIndexState != REBUILDING_STATE) { // rebuild index if existing file is corrupt, unless the index is already being rebuilt
259
					if (currentIndexState != REBUILDING_STATE && currentIndexState != REUSE_STATE) { // rebuild index if existing file is corrupt, unless the index is already being rebuilt
259
						if (VERBOSE)
260
						if (VERBOSE)
260
							Util.verbose("-> cannot reuse existing index: "+indexLocationString+" path: "+containerPathString); //$NON-NLS-1$ //$NON-NLS-2$
261
							Util.verbose("-> cannot reuse existing index: "+indexLocation+" path: "+containerPathString); //$NON-NLS-1$ //$NON-NLS-2$
261
						rebuildIndex(indexLocation, containerPath);
262
						rebuildIndex(indexLocation, containerPath);
262
						return null;
263
						return null;
263
					}
264
					}
Lines 268-285 Link Here
268
				rebuildIndex(indexLocation, containerPath);
269
				rebuildIndex(indexLocation, containerPath);
269
				return null;
270
				return null;
270
			}
271
			}
272
			if (currentIndexState == REUSE_STATE) {
273
				// supposed to be in reuse state but error in the index file, so reindex.
274
				if (VERBOSE)
275
					Util.verbose("-> cannot reuse given index: "+indexLocation+" path: "+containerPathString); //$NON-NLS-1$ //$NON-NLS-2$
276
				this.indexLocations.put(containerPath, null);
277
				indexLocation = computeIndexLocation(containerPath);
278
				rebuildIndex(indexLocation, containerPath);
279
				return null;
280
			}
271
		}
281
		}
272
		// index wasn't found on disk, consider creating an empty new one
282
		// index wasn't found on disk, consider creating an empty new one
273
		if (createIfMissing) {
283
		if (createIfMissing) {
274
			try {
284
			try {
275
				if (VERBOSE)
285
				if (VERBOSE)
276
					Util.verbose("-> create empty index: "+indexLocationString+" path: "+containerPathString); //$NON-NLS-1$ //$NON-NLS-2$
286
					Util.verbose("-> create empty index: "+indexLocation+" path: "+containerPathString); //$NON-NLS-1$ //$NON-NLS-2$
277
				index = new Index(indexLocationString, containerPathString, false /*do not reuse index file*/);
287
				index = new Index(indexLocation, containerPathString, false /*do not reuse index file*/);
278
				this.indexes.put(indexLocation, index);
288
				this.indexes.put(indexLocation, index);
279
				return index;
289
				return index;
280
			} catch (IOException e) {
290
			} catch (IOException e) {
281
				if (VERBOSE)
291
				if (VERBOSE)
282
					Util.verbose("-> unable to create empty index: "+indexLocationString+" path: "+containerPathString); //$NON-NLS-1$ //$NON-NLS-2$
292
					Util.verbose("-> unable to create empty index: "+indexLocation+" path: "+containerPathString); //$NON-NLS-1$ //$NON-NLS-2$
283
				// The file could not be created. Possible reason: the project has been deleted.
293
				// The file could not be created. Possible reason: the project has been deleted.
284
				return null;
294
				return null;
285
			}
295
			}
Lines 295-301 Link Here
295
 * @param locations The list of of the index files path
305
 * @param locations The list of of the index files path
296
 * @return The corresponding indexes list.
306
 * @return The corresponding indexes list.
297
 */
307
 */
298
public Index[] getIndexes(IPath[] locations, IProgressMonitor progressMonitor) {
308
public Index[] getIndexes(IndexLocation[] locations, IProgressMonitor progressMonitor) {
299
	// acquire the in-memory indexes on the fly
309
	// acquire the in-memory indexes on the fly
300
	int length = locations.length;
310
	int length = locations.length;
301
	Index[] locatedIndexes = new Index[length];
311
	Index[] locatedIndexes = new Index[length];
Lines 308-314 Link Here
308
			throw new OperationCanceledException();
318
			throw new OperationCanceledException();
309
		}
319
		}
310
		// may trigger some index recreation work
320
		// may trigger some index recreation work
311
		IPath indexLocation = locations[i];
321
		IndexLocation indexLocation = locations[i];
312
		Index index = getIndex(indexLocation);
322
		Index index = getIndex(indexLocation);
313
		if (index == null) {
323
		if (index == null) {
314
			// only need containerPath if the index must be built
324
			// only need containerPath if the index must be built
Lines 330-347 Link Here
330
					index = null;
340
					index = null;
331
				}
341
				}
332
			} else {
342
			} else {
333
				if (!getJavaPluginWorkingLocation().isPrefixOf(indexLocation)) { // the index belongs to non-jdt search participant
343
				if (indexLocation.isParticipantIndex() && indexLocation.exists()) { // the index belongs to non-jdt search participant
334
					if (indexLocation.toFile().exists()) { 
344
					try {
335
						try {
345
						IPath container = getParticipantsContainer(indexLocation);
336
							IPath container = getParticipantsContainer(indexLocation);
346
						if (container != null) {
337
							if (container != null) {
347
							index = new Index(indexLocation, container.toOSString(), true /*reuse index file*/);
338
								index = new Index(indexLocation.toOSString(), container.toOSString(), true /*reuse index file*/);
348
							this.indexes.put(indexLocation, index);
339
								this.indexes.put(indexLocation, index);
340
							}
341
						} catch (IOException e) {
342
							// ignore
343
						}
349
						}
344
					} 
350
					} catch (IOException e) {
351
						// ignore
352
					}
345
				}
353
				}
346
			}
354
			}
347
		}
355
		}
Lines 358-364 Link Here
358
	return locatedIndexes;
366
	return locatedIndexes;
359
}
367
}
360
public synchronized Index getIndexForUpdate(IPath containerPath, boolean reuseExistingFile, boolean createIfMissing) {
368
public synchronized Index getIndexForUpdate(IPath containerPath, boolean reuseExistingFile, boolean createIfMissing) {
361
	IPath indexLocation = computeIndexLocation(containerPath);
369
	IndexLocation indexLocation = computeIndexLocation(containerPath);
362
	if (getIndexStates().get(indexLocation) == REBUILDING_STATE)
370
	if (getIndexStates().get(indexLocation) == REBUILDING_STATE)
363
		return getIndex(containerPath, indexLocation, reuseExistingFile, createIfMissing);
371
		return getIndex(containerPath, indexLocation, reuseExistingFile, createIfMissing);
364
372
Lines 368-380 Link Here
368
	if (this.indexStates != null) return this.indexStates;
376
	if (this.indexStates != null) return this.indexStates;
369
377
370
	this.indexStates = new SimpleLookupTable();
378
	this.indexStates = new SimpleLookupTable();
371
	IPath indexesDirectoryPath = getJavaPluginWorkingLocation();
379
	File indexesDirectoryPath = getSavedIndexesDirectory();
372
	char[][] savedNames = readIndexState(indexesDirectoryPath.toOSString());
380
	char[][] savedNames = readIndexState(getJavaPluginWorkingLocation().toOSString());
373
	if (savedNames != null) {
381
	if (savedNames != null) {
374
		for (int i = 1, l = savedNames.length; i < l; i++) { // first name is saved signature, see readIndexState()
382
		for (int i = 1, l = savedNames.length; i < l; i++) { // first name is saved signature, see readIndexState()
375
			char[] savedName = savedNames[i];
383
			char[] savedName = savedNames[i];
376
			if (savedName.length > 0) {
384
			if (savedName.length > 0) {
377
				IPath indexLocation = indexesDirectoryPath.append(new String(savedName)); // shares indexesDirectoryPath's segments
385
				IndexLocation indexLocation = new FileIndexLocation(new File(indexesDirectoryPath, String.valueOf(savedName))); // shares indexesDirectoryPath's segments
378
				if (VERBOSE)
386
				if (VERBOSE)
379
					Util.verbose("Reading saved index file " + indexLocation); //$NON-NLS-1$
387
					Util.verbose("Reading saved index file " + indexLocation); //$NON-NLS-1$
380
				this.indexStates.put(indexLocation, SAVED_STATE);
388
				this.indexStates.put(indexLocation, SAVED_STATE);
Lines 387-395 Link Here
387
		this.javaLikeNamesChanged = false;
395
		this.javaLikeNamesChanged = false;
388
		deleteIndexFiles();
396
		deleteIndexFiles();
389
	}
397
	}
398
	readIndexMap();
390
	return this.indexStates;
399
	return this.indexStates;
391
}
400
}
392
private IPath getParticipantsContainer(IPath indexLocation) {
401
private IPath getParticipantsContainer(IndexLocation indexLocation) {
393
	if (this.participantsContainers == null) {
402
	if (this.participantsContainers == null) {
394
		readParticipantsIndexNamesFile();
403
		readParticipantsIndexNamesFile();
395
	}
404
	}
Lines 474-480 Link Here
474
		for (int i = 0; i < entries.length; i++) {
483
		for (int i = 0; i < entries.length; i++) {
475
			IClasspathEntry entry= entries[i];
484
			IClasspathEntry entry= entries[i];
476
			if (entry.getEntryKind() == IClasspathEntry.CPE_LIBRARY)
485
			if (entry.getEntryKind() == IClasspathEntry.CPE_LIBRARY)
477
				indexLibrary(entry.getPath(), project);
486
				indexLibrary(entry.getPath(), project, ((ClasspathEntry)entry).getLibraryIndexLocation());
478
		}
487
		}
479
	} catch(JavaModelException e){ // cannot retrieve classpath info
488
	} catch(JavaModelException e){ // cannot retrieve classpath info
480
	}
489
	}
Lines 488-503 Link Here
488
 * Trigger addition of a library to an index
497
 * Trigger addition of a library to an index
489
 * Note: the actual operation is performed in background
498
 * Note: the actual operation is performed in background
490
 */
499
 */
491
public void indexLibrary(IPath path, IProject requestingProject) {
500
public void indexLibrary(IPath path, IProject requestingProject, URL indexURL) {
492
	// requestingProject is no longer used to cancel jobs but leave it here just in case
501
	// requestingProject is no longer used to cancel jobs but leave it here just in case
502
	IndexLocation indexFile = indexURL != null ? IndexLocation.createIndexLocation(indexURL): null;
493
	if (JavaCore.getPlugin() == null) return;
503
	if (JavaCore.getPlugin() == null) return;
494
495
	Object target = JavaModel.getTarget(path, true);
496
	IndexRequest request = null;
504
	IndexRequest request = null;
505
	Object target = JavaModel.getTarget(path, true);
497
	if (target instanceof IFile) {
506
	if (target instanceof IFile) {
498
		request = new AddJarFileToIndex((IFile) target, this);
507
		request = new AddJarFileToIndex((IFile) target, indexFile, this);
499
	} else if (target instanceof File) {
508
	} else if (target instanceof File) {
500
		request = new AddJarFileToIndex(path, this);
509
		request = new AddJarFileToIndex(path, indexFile, this);
501
	} else if (target instanceof IContainer) {
510
	} else if (target instanceof IContainer) {
502
		request = new IndexBinaryFolder((IContainer) target, this);
511
		request = new IndexBinaryFolder((IContainer) target, this);
503
	} else {
512
	} else {
Lines 508-513 Link Here
508
	if (!isJobWaiting(request))
517
	if (!isJobWaiting(request))
509
		request(request);
518
		request(request);
510
}
519
}
520
521
synchronized boolean addIndex(IPath containerPath, IndexLocation indexFile) {
522
	getIndexStates().put(indexFile, REUSE_STATE);
523
	this.indexLocations.put(containerPath, indexFile);
524
	Index index = getIndex(containerPath, indexFile, true, false);
525
	if (index == null) {
526
		indexFile.close();
527
		this.indexLocations.put(containerPath, null);
528
		return false;
529
	}
530
	writeIndexMapFile();
531
	return true;
532
}
533
511
/**
534
/**
512
 * Index the content of the given source folder.
535
 * Index the content of the given source folder.
513
 */
536
 */
Lines 522-528 Link Here
522
	request(new AddFolderToIndex(sourceFolder, project, inclusionPatterns, exclusionPatterns, this));
545
	request(new AddFolderToIndex(sourceFolder, project, inclusionPatterns, exclusionPatterns, this));
523
}
546
}
524
public synchronized void jobWasCancelled(IPath containerPath) {
547
public synchronized void jobWasCancelled(IPath containerPath) {
525
	IPath indexLocation = computeIndexLocation(containerPath);
548
	IndexLocation indexLocation = computeIndexLocation(containerPath);
526
	Index index = getIndex(indexLocation);
549
	Index index = getIndex(indexLocation);
527
	if (index != null) {
550
	if (index != null) {
528
		index.monitor = null;
551
		index.monitor = null;
Lines 568-574 Link Here
568
	}
591
	}
569
	return null;
592
	return null;
570
}
593
}
571
private void rebuildIndex(IPath indexLocation, IPath containerPath) {
594
private void rebuildIndex(IndexLocation indexLocation, IPath containerPath) {
572
	Object target = JavaModel.getTarget(containerPath, true);
595
	Object target = JavaModel.getTarget(containerPath, true);
573
	if (target == null) return;
596
	if (target == null) return;
574
597
Lines 584-592 Link Here
584
	} else if (target instanceof IFolder) {
607
	} else if (target instanceof IFolder) {
585
		request = new IndexBinaryFolder((IFolder) target, this);
608
		request = new IndexBinaryFolder((IFolder) target, this);
586
	} else if (target instanceof IFile) {
609
	} else if (target instanceof IFile) {
587
		request = new AddJarFileToIndex((IFile) target, this);
610
		request = new AddJarFileToIndex((IFile) target, null, this);
588
	} else if (target instanceof File) {
611
	} else if (target instanceof File) {
589
		request = new AddJarFileToIndex(containerPath, this);
612
		request = new AddJarFileToIndex(containerPath, null, this);
590
	}
613
	}
591
	if (request != null)
614
	if (request != null)
592
		request(request);
615
		request(request);
Lines 601-613 Link Here
601
	String containerPathString = containerPath.getDevice() == null ? containerPath.toString() : containerPath.toOSString();
624
	String containerPathString = containerPath.getDevice() == null ? containerPath.toString() : containerPath.toOSString();
602
	try {
625
	try {
603
		// Path is already canonical
626
		// Path is already canonical
604
		IPath indexLocation = computeIndexLocation(containerPath);
627
		IndexLocation indexLocation = computeIndexLocation(containerPath);
605
		Index index = getIndex(indexLocation);
628
		Index index = getIndex(indexLocation);
606
		ReadWriteMonitor monitor = index == null ? null : index.monitor;
629
		ReadWriteMonitor monitor = index == null ? null : index.monitor;
607
630
608
		if (VERBOSE)
631
		if (VERBOSE)
609
			Util.verbose("-> recreating index: "+indexLocation+" for path: "+containerPathString); //$NON-NLS-1$ //$NON-NLS-2$
632
			Util.verbose("-> recreating index: "+indexLocation+" for path: "+containerPathString); //$NON-NLS-1$ //$NON-NLS-2$
610
		index = new Index(indexLocation.toOSString(), containerPathString, false /*do not reuse index file*/);
633
		index = new Index(indexLocation, containerPathString, false /*do not reuse index file*/);
611
		this.indexes.put(indexLocation, index);
634
		this.indexes.put(indexLocation, index);
612
		index.monitor = monitor;
635
		index.monitor = monitor;
613
		return index;
636
		return index;
Lines 634-640 Link Here
634
public synchronized void removeIndex(IPath containerPath) {
657
public synchronized void removeIndex(IPath containerPath) {
635
	if (VERBOSE || DEBUG)
658
	if (VERBOSE || DEBUG)
636
		Util.verbose("removing index " + containerPath); //$NON-NLS-1$
659
		Util.verbose("removing index " + containerPath); //$NON-NLS-1$
637
	IPath indexLocation = computeIndexLocation(containerPath);
660
	IndexLocation indexLocation = computeIndexLocation(containerPath);
638
	Index index = getIndex(indexLocation);
661
	Index index = getIndex(indexLocation);
639
	File indexFile = null;
662
	File indexFile = null;
640
	if (index != null) {
663
	if (index != null) {
Lines 642-649 Link Here
642
		indexFile = index.getIndexFile();
665
		indexFile = index.getIndexFile();
643
	}
666
	}
644
	if (indexFile == null)
667
	if (indexFile == null)
645
		indexFile = new File(indexLocation.toOSString()); // index is not cached yet, but still want to delete the file
668
		indexFile = indexLocation.getIndexFile(); // index is not cached yet, but still want to delete the file
646
	if (indexFile.exists()) {
669
	if (this.indexStates.get(indexLocation) == REUSE_STATE) {
670
		indexLocation.close();
671
		this.indexLocations.put(containerPath, null);
672
	} else if (indexFile != null && indexFile.exists()) {
647
		if (DEBUG)
673
		if (DEBUG)
648
			Util.verbose("removing index file " + indexFile); //$NON-NLS-1$
674
			Util.verbose("removing index file " + indexFile); //$NON-NLS-1$
649
		indexFile.delete();
675
		indexFile.delete();
Lines 659-682 Link Here
659
		Util.verbose("removing index path " + path); //$NON-NLS-1$
685
		Util.verbose("removing index path " + path); //$NON-NLS-1$
660
	Object[] keyTable = this.indexes.keyTable;
686
	Object[] keyTable = this.indexes.keyTable;
661
	Object[] valueTable = this.indexes.valueTable;
687
	Object[] valueTable = this.indexes.valueTable;
662
	IPath[] locations = null;
688
	IndexLocation[] locations = null;
663
	int max = this.indexes.elementSize;
689
	int max = this.indexes.elementSize;
664
	int count = 0;
690
	int count = 0;
665
	for (int i = 0, l = keyTable.length; i < l; i++) {
691
	for (int i = 0, l = keyTable.length; i < l; i++) {
666
		IPath indexLocation = (IPath) keyTable[i];
692
		IndexLocation indexLocation = (IndexLocation) keyTable[i];
667
		if (indexLocation == null)
693
		if (indexLocation == null)
668
			continue;
694
			continue;
669
		if (path.isPrefixOf(indexLocation)) {
695
		if (indexLocation.startsWith(path)) {
670
			Index index = (Index) valueTable[i];
696
			Index index = (Index) valueTable[i];
671
			index.monitor = null;
697
			index.monitor = null;
672
			if (locations == null)
698
			if (locations == null)
673
				locations = new IPath[max];
699
				locations = new IndexLocation[max];
674
			locations[count++] = indexLocation;
700
			locations[count++] = indexLocation;
675
			File indexFile = index.getIndexFile();
701
			if (this.indexStates.get(indexLocation) == REUSE_STATE) {
676
			if (indexFile.exists()) {
702
				indexLocation.close();
703
			} else {
677
				if (DEBUG)
704
				if (DEBUG)
678
					Util.verbose("removing index file " + indexFile); //$NON-NLS-1$
705
					Util.verbose("removing index file " + indexLocation); //$NON-NLS-1$
679
				indexFile.delete();
706
				indexLocation.delete();
680
			}
707
			}
681
		} else {
708
		} else {
682
			max--;
709
			max--;
Lines 686-694 Link Here
686
		for (int i = 0; i < count; i++)
713
		for (int i = 0; i < count; i++)
687
			this.indexes.removeKey(locations[i]);
714
			this.indexes.removeKey(locations[i]);
688
		removeIndexesState(locations);
715
		removeIndexesState(locations);
689
		if (this.participantsContainers != null && this.participantsContainers.get(path.toOSString()) != null) {
716
		if (this.participantsContainers != null) {
690
			this.participantsContainers.removeKey(path.toOSString());	
717
			boolean update = false;
691
			writeParticipantsIndexNamesFile();
718
			for (int i = 0; i < count; i++) {
719
				if (this.participantsContainers.get(locations[i]) != null) {
720
					update = true;
721
					this.participantsContainers.removeKey(locations[i]);
722
				}
723
			}
724
			if (update) writeParticipantsIndexNamesFile();
692
		}
725
		}
693
	}
726
	}
694
}
727
}
Lines 746-752 Link Here
746
	String containerPathString = containerPath.getDevice() == null ? containerPath.toString() : containerPath.toOSString();
779
	String containerPathString = containerPath.getDevice() == null ? containerPath.toString() : containerPath.toOSString();
747
	try {
780
	try {
748
		// Path is already canonical
781
		// Path is already canonical
749
		IPath indexLocation = computeIndexLocation(containerPath);
782
		IndexLocation indexLocation = computeIndexLocation(containerPath);
750
		Index index = getIndex(indexLocation);
783
		Index index = getIndex(indexLocation);
751
		if (VERBOSE) {
784
		if (VERBOSE) {
752
			Util.verbose("-> reseting index: "+indexLocation+" for path: "+containerPathString); //$NON-NLS-1$ //$NON-NLS-2$
785
			Util.verbose("-> reseting index: "+indexLocation+" for path: "+containerPathString); //$NON-NLS-1$ //$NON-NLS-2$
Lines 770-776 Link Here
770
	// must have permission to write from the write monitor
803
	// must have permission to write from the write monitor
771
	if (index.hasChanged()) {
804
	if (index.hasChanged()) {
772
		if (VERBOSE)
805
		if (VERBOSE)
773
			Util.verbose("-> saving index " + index.getIndexFile()); //$NON-NLS-1$
806
			Util.verbose("-> saving index " + index.getIndexLocation()); //$NON-NLS-1$
774
		index.save();
807
		index.save();
775
	}
808
	}
776
	synchronized (this) {
809
	synchronized (this) {
Lines 782-788 Link Here
782
					if (((IndexRequest) job).containerPath.equals(containerPath)) return;
815
					if (((IndexRequest) job).containerPath.equals(containerPath)) return;
783
			}
816
			}
784
		}
817
		}
785
		IPath indexLocation = computeIndexLocation(containerPath);
818
		IndexLocation indexLocation = computeIndexLocation(containerPath);
786
		updateIndexState(indexLocation, SAVED_STATE);
819
		updateIndexState(indexLocation, SAVED_STATE);
787
	}
820
	}
788
}
821
}
Lines 837-843 Link Here
837
	}
870
	}
838
	this.needToSave = !allSaved;
871
	this.needToSave = !allSaved;
839
}
872
}
840
public void scheduleDocumentIndexing(final SearchDocument searchDocument, IPath container, final IPath indexLocation, final SearchParticipant searchParticipant) {
873
public void scheduleDocumentIndexing(final SearchDocument searchDocument, IPath container, final IndexLocation indexLocation, final SearchParticipant searchParticipant) {
841
	request(new IndexRequest(container, this) {
874
	request(new IndexRequest(container, this) {
842
		public boolean execute(IProgressMonitor progressMonitor) {
875
		public boolean execute(IProgressMonitor progressMonitor) {
843
			if (this.isCancelled || progressMonitor != null && progressMonitor.isCanceled()) return true;
876
			if (this.isCancelled || progressMonitor != null && progressMonitor.isCanceled()) return true;
Lines 850-856 Link Here
850
883
851
			try {
884
			try {
852
				monitor.enterWrite(); // ask permission to write
885
				monitor.enterWrite(); // ask permission to write
853
				indexDocument(searchDocument, searchParticipant, index, indexLocation);
886
				indexDocument(searchDocument, searchParticipant, index, new Path(indexLocation.getCanonicalFilePath()));
854
			} finally {
887
			} finally {
855
				monitor.exitWrite(); // free write lock
888
				monitor.exitWrite(); // free write lock
856
			}
889
			}
Lines 876-881 Link Here
876
	return buffer.toString();
909
	return buffer.toString();
877
}
910
}
878
911
912
private void readIndexMap() {
913
	try {
914
		char[] indexMaps = org.eclipse.jdt.internal.compiler.util.Util.getFileCharContent(this.indexNamesMapFile, null);
915
		char[][] names = CharOperation.splitOn('\n', indexMaps);
916
		if (names.length >= 3) {
917
			// First line is DiskIndex signature (see writeIndexMapFile())
918
			String savedSignature = DiskIndex.SIGNATURE;
919
			if (savedSignature.equals(new String(names[0]))) {
920
				for (int i = 1, l = names.length-1 ; i < l ; i+=2) {
921
					IndexLocation indexPath = IndexLocation.createIndexLocation(new URL(new String(names[i])));
922
					this.indexLocations.put(new Path(new String(names[i+1])), indexPath );
923
					this.indexStates.put(indexPath, REUSE_STATE);
924
				}
925
			}		
926
		}
927
	} catch (IOException ignored) {
928
		if (VERBOSE)
929
			Util.verbose("Failed to read saved index file names"); //$NON-NLS-1$
930
	}
931
	return;
932
}
879
private char[][] readIndexState(String dirOSString) {
933
private char[][] readIndexState(String dirOSString) {
880
	try {
934
	try {
881
		char[] savedIndexNames = org.eclipse.jdt.internal.compiler.util.Util.getFileCharContent(this.savedIndexNamesFile, null);
935
		char[] savedIndexNames = org.eclipse.jdt.internal.compiler.util.Util.getFileCharContent(this.savedIndexNamesFile, null);
Lines 904-910 Link Here
904
				// First line is DiskIndex signature  (see writeParticipantsIndexNamesFile())
958
				// First line is DiskIndex signature  (see writeParticipantsIndexNamesFile())
905
				if (DiskIndex.SIGNATURE.equals(new String(names[0]))) {					
959
				if (DiskIndex.SIGNATURE.equals(new String(names[0]))) {					
906
					for (int i = 1, l = names.length-1 ; i < l ; i+=2) {
960
					for (int i = 1, l = names.length-1 ; i < l ; i+=2) {
907
						containers.put(new Path(new String(names[i])), new Path(new String(names[i+1])));
961
						IndexLocation indexLocation = new FileIndexLocation(new File(new String(names[i])), true);
962
						containers.put(indexLocation, new Path(new String(names[i+1])));
908
					}
963
					}
909
				}				
964
				}				
910
			}
965
			}
Lines 916-922 Link Here
916
	this.participantsContainers = containers;
971
	this.participantsContainers = containers;
917
	return;
972
	return;
918
}
973
}
919
private synchronized void removeIndexesState(IPath[] locations) {
974
private synchronized void removeIndexesState(IndexLocation[] locations) {
920
	getIndexStates(); // ensure the states are initialized
975
	getIndexStates(); // ensure the states are initialized
921
	int length = locations.length;
976
	int length = locations.length;
922
	boolean changed = false;
977
	boolean changed = false;
Lines 932-940 Link Here
932
	if (!changed) return;
987
	if (!changed) return;
933
988
934
	writeSavedIndexNamesFile();
989
	writeSavedIndexNamesFile();
990
	writeIndexMapFile();
935
}
991
}
936
private synchronized void updateIndexState(IPath indexLocation, Integer indexState) {
992
private synchronized void updateIndexState(IndexLocation indexLocation, Integer indexState) {
937
	if (indexLocation.isEmpty())
993
	if (indexLocation == null)
938
		throw new IllegalArgumentException();
994
		throw new IllegalArgumentException();
939
995
940
	getIndexStates(); // ensure the states are initialized
996
	getIndexStates(); // ensure the states are initialized
Lines 962-971 Link Here
962
	}
1018
	}
963
1019
964
}
1020
}
965
public void updateParticipant(IPath indexLocation, IPath containerPath) {
1021
public void updateParticipant(IPath indexPath, IPath containerPath) {
966
	if (this.participantsContainers == null) {
1022
	if (this.participantsContainers == null) {
967
		readParticipantsIndexNamesFile();
1023
		readParticipantsIndexNamesFile();
968
	} 
1024
	}
1025
	IndexLocation indexLocation = new FileIndexLocation(indexPath.toFile(), true);
969
	if (this.participantsContainers.get(indexLocation) == null) {
1026
	if (this.participantsContainers.get(indexLocation) == null) {
970
		this.participantsContainers.put(indexLocation, containerPath);
1027
		this.participantsContainers.put(indexLocation, containerPath);
971
		this.participantUpdated  = true;
1028
		this.participantUpdated  = true;
Lines 1005-1010 Link Here
1005
		}
1062
		}
1006
	}
1063
	}
1007
}
1064
}
1065
private void writeIndexMapFile() {
1066
	BufferedWriter writer = null;
1067
	try {
1068
		writer = new BufferedWriter(new FileWriter(this.indexNamesMapFile));
1069
		writer.write(DiskIndex.SIGNATURE);
1070
		writer.write('\n');
1071
		Object[] keys = this.indexStates.keyTable;
1072
		Object[] states = this.indexStates.valueTable;
1073
		for (int i = 0, l = states.length; i < l; i++) {
1074
			IndexLocation location = (IndexLocation)keys[i];
1075
			if (location != null && states[i] == REUSE_STATE) {
1076
				IPath container = (IPath)this.indexLocations.keyForValue(location);
1077
				if (container != null) {
1078
					writer.write(location.toString());
1079
					writer.write('\n');
1080
					writer.write(container.toOSString());
1081
					writer.write('\n');
1082
				}
1083
			}
1084
		}
1085
	} catch (IOException ignored) {
1086
		if (VERBOSE)
1087
			Util.verbose("Failed to write saved index file names", System.err); //$NON-NLS-1$
1088
	} finally {
1089
		if (writer != null) {
1090
			try {
1091
				writer.close();
1092
			} catch (IOException e) {
1093
				// ignore
1094
			}
1095
		}
1096
	}
1097
}
1008
private void writeParticipantsIndexNamesFile() {
1098
private void writeParticipantsIndexNamesFile() {
1009
	BufferedWriter writer = null;
1099
	BufferedWriter writer = null;
1010
	try {
1100
	try {
Lines 1014-1022 Link Here
1014
		Object[] indexFiles = this.participantsContainers.keyTable;
1104
		Object[] indexFiles = this.participantsContainers.keyTable;
1015
		Object[] containers = this.participantsContainers.valueTable;
1105
		Object[] containers = this.participantsContainers.valueTable;
1016
		for (int i = 0, l = indexFiles.length; i < l; i++) {
1106
		for (int i = 0, l = indexFiles.length; i < l; i++) {
1017
			IPath indexFile = (IPath)indexFiles[i];
1107
			IndexLocation indexFile = (IndexLocation)indexFiles[i];
1018
			if (indexFile != null) {
1108
			if (indexFile != null) {
1019
				writer.write(indexFile.toOSString());
1109
				writer.write(indexFile.getIndexFile().getPath());
1020
				writer.write('\n');
1110
				writer.write('\n');
1021
				writer.write(((IPath)containers[i]).toOSString());
1111
				writer.write(((IPath)containers[i]).toOSString());
1022
				writer.write('\n');
1112
				writer.write('\n');
Lines 1046-1054 Link Here
1046
		Object[] keys = this.indexStates.keyTable;
1136
		Object[] keys = this.indexStates.keyTable;
1047
		Object[] states = this.indexStates.valueTable;
1137
		Object[] states = this.indexStates.valueTable;
1048
		for (int i = 0, l = states.length; i < l; i++) {
1138
		for (int i = 0, l = states.length; i < l; i++) {
1049
			IPath key = (IPath) keys[i];
1139
			IndexLocation key = (IndexLocation) keys[i];
1050
			if (key != null && !key.isEmpty() && states[i] == SAVED_STATE) {
1140
			if (key != null && states[i] == SAVED_STATE) {
1051
				writer.write(key.lastSegment());
1141
				writer.write(key.fileName());
1052
				writer.write('\n');
1142
				writer.write('\n');
1053
			}
1143
			}
1054
		}
1144
		}
(-)a/org.eclipse.jdt.core/search/org/eclipse/jdt/internal/core/search/matching/ClassFileMatchLocator.java (-13 / +4 lines)
Lines 1-5 Link Here
1
/*******************************************************************************
1
/*******************************************************************************
2
 * Copyright (c) 2000, 2011 IBM Corporation and others.
2
 * Copyright (c) 2000, 2012 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 90-95 Link Here
90
	return true;
90
	return true;
91
}
91
}
92
private boolean checkStandardAnnotations(long annotationTagBits, TypeReferencePattern pattern) {
92
private boolean checkStandardAnnotations(long annotationTagBits, TypeReferencePattern pattern) {
93
	if ((annotationTagBits & TagBits.AllStandardAnnotationsMask) == 0) {
94
		return false;
95
	}
93
	if ((annotationTagBits & TagBits.AnnotationTargetMASK) != 0) {
96
	if ((annotationTagBits & TagBits.AnnotationTargetMASK) != 0) {
94
		char[][] compoundName = TypeConstants.JAVA_LANG_ANNOTATION_TARGET;
97
		char[][] compoundName = TypeConstants.JAVA_LANG_ANNOTATION_TARGET;
95
		if (checkAnnotationTypeReference(CharOperation.concatWith(compoundName, '.'), pattern) ||
98
		if (checkAnnotationTypeReference(CharOperation.concatWith(compoundName, '.'), pattern) ||
Lines 142-159 Link Here
142
	}
145
	}
143
	if ((annotationTagBits & TagBits.AnnotationPolymorphicSignature) != 0) {
146
	if ((annotationTagBits & TagBits.AnnotationPolymorphicSignature) != 0) {
144
		char[][] compoundName = TypeConstants.JAVA_LANG_INVOKE_METHODHANDLE_$_POLYMORPHICSIGNATURE;
147
		char[][] compoundName = TypeConstants.JAVA_LANG_INVOKE_METHODHANDLE_$_POLYMORPHICSIGNATURE;
145
		if (checkAnnotationTypeReference(CharOperation.concatWith(compoundName, '.'), pattern)) {
146
			return true;
147
		}
148
	}
149
	if ((annotationTagBits & TagBits.AnnotationPostConstruct) != 0) {
150
		char[][] compoundName = TypeConstants.JAVAX_ANNOTATION_POSTCONSTRUCT;
151
		if (checkAnnotationTypeReference(CharOperation.concatWith(compoundName, '.'), pattern)) {
152
			return true;
153
		}
154
	}
155
	if ((annotationTagBits & TagBits.AnnotationPreDestroy) != 0) {
156
		char[][] compoundName = TypeConstants.JAVAX_ANNOTATION_PREDESTROY;
157
		if (checkAnnotationTypeReference(CharOperation.concatWith(compoundName, '.'), pattern)) {
148
		if (checkAnnotationTypeReference(CharOperation.concatWith(compoundName, '.'), pattern)) {
158
			return true;
149
			return true;
159
		}
150
		}
(-)a/org.eclipse.jdt.core/search/org/eclipse/jdt/internal/core/search/matching/MatchLocator.java (-8 / +71 lines)
Lines 1-5 Link Here
1
/*******************************************************************************
1
/*******************************************************************************
2
 * Copyright (c) 2000, 2011 IBM Corporation and others.
2
 * Copyright (c) 2000, 2012 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 70-78 Link Here
70
import org.eclipse.jdt.internal.core.SearchableEnvironment;
70
import org.eclipse.jdt.internal.core.SearchableEnvironment;
71
import org.eclipse.jdt.internal.core.SourceMapper;
71
import org.eclipse.jdt.internal.core.SourceMapper;
72
import org.eclipse.jdt.internal.core.SourceMethod;
72
import org.eclipse.jdt.internal.core.SourceMethod;
73
import org.eclipse.jdt.internal.core.SourceType;
73
import org.eclipse.jdt.internal.core.SourceTypeElementInfo;
74
import org.eclipse.jdt.internal.core.SourceTypeElementInfo;
74
import org.eclipse.jdt.internal.core.index.Index;
75
import org.eclipse.jdt.internal.core.index.Index;
75
import org.eclipse.jdt.internal.core.search.*;
76
import org.eclipse.jdt.internal.core.search.*;
77
import org.eclipse.jdt.internal.core.search.indexing.IIndexConstants;
78
import org.eclipse.jdt.internal.core.util.ASTNodeFinder;
76
import org.eclipse.jdt.internal.core.util.HandleFactory;
79
import org.eclipse.jdt.internal.core.util.HandleFactory;
77
import org.eclipse.jdt.internal.core.util.Util;
80
import org.eclipse.jdt.internal.core.util.Util;
78
81
Lines 145-150 Link Here
145
HashSet methodHandles;
148
HashSet methodHandles;
146
149
147
private final boolean searchPackageDeclaration;
150
private final boolean searchPackageDeclaration;
151
private int sourceStartOfMethodToRetain;
152
private int sourceEndOfMethodToRetain;
148
153
149
public static class WorkingCopyDocument extends JavaSearchDocument {
154
public static class WorkingCopyDocument extends JavaSearchDocument {
150
	public org.eclipse.jdt.core.ICompilationUnit workingCopy;
155
	public org.eclipse.jdt.core.ICompilationUnit workingCopy;
Lines 293-298 Link Here
293
		this.searchPackageDeclaration = ((OrPattern)pattern).hasPackageDeclaration();
298
		this.searchPackageDeclaration = ((OrPattern)pattern).hasPackageDeclaration();
294
	} else {
299
	} else {
295
		this.searchPackageDeclaration = false;
300
		this.searchPackageDeclaration = false;
301
	}
302
	if (pattern instanceof MethodPattern) {
303
	    IType type = ((MethodPattern) pattern).declaringType;
304
	    if (type != null && !type.isBinary()) {
305
	    	SourceType sourceType = (SourceType) type;
306
	    	IMember local = sourceType.getOuterMostLocalContext();
307
	    	if (local instanceof IMethod) { // remember this method's range so we don't purge its statements.
308
	    		try {
309
	    			ISourceRange range = local.getSourceRange();
310
	    			this.sourceStartOfMethodToRetain  = range.getOffset();
311
	    			this.sourceEndOfMethodToRetain = this.sourceStartOfMethodToRetain + range.getLength() - 1; // offset is 0 based.
312
	    		} catch (JavaModelException e) {
313
	    			// drop silently. 
314
	    		}
315
	    	}
316
	    }
296
	}
317
	}
297
}
318
}
298
/**
319
/**
Lines 876-885 Link Here
876
	// Get binding from unit scope
897
	// Get binding from unit scope
877
	char[][] compoundName = CharOperation.splitOn('.', typeName);
898
	char[][] compoundName = CharOperation.splitOn('.', typeName);
878
	TypeBinding typeBinding = this.unitScope.getType(compoundName, compoundName.length);
899
	TypeBinding typeBinding = this.unitScope.getType(compoundName, compoundName.length);
900
	if (typeBinding == null || !typeBinding.isValidBinding()) {
901
		typeBinding = this.lookupEnvironment.getType(compoundName);
902
	}
879
	this.bindings.put(typeKey, typeBinding);
903
	this.bindings.put(typeKey, typeBinding);
880
	return typeBinding.isValidBinding() ? typeBinding : null;
904
	return typeBinding != null && typeBinding.isValidBinding() ? typeBinding : null;
881
}
905
}
882
public MethodBinding getMethodBinding(MethodPattern methodPattern) {
906
public MethodBinding getMethodBinding(MethodPattern methodPattern) {
907
    MethodBinding methodBinding = getMethodBinding0(methodPattern);
908
    if (methodBinding != null)
909
    	return methodBinding; // known to be valid.
910
    // special handling for methods of anonymous/local types. Since these cannot be looked up in the environment the usual way ...
911
    if (methodPattern.focus instanceof SourceMethod) {
912
    	char[] typeName = PatternLocator.qualifiedPattern(methodPattern.declaringSimpleName, methodPattern.declaringQualification);
913
    	if (CharOperation.indexOf(IIndexConstants.ONE_STAR, typeName, true) >= 0) { // See org.eclipse.jdt.core.search.SearchPattern.enclosingTypeNames(IType)
914
    		IType type = methodPattern.declaringType;
915
    		IType enclosingType = type.getDeclaringType();
916
    		while (enclosingType != null) {
917
    			type = enclosingType;
918
    			enclosingType = type.getDeclaringType();
919
    		}
920
    		typeName = type.getFullyQualifiedName().toCharArray();
921
    		TypeBinding declaringTypeBinding = getType(typeName, typeName);
922
    		if (declaringTypeBinding instanceof SourceTypeBinding) {
923
    			SourceTypeBinding sourceTypeBinding = ((SourceTypeBinding) declaringTypeBinding);
924
    			ClassScope skope = sourceTypeBinding.scope;
925
    			if (skope != null) {
926
    				CompilationUnitDeclaration unit = skope.referenceCompilationUnit();
927
    				if (unit != null) {
928
    					AbstractMethodDeclaration amd = new ASTNodeFinder(unit).findMethod((IMethod) methodPattern.focus);
929
    					if (amd != null && amd.binding != null && amd.binding.isValidBinding()) {
930
    						this.bindings.put(methodPattern, amd.binding);
931
    						return amd.binding;
932
    					}
933
    				}
934
    			}
935
    		}
936
    	}
937
    }
938
	return null;
939
}
940
private MethodBinding getMethodBinding0(MethodPattern methodPattern) {
883
	if (this.unitScope == null) return null;
941
	if (this.unitScope == null) return null;
884
	// Try to get binding from cache
942
	// Try to get binding from cache
885
	Binding binding = (Binding) this.bindings.get(methodPattern);
943
	Binding binding = (Binding) this.bindings.get(methodPattern);
Lines 990-996 Link Here
990
			this.options,
1048
			this.options,
991
			new DefaultProblemFactory());
1049
			new DefaultProblemFactory());
992
	this.lookupEnvironment = new LookupEnvironment(this, this.options, problemReporter, this.nameEnvironment);
1050
	this.lookupEnvironment = new LookupEnvironment(this, this.options, problemReporter, this.nameEnvironment);
993
1051
	this.lookupEnvironment.mayTolerateMissingType = true;
994
	this.parser = MatchLocatorParser.createParser(problemReporter, this);
1052
	this.parser = MatchLocatorParser.createParser(problemReporter, this);
995
1053
996
	// basic parser needs also to be reset as project options may have changed
1054
	// basic parser needs also to be reset as project options may have changed
Lines 1351-1357 Link Here
1351
}
1409
}
1352
//*/
1410
//*/
1353
protected IType lookupType(ReferenceBinding typeBinding) {
1411
protected IType lookupType(ReferenceBinding typeBinding) {
1354
	if (typeBinding == null) return null;
1412
	if (typeBinding == null || !typeBinding.isValidBinding()) return null;
1355
1413
1356
	char[] packageName = typeBinding.qualifiedPackageName();
1414
	char[] packageName = typeBinding.qualifiedPackageName();
1357
	IPackageFragment[] pkgs = this.nameLookup.findPackageFragments(
1415
	IPackageFragment[] pkgs = this.nameLookup.findPackageFragments(
Lines 1692-1705 Link Here
1692
			for (int j = 0, length = methods.length; j < length; j++) {
1750
			for (int j = 0, length = methods.length; j < length; j++) {
1693
				AbstractMethodDeclaration method = methods[j];
1751
				AbstractMethodDeclaration method = methods[j];
1694
				if (!this.currentPossibleMatch.nodeSet.hasPossibleNodes(method.declarationSourceStart, method.declarationSourceEnd)) {
1752
				if (!this.currentPossibleMatch.nodeSet.hasPossibleNodes(method.declarationSourceStart, method.declarationSourceEnd)) {
1695
					method.statements = null;
1753
					if (this.sourceStartOfMethodToRetain != method.declarationSourceStart || this.sourceEndOfMethodToRetain != method.declarationSourceEnd) { // approximate, but no big deal
1696
					method.javadoc = null;
1754
						method.statements = null;
1755
						method.javadoc = null;
1756
					}
1697
				}
1757
				}
1698
			}
1758
			}
1699
		} else {
1759
		} else {
1700
			for (int j = 0, length = methods.length; j < length; j++) {
1760
			for (int j = 0, length = methods.length; j < length; j++) {
1701
				methods[j].statements = null;
1761
				AbstractMethodDeclaration method = methods[j];
1702
				methods[j].javadoc = null;
1762
				if (this.sourceStartOfMethodToRetain != method.declarationSourceStart || this.sourceEndOfMethodToRetain != method.declarationSourceEnd) { // approximate, but no big deal
1763
					method.statements = null;
1764
					method.javadoc = null;
1765
				}
1703
			}
1766
			}
1704
		}
1767
		}
1705
	}
1768
	}
(-)a/org.eclipse.jdt.core/search/org/eclipse/jdt/internal/core/search/matching/MethodLocator.java (-2 / +20 lines)
Lines 1-5 Link Here
1
/*******************************************************************************
1
/*******************************************************************************
2
 * Copyright (c) 2000, 2011 IBM Corporation and others.
2
 * Copyright (c) 2000, 2012 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 31-36 Link Here
31
//extra reference info
31
//extra reference info
32
public char[][][] allSuperDeclaringTypeNames;
32
public char[][][] allSuperDeclaringTypeNames;
33
33
34
private MatchLocator matchLocator;
34
//method declarations which parameters verification fail
35
//method declarations which parameters verification fail
35
private HashMap methodDeclarationsWithInvalidParam = new HashMap();
36
private HashMap methodDeclarationsWithInvalidParam = new HashMap();
36
37
Lines 82-87 Link Here
82
				locator,
83
				locator,
83
				this.pattern.declaringType,
84
				this.pattern.declaringType,
84
				locator.progressMonitor).collect();
85
				locator.progressMonitor).collect();
86
		this.matchLocator = locator;	
85
	} catch (JavaModelException e) {
87
	} catch (JavaModelException e) {
86
		// inaccurate matches will be found
88
		// inaccurate matches will be found
87
	}
89
	}
Lines 251-257 Link Here
251
			// return inaccurate match for ambiguous call (bug 80890)
253
			// return inaccurate match for ambiguous call (bug 80890)
252
			return INACCURATE_MATCH;
254
			return INACCURATE_MATCH;
253
		}
255
		}
254
256
		boolean foundTypeVariable = false;
255
		// verify each parameter
257
		// verify each parameter
256
		for (int i = 0; i < parameterCount; i++) {
258
		for (int i = 0; i < parameterCount; i++) {
257
			TypeBinding argType = method.parameters[i];
259
			TypeBinding argType = method.parameters[i];
Lines 272-277 Link Here
272
						// Do not consider match as impossible while finding declarations and source level >= 1.5
274
						// Do not consider match as impossible while finding declarations and source level >= 1.5
273
					 	// (see  bugs https://bugs.eclipse.org/bugs/show_bug.cgi?id=79990, 96761, 96763)
275
					 	// (see  bugs https://bugs.eclipse.org/bugs/show_bug.cgi?id=79990, 96761, 96763)
274
						newLevel = level;
276
						newLevel = level;
277
					} else if (argType.isTypeVariable()) {
278
						newLevel = level;
279
						foundTypeVariable = true;
275
					} else {
280
					} else {
276
						return IMPOSSIBLE_MATCH;
281
						return IMPOSSIBLE_MATCH;
277
					}
282
					}
Lines 279-288 Link Here
279
				level = newLevel; // can only be downgraded
284
				level = newLevel; // can only be downgraded
280
			}
285
			}
281
		}
286
		}
287
		if (foundTypeVariable) {
288
			if (!method.isStatic() && !method.isPrivate()) {
289
				// https://bugs.eclipse.org/bugs/show_bug.cgi?id=123836, No point in textually comparing type variables, captures etc with concrete types. 
290
				MethodBinding focusMethodBinding = this.matchLocator.getMethodBinding(this.pattern);
291
				if (focusMethodBinding != null) {
292
					if (matchOverriddenMethod(focusMethodBinding.declaringClass, focusMethodBinding, method)) {
293
						return ACCURATE_MATCH;
294
					}
295
				}
296
			} 
297
			return IMPOSSIBLE_MATCH;
298
		}
282
	}
299
	}
283
300
284
	return level;
301
	return level;
285
}
302
}
303
// This works for only methods of parameterized types.
286
private boolean matchOverriddenMethod(ReferenceBinding type, MethodBinding method, MethodBinding matchMethod) {
304
private boolean matchOverriddenMethod(ReferenceBinding type, MethodBinding method, MethodBinding matchMethod) {
287
	if (type == null || this.pattern.selector == null) return false;
305
	if (type == null || this.pattern.selector == null) return false;
288
306
(-)a/org.eclipse.jdt.core/search/org/eclipse/jdt/internal/core/search/matching/PossibleMatch.java (-1 / +4 lines)
Lines 1-5 Link Here
1
/*******************************************************************************
1
/*******************************************************************************
2
 * Copyright (c) 2000, 2009 IBM Corporation and others.
2
 * Copyright (c) 2000, 2012 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 154-159 Link Here
154
		hashCode += CharOperation.hashCode(this.compoundName[i]);
154
		hashCode += CharOperation.hashCode(this.compoundName[i]);
155
	return hashCode;
155
	return hashCode;
156
}
156
}
157
public boolean ignoreOptionalProblems() {
158
	return false;
159
}
157
void setSimilarMatch(PossibleMatch possibleMatch) {
160
void setSimilarMatch(PossibleMatch possibleMatch) {
158
	// source does not matter on similar match as it is read on
161
	// source does not matter on similar match as it is read on
159
	// the first stored possible match
162
	// the first stored possible match

Return to bug 359724